repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/join.rs
crates/nu_plugin_polars/src/dataframe/command/data/join.rs
use crate::{ PolarsPlugin, dataframe::values::{Column, NuDataFrame, NuExpression, NuLazyFrame}, values::{CustomValueSupport, PolarsPluginType}, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use polars::{ df, prelude::{Expr, JoinCoalesce, JoinType}, }; #[derive(Clone)] pub struct LazyJoin; impl PluginCommand for LazyJoin { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars join" } fn description(&self) -> &str { "Joins a lazy frame with other lazy frame." } fn signature(&self) -> Signature { Signature::build(self.name()) .required("other", SyntaxShape::Any, "LazyFrame to join with") .optional("left_on", SyntaxShape::Any, "Left column(s) to join on") .optional("right_on", SyntaxShape::Any, "Right column(s) to join on") .switch( "inner", "inner joining between lazyframes (default)", Some('i'), ) .switch("left", "left join between lazyframes", Some('l')) .switch("full", "full join between lazyframes", Some('f')) .switch("cross", "cross join between lazyframes", Some('c')) .switch("coalesce-columns", "Sets the join coalesce strategy to colesce columns. Most useful when used with --full, which will not otherwise coalesce.", None) .named( "suffix", SyntaxShape::String, "Suffix to use on columns with same name", Some('s'), ) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("lazyframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Join two lazy dataframes", example: r#"let df_a = ([[a b c];[1 "a" 0] [2 "b" 1] [1 "c" 2] [1 "c" 3]] | polars into-lazy) let df_b = ([["foo" "bar" "ham"];[1 "a" "let"] [2 "c" "var"] [3 "c" "const"]] | polars into-lazy) $df_a | polars join $df_b a foo | polars collect"#, result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![ Value::test_int(1), Value::test_int(2), Value::test_int(1), Value::test_int(1), ], ), Column::new( "b".to_string(), vec![ Value::test_string("a"), Value::test_string("b"), Value::test_string("c"), Value::test_string("c"), ], ), Column::new( "c".to_string(), vec![ Value::test_int(0), Value::test_int(1), Value::test_int(2), Value::test_int(3), ], ), Column::new( "bar".to_string(), vec![ Value::test_string("a"), Value::test_string("c"), Value::test_string("a"), Value::test_string("a"), ], ), Column::new( "ham".to_string(), vec![ Value::test_string("let"), Value::test_string("var"), Value::test_string("let"), Value::test_string("let"), ], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Join one eager dataframe with a lazy dataframe", example: r#"let df_a = ([[a b c];[1 "a" 0] [2 "b" 1] [1 "c" 2] [1 "c" 3]] | polars into-df) let df_b = ([["foo" "bar" "ham"];[1 "a" "let"] [2 "c" "var"] [3 "c" "const"]] | polars into-lazy) $df_a | polars join $df_b a foo"#, result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![ Value::test_int(1), Value::test_int(2), Value::test_int(1), Value::test_int(1), ], ), Column::new( "b".to_string(), vec![ Value::test_string("a"), Value::test_string("b"), Value::test_string("c"), Value::test_string("c"), ], ), Column::new( "c".to_string(), vec![ Value::test_int(0), Value::test_int(1), Value::test_int(2), Value::test_int(3), ], ), Column::new( "bar".to_string(), vec![ Value::test_string("a"), Value::test_string("c"), Value::test_string("a"), Value::test_string("a"), ], ), Column::new( "ham".to_string(), vec![ Value::test_string("let"), Value::test_string("var"), Value::test_string("let"), Value::test_string("let"), ], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Perform a full join of two dataframes and coalesce columns", example: r#"let table1 = [[A B]; ["common" "common"] ["table1" "only"]] | polars into-df let table2 = [[A C]; ["common" "common"] ["table2" "only"]] | polars into-df $table1 | polars join -f $table2 --coalesce-columns A A"#, result: Some( NuDataFrame::new( false, df!( "A" => [Some("common"), Some("table2"), Some("table1")], "B" => [Some("common"), None, Some("only")], "C" => [Some("common"), Some("only"), None] ) .expect("Should have created a DataFrame"), ) .into_value(Span::test_data()), ), }, Example { description: "Join one eager dataframe with another using a cross join", example: r#"let tokens = [[monopoly_token]; [hat] [shoe] [boat]] | polars into-df let players = [[name, cash]; [Alice, 78] [Bob, 135]] | polars into-df $players | polars select (polars col name) | polars join --cross $tokens | polars collect"#, result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "name".to_string(), vec![ Value::test_string("Alice"), Value::test_string("Alice"), Value::test_string("Alice"), Value::test_string("Bob"), Value::test_string("Bob"), Value::test_string("Bob"), ], ), Column::new( "monopoly_token".to_string(), vec![ Value::test_string("hat"), Value::test_string("shoe"), Value::test_string("boat"), Value::test_string("hat"), Value::test_string("shoe"), Value::test_string("boat"), ], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let left = call.has_flag("left")?; let full = call.has_flag("full")?; let cross = call.has_flag("cross")?; let how = if left { JoinType::Left } else if full { JoinType::Full } else if cross { JoinType::Cross } else { JoinType::Inner }; let other: Value = call.req(0)?; let other = NuLazyFrame::try_from_value_coerce(plugin, &other)?; let other = other.to_polars(); let left_on_opt: Option<Value> = call.opt(1)?; let left_on = match left_on_opt { Some(left_on_value) if left || left_on_opt.is_some() => { NuExpression::extract_exprs(plugin, left_on_value)? } _ => vec![], }; let right_on_opt: Option<Value> = call.opt(2)?; let right_on = match right_on_opt { Some(right_on_value) if full || right_on_opt.is_some() => { NuExpression::extract_exprs(plugin, right_on_value)? } _ => vec![], }; if left_on.len() != right_on.len() { let right_on: Value = call.req(2)?; Err(ShellError::IncompatibleParametersSingle { msg: "The right column list has a different size to the left column list".into(), span: right_on.span(), })?; } // Checking that both list of expressions are made out of col expressions or strings for (index, list) in &[(1usize, &left_on), (2, &left_on)] { if list.iter().any(|expr| !matches!(expr, Expr::Column(..))) { let value: Value = call.req(*index)?; Err(ShellError::IncompatibleParametersSingle { msg: "Expected only a string, col expressions or list of strings".into(), span: value.span(), })?; } } let suffix: Option<String> = call.get_flag("suffix")?; let suffix = suffix.unwrap_or_else(|| "_x".into()); let value = input.into_value(call.head)?; let lazy = NuLazyFrame::try_from_value_coerce(plugin, &value)?; let from_eager = lazy.from_eager; let lazy = lazy.to_polars(); let coalesce = if call.has_flag("coalesce-columns")? { JoinCoalesce::CoalesceColumns } else { JoinCoalesce::default() }; let lazy = if cross { lazy.join_builder() .with(other) .coalesce(coalesce) .left_on(vec![]) .right_on(vec![]) .how(how) .force_parallel(true) .suffix(suffix) .finish() } else { lazy.join_builder() .with(other) .coalesce(coalesce) .left_on(left_on) .right_on(right_on) .how(how) .force_parallel(true) .suffix(suffix) .finish() }; let lazy = NuLazyFrame::new(from_eager, lazy); lazy.to_pipeline_data(plugin, engine, call.head) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&LazyJoin) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/alias.rs
crates/nu_plugin_polars/src/dataframe/command/data/alias.rs
use crate::{PolarsPlugin, values::CustomValueSupport}; use crate::values::{NuExpression, PolarsPluginType}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, Signature, SyntaxShape, Value, record, }; #[derive(Clone)] pub struct ExprAlias; impl PluginCommand for ExprAlias { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars as" } fn description(&self) -> &str { "Creates an alias expression." } fn signature(&self) -> Signature { Signature::build(self.name()) .required( "Alias name", SyntaxShape::String, "Alias name for the expression", ) .input_output_type( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ) .category(Category::Custom("expression".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Creates and alias expression", example: "polars col a | polars as new_a | polars into-nu", result: { let record = Value::test_record(record! { "expr" => Value::test_record(record! { "expr" => Value::test_string("column"), "value" => Value::test_string("a"), }), "alias" => Value::test_string("new_a"), }); Some(record) }, }] } fn search_terms(&self) -> Vec<&str> { vec!["aka", "abbr", "otherwise"] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let alias: String = call.req(0)?; let expr = NuExpression::try_from_pipeline(plugin, input, call.head)?; let expr: NuExpression = expr.into_polars().alias(alias.as_str()).into(); expr.to_pipeline_data(plugin, engine, call.head) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), nu_protocol::ShellError> { test_polars_plugin_command(&ExprAlias) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/explode.rs
crates/nu_plugin_polars/src/dataframe/command/data/explode.rs
use std::sync::Arc; use crate::PolarsPlugin; use crate::dataframe::values::{Column, NuDataFrame, NuExpression, NuLazyFrame}; use crate::values::{CustomValueSupport, PolarsPluginObject, PolarsPluginType}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use polars::prelude::{PlSmallStr, Selector}; #[derive(Clone)] pub struct LazyExplode; impl PluginCommand for LazyExplode { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars explode" } fn description(&self) -> &str { "Explodes a dataframe or creates a explode expression." } fn signature(&self) -> Signature { Signature::build(self.name()) .rest( "columns", SyntaxShape::String, "columns to explode, only applicable for dataframes", ) .input_output_types(vec![ ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("lazyframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Explode the specified dataframe", example: "[[id name hobbies]; [1 Mercy [Cycling Knitting]] [2 Bob [Skiing Football]]] | polars into-df | polars explode hobbies | polars collect | polars sort-by [id, name]", result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "id".to_string(), vec![ Value::test_int(1), Value::test_int(1), Value::test_int(2), Value::test_int(2), ], ), Column::new( "name".to_string(), vec![ Value::test_string("Mercy"), Value::test_string("Mercy"), Value::test_string("Bob"), Value::test_string("Bob"), ], ), Column::new( "hobbies".to_string(), vec![ Value::test_string("Cycling"), Value::test_string("Knitting"), Value::test_string("Skiing"), Value::test_string("Football"), ], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Select a column and explode the values", example: "[[id name hobbies]; [1 Mercy [Cycling Knitting]] [2 Bob [Skiing Football]]] | polars into-df | polars select (polars col hobbies | polars explode)", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "hobbies".to_string(), vec![ Value::test_string("Cycling"), Value::test_string("Knitting"), Value::test_string("Skiing"), Value::test_string("Football"), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); explode(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } pub(crate) fn explode( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => { let lazy = df.lazy(); explode_lazy(plugin, engine, call, lazy) } PolarsPluginObject::NuLazyFrame(lazy) => explode_lazy(plugin, engine, call, lazy), PolarsPluginObject::NuExpression(expr) => explode_expr(plugin, engine, call, expr), _ => Err(ShellError::CantConvert { to_type: "dataframe or expression".into(), from_type: value.get_type().to_string(), span: call.head, help: None, }), } } pub(crate) fn explode_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, ) -> Result<PipelineData, ShellError> { let columns = call .positional .iter() .map(|param| param.as_str().map(|s| s.to_string())) .map(|s_result| s_result.map(|ref s| PlSmallStr::from_str(s))) .collect::<Result<Vec<PlSmallStr>, ShellError>>()?; // todo - refactor to add selector support let columns = Arc::from(columns); let selector = Selector::ByName { names: columns, strict: true, }; let exploded = lazy.to_polars().explode(selector); let lazy = NuLazyFrame::from(exploded); lazy.to_pipeline_data(plugin, engine, call.head) } pub(crate) fn explode_expr( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, expr: NuExpression, ) -> Result<PipelineData, ShellError> { let expr: NuExpression = expr.into_polars().explode().into(); expr.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&LazyExplode) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/cast.rs
crates/nu_plugin_polars/src/dataframe/command/data/cast.rs
use crate::{ PolarsPlugin, dataframe::values::{NuExpression, NuLazyFrame, str_to_dtype}, values::{CustomValueSupport, PolarsPluginObject, PolarsPluginType, cant_convert_err}, }; use crate::values::NuDataFrame; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, record, }; use polars::prelude::*; #[derive(Clone)] pub struct CastDF; impl PluginCommand for CastDF { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars cast" } fn description(&self) -> &str { "Cast a column to a different dtype." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .required( "dtype", SyntaxShape::String, "The dtype to cast the column to", ) .optional( "column", SyntaxShape::String, "The column to cast. Required when used with a dataframe.", ) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Cast a column in a dataframe to a different dtype", example: "[[a b]; [1 2] [3 4]] | polars into-df | polars cast u8 a | polars schema", result: Some(Value::record( record! { "a" => Value::string("u8", Span::test_data()), "b" => Value::string("i64", Span::test_data()), }, Span::test_data(), )), }, Example { description: "Cast a column in a lazy dataframe to a different dtype", example: "[[a b]; [1 2] [3 4]] | polars into-df | polars into-lazy | polars cast u8 a | polars schema", result: Some(Value::record( record! { "a" => Value::string("u8", Span::test_data()), "b" => Value::string("i64", Span::test_data()), }, Span::test_data(), )), }, Example { description: "Cast a column in a expression to a different dtype", example: r#"[[a b]; [1 2] [1 4]] | polars into-df | polars group-by a | polars agg [ (polars col b | polars cast u8 | polars min | polars as "b_min") ] | polars schema"#, result: None, }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuLazyFrame(lazy) => { let (dtype, column_nm) = df_args(call)?; command_lazy(plugin, engine, call, column_nm, dtype, lazy) } PolarsPluginObject::NuDataFrame(df) => { let (dtype, column_nm) = df_args(call)?; command_eager(plugin, engine, call, column_nm, dtype, df) } PolarsPluginObject::NuExpression(expr) => { let dtype: String = call.req(0)?; let dtype = str_to_dtype(&dtype, call.head)?; let expr: NuExpression = expr.into_polars().cast(dtype).into(); expr.to_pipeline_data(plugin, engine, call.head) } _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn df_args(call: &EvaluatedCall) -> Result<(DataType, String), ShellError> { let dtype = dtype_arg(call)?; let column_nm: String = call.opt(1)?.ok_or(ShellError::MissingParameter { param_name: "column_name".into(), span: call.head, })?; Ok((dtype, column_nm)) } fn dtype_arg(call: &EvaluatedCall) -> Result<DataType, ShellError> { let dtype: String = call.req(0)?; str_to_dtype(&dtype, call.head) } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, column_nm: String, dtype: DataType, lazy: NuLazyFrame, ) -> Result<PipelineData, ShellError> { let column = col(&column_nm).cast(dtype); let lazy = lazy.to_polars().with_columns(&[column]); let lazy = NuLazyFrame::new(false, lazy); lazy.to_pipeline_data(plugin, engine, call.head) } fn command_eager( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, column_nm: String, dtype: DataType, nu_df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let mut df = (*nu_df.df).clone(); let column = df .column(&column_nm) .map_err(|e| ShellError::GenericError { error: format!("{e}"), msg: "".into(), span: Some(call.head), help: None, inner: vec![], })?; let casted = column.cast(&dtype).map_err(|e| ShellError::GenericError { error: format!("{e}"), msg: "".into(), span: Some(call.head), help: None, inner: vec![], })?; let _ = df .with_column(casted) .map_err(|e| ShellError::GenericError { error: format!("{e}"), msg: "".into(), span: Some(call.head), help: None, inner: vec![], })?; let df = NuDataFrame::new(false, df); df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&CastDF) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/query_df.rs
crates/nu_plugin_polars/src/dataframe/command/data/query_df.rs
use super::sql_context::SQLContext; use crate::PolarsPlugin; use crate::dataframe::values::Column; use crate::dataframe::values::NuLazyFrame; use crate::values::CustomValueSupport; use crate::values::NuDataFrame; use crate::values::PolarsPluginType; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; // attribution: // sql_context.rs, and sql_expr.rs were copied from polars-sql. thank you. // maybe we should just use the crate at some point but it's not published yet. // https://github.com/pola-rs/polars/tree/master/polars-sql #[derive(Clone)] pub struct QueryDf; impl PluginCommand for QueryDf { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars query" } fn description(&self) -> &str { "Query dataframe using SQL. Note: The dataframe is always named 'df' in your query's from clause." } fn signature(&self) -> Signature { Signature::build(self.name()) .required("sql", SyntaxShape::String, "sql query") .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn search_terms(&self) -> Vec<&str> { vec!["dataframe", "sql", "search"] } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Query dataframe using SQL", example: "[[a b]; [1 2] [3 4]] | polars into-df | polars query 'select a from df'", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "a".to_string(), vec![Value::test_int(1), Value::test_int(3)], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let sql_query: String = call.req(0)?; let df = NuDataFrame::try_from_pipeline_coerce(plugin, input, call.head)?; let mut ctx = SQLContext::new(); ctx.register("df", &df.df); let df_sql = ctx .execute(&sql_query) .map_err(|e| ShellError::GenericError { error: "Dataframe Error".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })?; let lazy = NuLazyFrame::new(!df.from_lazy, df_sql); lazy.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use crate::test::test_polars_plugin_command; use super::*; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&QueryDf) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/qcut.rs
crates/nu_plugin_polars/src/dataframe/command/data/qcut.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{Category, Example, PipelineData, ShellError, Signature, SyntaxShape}; use polars::prelude::PlSmallStr; use crate::{ PolarsPlugin, values::{CustomValueSupport, NuDataFrame, PolarsPluginType}, }; pub struct QCutSeries; impl PluginCommand for QCutSeries { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars qcut" } fn description(&self) -> &str { "Bin continuous values into discrete categories based on their quantiles for a series." } fn signature(&self) -> nu_protocol::Signature { Signature::build(self.name()) .required("quantiles", SyntaxShape::Any, "Either a list of quantile probabilities between 0 and 1 or a positive integer determining the number of bins with uniform probability.") .named( "labels", SyntaxShape::List(Box::new(SyntaxShape::String)), "Names of the categories. The number of labels must be equal to the number of cut points plus one.", Some('l'), ) .switch("left_closed", "Set the intervals to be left-closed instead of right-closed.", Some('c')) .switch("include_breaks", "Include a column with the right endpoint of the bin each observation falls in. This will change the data type of the output from a Categorical to a Struct.", Some('b')) .switch("allow_duplicates", "If set, duplicates in the resulting quantiles are dropped, rather than raising an error. This can happen even with unique probabilities, depending on the data.", Some('d')) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Divide a column into three categories according to pre-defined quantile probabilities.", example: r#"[-2, -1, 0, 1, 2] | polars into-df | polars qcut [0.25, 0.75] --labels ["a", "b", "c"]"#, result: None, }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, nu_protocol::LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(|e| e.into()) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let df = NuDataFrame::try_from_pipeline_coerce(plugin, input, call.head)?; let series = df.as_series(call.head)?; let quantiles = call.req::<Vec<f64>>(0)?; let labels: Option<Vec<PlSmallStr>> = call.get_flag::<Vec<String>>("labels")?.map(|l| { l.into_iter() .map(PlSmallStr::from) .collect::<Vec<PlSmallStr>>() }); let left_closed = call.has_flag("left_closed")?; let include_breaks = call.has_flag("include_breaks")?; let allow_duplicates = call.has_flag("allow_duplicates")?; let new_series = polars_ops::series::qcut( &series, quantiles, labels, left_closed, allow_duplicates, include_breaks, ) .map_err(|e| ShellError::GenericError { error: "Error cutting series".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })?; NuDataFrame::try_from_series(new_series, call.head)?.to_pipeline_data(plugin, engine, call.head) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/cut.rs
crates/nu_plugin_polars/src/dataframe/command/data/cut.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{Category, Example, PipelineData, ShellError, Signature, SyntaxShape}; use polars::prelude::PlSmallStr; use crate::{ PolarsPlugin, values::{CustomValueSupport, NuDataFrame, PolarsPluginType}, }; pub struct CutSeries; impl PluginCommand for CutSeries { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars cut" } fn description(&self) -> &str { "Bin continuous values into discrete categories for a series." } fn signature(&self) -> nu_protocol::Signature { Signature::build(self.name()) .required("breaks", SyntaxShape::Any, "Dataframe that contains a series of unique cut points.") .named( "labels", SyntaxShape::List(Box::new(SyntaxShape::String)), "Names of the categories. The number of labels must be equal to the number of cut points plus one.", Some('l'), ) .switch("left_closed", "Set the intervals to be left-closed instead of right-closed.", Some('c')) .switch("include_breaks", "Include a column with the right endpoint of the bin each observation falls in. This will change the data type of the output from a Categorical to a Struct.", Some('b')) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Divide the column into three categories.", example: r#"[-2, -1, 0, 1, 2] | polars into-df | polars cut [-1, 1] --labels ["a", "b", "c"]"#, result: None, }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, nu_protocol::LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(|e| e.into()) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let df = NuDataFrame::try_from_pipeline_coerce(plugin, input, call.head)?; let series = df.as_series(call.head)?; let breaks = call.req::<Vec<f64>>(0)?; let labels: Option<Vec<PlSmallStr>> = call.get_flag::<Vec<String>>("labels")?.map(|l| { l.into_iter() .map(PlSmallStr::from) .collect::<Vec<PlSmallStr>>() }); let left_closed = call.has_flag("left_closed")?; let include_breaks = call.has_flag("include_breaks")?; let new_series = polars_ops::series::cut(&series, breaks, labels, left_closed, include_breaks) .map_err(|e| ShellError::GenericError { error: "Error cutting series".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })?; NuDataFrame::try_from_series(new_series, call.head)?.to_pipeline_data(plugin, engine, call.head) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/sample.rs
crates/nu_plugin_polars/src/dataframe/command/data/sample.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Spanned, SyntaxShape, Value, }; use polars::prelude::NamedFrom; use polars::series::Series; use crate::{PolarsPlugin, values::CustomValueSupport}; use crate::values::{Column, NuDataFrame, PolarsPluginType}; #[derive(Clone)] pub struct SampleDF; impl PluginCommand for SampleDF { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars sample" } fn description(&self) -> &str { "Create sample dataframe." } fn signature(&self) -> Signature { Signature::build(self.name()) .named( "n-rows", SyntaxShape::Int, "number of rows to be taken from dataframe", Some('n'), ) .named( "fraction", SyntaxShape::Number, "fraction of dataframe to be taken", Some('f'), ) .named( "seed", SyntaxShape::Number, "seed for the selection", Some('s'), ) .switch("replace", "sample with replace", Some('e')) .switch("shuffle", "shuffle sample", Some('u')) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Sample rows from dataframe", example: "[[a b]; [1 2] [3 4]] | polars into-df | polars sample --n-rows 1", result: None, // No expected value because sampling is random }, Example { description: "Shows sample row using fraction and replace", example: "[[a b]; [1 2] [3 4] [5 6]] | polars into-df | polars sample --fraction 0.5 --replace", result: None, // No expected value because sampling is random }, Example { description: "Shows sample row using using predefined seed 1", example: "[[a b]; [1 2] [3 4] [5 6]] | polars into-df | polars sample --seed 1 --n-rows 1", result: Some( NuDataFrame::try_from_columns( vec![ Column::new("a".to_string(), vec![Value::test_int(5)]), Column::new("b".to_string(), vec![Value::test_int(6)]), ], None, ) .expect("should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { command(plugin, engine, call, input).map_err(LabeledError::from) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let rows: Option<Spanned<i64>> = call.get_flag("n-rows")?; let fraction: Option<Spanned<f64>> = call.get_flag("fraction")?; let seed: Option<u64> = call.get_flag::<i64>("seed")?.map(|val| val as u64); let replace: bool = call.has_flag("replace")?; let shuffle: bool = call.has_flag("shuffle")?; let df = NuDataFrame::try_from_pipeline_coerce(plugin, input, call.head)?; let df = match (rows, fraction) { (Some(rows), None) => df .as_ref() .sample_n( &Series::new("s".into(), &[rows.item]), replace, shuffle, seed, ) .map_err(|e| ShellError::GenericError { error: "Error creating sample".into(), msg: e.to_string(), span: Some(rows.span), help: None, inner: vec![], }), (None, Some(frac)) => df .as_ref() .sample_frac( &Series::new("frac".into(), &[frac.item]), replace, shuffle, seed, ) .map_err(|e| ShellError::GenericError { error: "Error creating sample".into(), msg: e.to_string(), span: Some(frac.span), help: None, inner: vec![], }), (Some(_), Some(_)) => Err(ShellError::GenericError { error: "Incompatible flags".into(), msg: "Only one selection criterion allowed".into(), span: Some(call.head), help: None, inner: vec![], }), (None, None) => Err(ShellError::GenericError { error: "No selection".into(), msg: "No selection criterion was found".into(), span: Some(call.head), help: Some("Perhaps you want to use the flag -n or -f".into()), inner: vec![], }), }; let df = NuDataFrame::new(false, df?); df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&SampleDF) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/join_where.rs
crates/nu_plugin_polars/src/dataframe/command/data/join_where.rs
use crate::{ PolarsPlugin, dataframe::values::{Column, NuDataFrame, NuExpression, NuLazyFrame}, values::{CustomValueSupport, PolarsPluginType}, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, Signature, Span, SyntaxShape, Value, }; #[derive(Clone)] pub struct LazyJoinWhere; impl PluginCommand for LazyJoinWhere { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars join-where" } fn description(&self) -> &str { "Joins a lazy frame with other lazy frame based on conditions." } fn signature(&self) -> Signature { Signature::build(self.name()) .required("other", SyntaxShape::Any, "LazyFrame to join with") .required("condition", SyntaxShape::Any, "Condition") .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("lazyframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Join two lazy dataframes with a condition", example: r#"let df_a = ([[name cash];[Alice 5] [Bob 10]] | polars into-lazy) let df_b = ([[item price];[A 3] [B 7] [C 12]] | polars into-lazy) $df_a | polars join-where $df_b ((polars col cash) > (polars col price)) | polars collect"#, result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "name".to_string(), vec![ Value::test_string("Bob"), Value::test_string("Bob"), Value::test_string("Alice"), ], ), Column::new( "cash".to_string(), vec![Value::test_int(10), Value::test_int(10), Value::test_int(5)], ), Column::new( "item".to_string(), vec![ Value::test_string("B"), Value::test_string("A"), Value::test_string("A"), ], ), Column::new( "price".to_string(), vec![Value::test_int(7), Value::test_int(3), Value::test_int(3)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let other: Value = call.req(0)?; let other = NuLazyFrame::try_from_value_coerce(plugin, &other)?; let other = other.to_polars(); let condition: Value = call.req(1)?; let condition = NuExpression::try_from_value(plugin, &condition)?; let condition = condition.into_polars(); let pipeline_value = input.into_value(call.head)?; let lazy = NuLazyFrame::try_from_value_coerce(plugin, &pipeline_value)?; let from_eager = lazy.from_eager; let lazy = lazy.to_polars(); let lazy = lazy .join_builder() .with(other) .force_parallel(true) .join_where(vec![condition]); let lazy = NuLazyFrame::new(from_eager, lazy); lazy.to_pipeline_data(plugin, engine, call.head) .map_err(LabeledError::from) } } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), nu_protocol::ShellError> { test_polars_plugin_command(&LazyJoinWhere) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/with_column.rs
crates/nu_plugin_polars/src/dataframe/command/data/with_column.rs
use crate::values::{Column, NuDataFrame, PolarsPluginType}; use crate::{ PolarsPlugin, dataframe::values::{NuExpression, NuLazyFrame}, values::{CustomValueSupport, PolarsPluginObject}, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Spanned, SyntaxShape, Value, }; #[derive(Clone)] pub struct WithColumn; impl PluginCommand for WithColumn { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars with-column" } fn description(&self) -> &str { "Adds a series to the dataframe." } fn signature(&self) -> Signature { Signature::build(self.name()) .named("name", SyntaxShape::String, "New column name. For lazy dataframes and expressions syntax, use a `polars as` expression to name a column.", Some('n')) .rest( "series or expressions", SyntaxShape::Any, "series to be added or expressions used to define the new columns", ) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe or lazyframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Adds a series to the dataframe", example: r#"[[a b]; [1 2] [3 4]] | polars into-df | polars with-column ([5 6] | polars into-df) --name c"#, result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![Value::test_int(1), Value::test_int(3)], ), Column::new( "b".to_string(), vec![Value::test_int(2), Value::test_int(4)], ), Column::new( "c".to_string(), vec![Value::test_int(5), Value::test_int(6)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Adds a series to the dataframe", example: r#"[[a b]; [1 2] [3 4]] | polars into-lazy | polars with-column [ ((polars col a) * 2 | polars as "c") ((polars col a) * 3 | polars as "d") ] | polars collect"#, result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![Value::test_int(1), Value::test_int(3)], ), Column::new( "b".to_string(), vec![Value::test_int(2), Value::test_int(4)], ), Column::new( "c".to_string(), vec![Value::test_int(2), Value::test_int(6)], ), Column::new( "d".to_string(), vec![Value::test_int(3), Value::test_int(9)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Add series to a lazyframe using a record", example: r#"[[a b]; [1 2] [3 4]] | polars into-lazy | polars with-column { c: ((polars col a) * 2) d: ((polars col a) * 3) } | polars collect"#, result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![Value::test_int(1), Value::test_int(3)], ), Column::new( "b".to_string(), vec![Value::test_int(2), Value::test_int(4)], ), Column::new( "c".to_string(), vec![Value::test_int(2), Value::test_int(6)], ), Column::new( "d".to_string(), vec![Value::test_int(3), Value::test_int(9)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Add series to a dataframe using a record", example: r#"[[a b]; [1 2] [3 4]] | polars into-df | polars with-column { c: ((polars col a) * 2) d: ((polars col a) * 3) } | polars collect"#, result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![Value::test_int(1), Value::test_int(3)], ), Column::new( "b".to_string(), vec![Value::test_int(2), Value::test_int(4)], ), Column::new( "c".to_string(), vec![Value::test_int(2), Value::test_int(6)], ), Column::new( "d".to_string(), vec![Value::test_int(3), Value::test_int(9)], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => command_eager(plugin, engine, call, df), PolarsPluginObject::NuLazyFrame(lazy) => command_lazy(plugin, engine, call, lazy), _ => Err(ShellError::CantConvert { to_type: "lazy or eager dataframe".into(), from_type: value.get_type().to_string(), span: value.span(), help: None, }), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command_eager( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let new_column: Value = call.req(0)?; let column_span = new_column.span(); if NuExpression::can_downcast(&new_column) { if let Some(name) = call.get_flag::<Spanned<String>>("name")? { return Err(ShellError::GenericError { error: "Flag 'name' is unsupported when used with expressions. Please use the `polars as` expression to name a column".into(), msg: "".into(), span: Some(name.span), help: Some("Use a `polars as` expression to name a column".into()), inner: vec![], }); } let vals: Vec<Value> = call.rest(0)?; let value = Value::list(vals, call.head); let expressions = NuExpression::extract_exprs(plugin, value)?; let lazy = NuLazyFrame::new(true, df.lazy().to_polars().with_columns(&expressions)); let df = lazy.collect(call.head)?; df.to_pipeline_data(plugin, engine, call.head) } else { let mut other = NuDataFrame::try_from_value_coerce(plugin, &new_column, call.head)? .as_series(column_span)?; let name = match call.get_flag::<String>("name")? { Some(name) => name, None => other.name().to_string(), }; let series = other.rename(name.into()).clone(); let mut polars_df = df.to_polars(); polars_df .with_column(series) .map_err(|e| ShellError::GenericError { error: "Error adding column to dataframe".into(), msg: e.to_string(), span: Some(column_span), help: None, inner: vec![], })?; let df = NuDataFrame::new(df.from_lazy, polars_df); df.to_pipeline_data(plugin, engine, call.head) } } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, ) -> Result<PipelineData, ShellError> { if let Some(name) = call.get_flag::<Spanned<String>>("name")? { return Err(ShellError::GenericError { error: "Flag 'name' is unsupported for lazy dataframes. Please use the `polars as` expression to name a column".into(), msg: "".into(), span: Some(name.span), help: Some("Use a `polars as` expression to name a column".into()), inner: vec![], }); } let vals: Vec<Value> = call.rest(0)?; let value = Value::list(vals, call.head); let expressions = NuExpression::extract_exprs(plugin, value)?; let lazy: NuLazyFrame = lazy.to_polars().with_columns(&expressions).into(); lazy.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&WithColumn) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/len.rs
crates/nu_plugin_polars/src/dataframe/command/data/len.rs
use crate::{ PolarsPlugin, values::{Column, CustomValueSupport, NuDataFrame, NuExpression, PolarsPluginType}, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{Category, Example, LabeledError, PipelineData, Signature, Span, Type, Value}; #[derive(Clone)] pub struct ExprLen; impl PluginCommand for ExprLen { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars len" } fn description(&self) -> &str { "Return the number of rows in the context. This is similar to COUNT(*) in SQL." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_type(Type::Any, PolarsPluginType::NuExpression.into()) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Count the number of rows in the the dataframe.", example: "[[a b]; [1 2] [3 4]] | polars into-df | polars select (polars len) | polars collect", result: Some( NuDataFrame::try_from_columns( vec![Column::new("len".to_string(), vec![Value::test_int(2)])], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Creates a last expression from a column", example: "polars col a | polars last", result: None, }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let res: NuExpression = polars::prelude::len().into(); res.to_pipeline_data(plugin, engine, call.head) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; use nu_protocol::ShellError; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ExprLen) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/col.rs
crates/nu_plugin_polars/src/dataframe/command/data/col.rs
use crate::{ PolarsPlugin, dataframe::values::NuExpression, values::{Column, CustomValueSupport, NuDataFrame, PolarsPluginType, str_to_dtype}, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Type, Value, record, }; use polars::{df, prelude::DataType}; #[derive(Clone)] pub struct ExprCol; impl PluginCommand for ExprCol { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars col" } fn description(&self) -> &str { "Creates a named column expression." } fn signature(&self) -> Signature { Signature::build(self.name()) .required( "column name", SyntaxShape::String, "Name of column to be used. '*' can be used for all columns. Accepts regular expression input; regular expressions should start with ^ and end with $.", ) .rest( "more columns", SyntaxShape::String, "Additional columns to be used. Cannot be '*'", ) .switch("type", "Treat column names as type names", Some('t')) .input_output_type(Type::Any, PolarsPluginType::NuExpression.into()) .category(Category::Custom("expression".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Creates a named column expression and converts it to a nu object", example: "polars col a | polars into-nu", result: Some(Value::test_record(record! { "expr" => Value::test_string("column"), "value" => Value::test_string("a"), })), }, Example { description: "Select all columns using the asterisk wildcard.", example: "[[a b]; [x 1] [y 2] [z 3]] | polars into-df | polars select (polars col '*') | polars collect", result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![ Value::test_string("x"), Value::test_string("y"), Value::test_string("z"), ], ), Column::new( "b".to_string(), vec![Value::test_int(1), Value::test_int(2), Value::test_int(3)], ), ], None, ) .expect("should not fail") .into_value(Span::test_data()), ), }, Example { description: "Select multiple columns (cannot be used with asterisk wildcard)", example: "[[a b c]; [x 1 1.1] [y 2 2.2] [z 3 3.3]] | polars into-df | polars select (polars col b c | polars sum) | polars collect", result: Some( NuDataFrame::try_from_columns( vec![ Column::new("b".to_string(), vec![Value::test_int(6)]), Column::new("c".to_string(), vec![Value::test_float(6.6)]), ], None, ) .expect("should not fail") .into_value(Span::test_data()), ), }, Example { description: "Select multiple columns by types (cannot be used with asterisk wildcard)", example: "[[a b c]; [x o 1.1] [y p 2.2] [z q 3.3]] | polars into-df | polars select (polars col str f64 --type | polars max) | polars collect", result: Some( NuDataFrame::try_from_columns( vec![ Column::new("a".to_string(), vec![Value::test_string("z")]), Column::new("b".to_string(), vec![Value::test_string("q")]), Column::new("c".to_string(), vec![Value::test_float(3.3)]), ], None, ) .expect("should not fail") .into_value(Span::test_data()), ), }, Example { description: "Select columns using a regular expression", example: "[[ham hamburger foo bar]; [1 11 2 a] [2 22 1 b]] | polars into-df | polars select (polars col '^ham.*$') | polars collect", result: Some( NuDataFrame::new( false, df!( "ham" => [1, 2], "hamburger" => [11, 22], ) .expect("should not fail to create dataframe"), ) .into_value(Span::test_data()), ), }, ] } fn search_terms(&self) -> Vec<&str> { vec!["create"] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let mut names: Vec<String> = vec![call.req(0)?]; names.extend(call.rest(1)?); let as_type = call.has_flag("type")?; let expr: NuExpression = match as_type { false => match names.as_slice() { [single] => polars::prelude::col(single).into(), _ => polars::prelude::cols(&names).as_expr().into(), }, true => { let dtypes = names .iter() .map(|n| str_to_dtype(n, call.head)) .collect::<Result<Vec<DataType>, ShellError>>() .map_err(LabeledError::from)?; polars::prelude::dtype_cols(dtypes) .as_selector() .as_expr() .into() } }; expr.to_pipeline_data(plugin, engine, call.head) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), nu_protocol::ShellError> { test_polars_plugin_command(&ExprCol) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/data/get.rs
crates/nu_plugin_polars/src/dataframe/command/data/get.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use crate::{ PolarsPlugin, dataframe::values::utils::convert_columns_string, values::CustomValueSupport, }; use crate::values::{Column, NuDataFrame, PolarsPluginType}; #[derive(Clone)] pub struct GetDF; impl PluginCommand for GetDF { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars get" } fn description(&self) -> &str { "Creates dataframe with the selected columns." } fn signature(&self) -> Signature { Signature::build(self.name()) .rest("rest", SyntaxShape::Any, "column names to sort dataframe") .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Returns the selected column", example: "[[a b]; [1 2] [3 4]] | polars into-df | polars get a", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "a".to_string(), vec![Value::test_int(1), Value::test_int(3)], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let columns: Vec<Value> = call.rest(0)?; let (col_string, col_span) = convert_columns_string(columns, call.head)?; let df = NuDataFrame::try_from_pipeline_coerce(plugin, input, call.head)?; let df = df .as_ref() .select(col_string) .map_err(|e| ShellError::GenericError { error: "Error selecting columns".into(), msg: e.to_string(), span: Some(col_span), help: None, inner: vec![], })?; let df = NuDataFrame::new(false, df); df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use crate::test::test_polars_plugin_command; use super::*; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&GetDF) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/values/file_type.rs
crates/nu_plugin_polars/src/dataframe/values/file_type.rs
use nu_protocol::{ShellError, Span}; #[derive(Debug, Clone, PartialEq)] pub enum PolarsFileType { Csv, Tsv, Parquet, Arrow, Json, Avro, NdJson, Unknown, } impl PolarsFileType { pub fn build_unsupported_error( extension: &str, supported_types: &[PolarsFileType], span: Span, ) -> ShellError { let type_string = supported_types .iter() .map(|ft| ft.to_str()) .collect::<Vec<&'static str>>() .join(", "); ShellError::GenericError { error: format!("Unsupported type {extension} expected {type_string}"), msg: "".into(), span: Some(span), help: None, inner: vec![], } } pub fn to_str(&self) -> &'static str { match self { PolarsFileType::Csv => "csv", PolarsFileType::Tsv => "tsv", PolarsFileType::Parquet => "parquet", PolarsFileType::Arrow => "arrow", PolarsFileType::Json => "json", PolarsFileType::Avro => "avro", PolarsFileType::NdJson => "ndjson", PolarsFileType::Unknown => "unknown", } } } impl From<&str> for PolarsFileType { fn from(file_type: &str) -> Self { match file_type { "csv" => PolarsFileType::Csv, "tsv" => PolarsFileType::Tsv, "parquet" | "parq" | "pq" => PolarsFileType::Parquet, "ipc" | "arrow" => PolarsFileType::Arrow, "json" => PolarsFileType::Json, "avro" => PolarsFileType::Avro, "jsonl" | "ndjson" => PolarsFileType::NdJson, _ => PolarsFileType::Unknown, } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/values/utils.rs
crates/nu_plugin_polars/src/dataframe/values/utils.rs
use nu_protocol::{ShellError, Span, Spanned, Value}; // Default value used when selecting rows from dataframe pub const DEFAULT_ROWS: usize = 5; // Converts a Vec<Value> to a Vec<Spanned<String>> with a Span marking the whole // location of the columns for error referencing pub(crate) fn convert_columns( columns: Vec<Value>, span: Span, ) -> Result<(Vec<Spanned<String>>, Span), ShellError> { // First column span let mut col_span = columns .first() .ok_or_else(|| ShellError::GenericError { error: "Empty column list".into(), msg: "Empty list found for command".into(), span: Some(span), help: None, inner: vec![], })? .span(); let res = columns .into_iter() .map(|value| { let span = value.span(); match value { Value::String { val, .. } => { col_span = col_span.merge(span); Ok(Spanned { item: val, span }) } _ => Err(ShellError::GenericError { error: "Incorrect column format".into(), msg: "Only string as column name".into(), span: Some(span), help: None, inner: vec![], }), } }) .collect::<Result<Vec<Spanned<String>>, _>>()?; Ok((res, col_span)) } // Converts a Vec<Value> to a Vec<String> with a Span marking the whole // location of the columns for error referencing pub(crate) fn convert_columns_string( columns: Vec<Value>, span: Span, ) -> Result<(Vec<String>, Span), ShellError> { // First column span let mut col_span = columns .first() .ok_or_else(|| ShellError::GenericError { error: "Empty column list".into(), msg: "Empty list found for command".into(), span: Some(span), help: None, inner: vec![], }) .map(|v| v.span())?; let res = columns .into_iter() .map(|value| { let span = value.span(); match value { Value::String { val, .. } => { col_span = col_span.merge(span); Ok(val) } _ => Err(ShellError::GenericError { error: "Incorrect column format".into(), msg: "Only string as column name".into(), span: Some(span), help: None, inner: vec![], }), } }) .collect::<Result<Vec<String>, _>>()?; Ok((res, col_span)) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/values/mod.rs
crates/nu_plugin_polars/src/dataframe/values/mod.rs
mod file_type; mod nu_dataframe; mod nu_dtype; mod nu_expression; mod nu_lazyframe; mod nu_lazygroupby; mod nu_schema; mod nu_when; pub mod utils; use crate::{Cacheable, PolarsPlugin}; use nu_dtype::custom_value::NuDataTypeCustomValue; use nu_plugin::EngineInterface; use nu_protocol::{ CustomValue, PipelineData, ShellError, Span, Spanned, Type, Value, ast::Operator, }; use nu_schema::custom_value::NuSchemaCustomValue; use std::{cmp::Ordering, fmt}; use uuid::Uuid; pub use file_type::PolarsFileType; pub use nu_dataframe::{Axis, Column, NuDataFrame, NuDataFrameCustomValue}; pub use nu_dtype::NuDataType; pub use nu_dtype::{datatype_list, str_to_dtype, str_to_time_unit}; pub use nu_expression::{NuExpression, NuExpressionCustomValue}; pub use nu_lazyframe::{NuLazyFrame, NuLazyFrameCustomValue}; pub use nu_lazygroupby::{NuLazyGroupBy, NuLazyGroupByCustomValue}; pub use nu_schema::NuSchema; pub use nu_when::{NuWhen, NuWhenCustomValue, NuWhenType}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PolarsPluginType { NuDataFrame, NuLazyFrame, NuExpression, NuLazyGroupBy, NuWhen, NuPolarsTestData, NuDataType, NuSchema, } impl PolarsPluginType { pub fn type_name(&self) -> &'static str { match self { Self::NuDataFrame => "polars_dataframe", Self::NuLazyFrame => "polars_lazyframe", Self::NuExpression => "polars_expression", Self::NuLazyGroupBy => "polars_group_by", Self::NuWhen => "polars_when", Self::NuPolarsTestData => "polars_test_data", Self::NuDataType => "polars_datatype", Self::NuSchema => "polars_schema", } } pub fn types() -> &'static [PolarsPluginType] { &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, PolarsPluginType::NuLazyGroupBy, PolarsPluginType::NuWhen, PolarsPluginType::NuDataType, PolarsPluginType::NuSchema, ] } } impl From<PolarsPluginType> for Type { fn from(pt: PolarsPluginType) -> Self { Type::Custom(pt.type_name().into()) } } impl fmt::Display for PolarsPluginType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::NuDataFrame => write!(f, "NuDataFrame"), Self::NuLazyFrame => write!(f, "NuLazyFrame"), Self::NuExpression => write!(f, "NuExpression"), Self::NuLazyGroupBy => write!(f, "NuLazyGroupBy"), Self::NuWhen => write!(f, "NuWhen"), Self::NuPolarsTestData => write!(f, "NuPolarsTestData"), Self::NuDataType => write!(f, "NuDataType"), Self::NuSchema => write!(f, "NuSchema"), } } } #[derive(Debug, Clone)] pub enum PolarsPluginObject { NuDataFrame(NuDataFrame), NuLazyFrame(NuLazyFrame), NuExpression(NuExpression), NuLazyGroupBy(NuLazyGroupBy), NuWhen(NuWhen), NuPolarsTestData(Uuid, String), NuDataType(NuDataType), NuSchema(NuSchema), } impl PolarsPluginObject { pub fn try_from_value( plugin: &PolarsPlugin, value: &Value, ) -> Result<PolarsPluginObject, ShellError> { if NuDataFrame::can_downcast(value) { NuDataFrame::try_from_value(plugin, value).map(PolarsPluginObject::NuDataFrame) } else if NuLazyFrame::can_downcast(value) { NuLazyFrame::try_from_value(plugin, value).map(PolarsPluginObject::NuLazyFrame) } else if NuExpression::can_downcast(value) { NuExpression::try_from_value(plugin, value).map(PolarsPluginObject::NuExpression) } else if NuLazyGroupBy::can_downcast(value) { NuLazyGroupBy::try_from_value(plugin, value).map(PolarsPluginObject::NuLazyGroupBy) } else if NuWhen::can_downcast(value) { NuWhen::try_from_value(plugin, value).map(PolarsPluginObject::NuWhen) } else if NuSchema::can_downcast(value) { NuSchema::try_from_value(plugin, value).map(PolarsPluginObject::NuSchema) } else if NuDataType::can_downcast(value) { NuDataType::try_from_value(plugin, value).map(PolarsPluginObject::NuDataType) } else { Err(cant_convert_err( value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, PolarsPluginType::NuLazyGroupBy, PolarsPluginType::NuWhen, PolarsPluginType::NuDataType, PolarsPluginType::NuSchema, ], )) } } pub fn try_from_pipeline( plugin: &PolarsPlugin, input: PipelineData, span: Span, ) -> Result<Self, ShellError> { let value = input.into_value(span)?; Self::try_from_value(plugin, &value) } pub fn get_type(&self) -> PolarsPluginType { match self { Self::NuDataFrame(_) => PolarsPluginType::NuDataFrame, Self::NuLazyFrame(_) => PolarsPluginType::NuLazyFrame, Self::NuExpression(_) => PolarsPluginType::NuExpression, Self::NuLazyGroupBy(_) => PolarsPluginType::NuLazyGroupBy, Self::NuWhen(_) => PolarsPluginType::NuWhen, Self::NuPolarsTestData(_, _) => PolarsPluginType::NuPolarsTestData, Self::NuDataType(_) => PolarsPluginType::NuDataType, Self::NuSchema(_) => PolarsPluginType::NuSchema, } } pub fn id(&self) -> Uuid { match self { PolarsPluginObject::NuDataFrame(df) => df.id, PolarsPluginObject::NuLazyFrame(lf) => lf.id, PolarsPluginObject::NuExpression(e) => e.id, PolarsPluginObject::NuLazyGroupBy(lg) => lg.id, PolarsPluginObject::NuWhen(w) => w.id, PolarsPluginObject::NuPolarsTestData(id, _) => *id, PolarsPluginObject::NuDataType(dt) => dt.id, PolarsPluginObject::NuSchema(schema) => schema.id, } } pub fn into_value(self, span: Span) -> Value { match self { PolarsPluginObject::NuDataFrame(df) => df.into_value(span), PolarsPluginObject::NuLazyFrame(lf) => lf.into_value(span), PolarsPluginObject::NuExpression(e) => e.into_value(span), PolarsPluginObject::NuLazyGroupBy(lg) => lg.into_value(span), PolarsPluginObject::NuWhen(w) => w.into_value(span), PolarsPluginObject::NuPolarsTestData(id, s) => { Value::string(format!("{id}:{s}"), Span::test_data()) } PolarsPluginObject::NuDataType(dt) => dt.into_value(span), PolarsPluginObject::NuSchema(schema) => schema.into_value(span), } } pub fn dataframe(&self) -> Option<&NuDataFrame> { match self { PolarsPluginObject::NuDataFrame(df) => Some(df), _ => None, } } pub fn lazyframe(&self) -> Option<&NuLazyFrame> { match self { PolarsPluginObject::NuLazyFrame(lf) => Some(lf), _ => None, } } } #[derive(Debug, Clone)] pub enum CustomValueType { NuDataFrame(NuDataFrameCustomValue), NuLazyFrame(NuLazyFrameCustomValue), NuExpression(NuExpressionCustomValue), NuLazyGroupBy(NuLazyGroupByCustomValue), NuWhen(NuWhenCustomValue), NuDataType(NuDataTypeCustomValue), NuSchema(NuSchemaCustomValue), } impl CustomValueType { pub fn id(&self) -> Uuid { match self { CustomValueType::NuDataFrame(df_cv) => df_cv.id, CustomValueType::NuLazyFrame(lf_cv) => lf_cv.id, CustomValueType::NuExpression(e_cv) => e_cv.id, CustomValueType::NuLazyGroupBy(lg_cv) => lg_cv.id, CustomValueType::NuWhen(w_cv) => w_cv.id, CustomValueType::NuDataType(dt_cv) => dt_cv.id, CustomValueType::NuSchema(schema_cv) => schema_cv.id, } } pub fn try_from_custom_value(val: Box<dyn CustomValue>) -> Result<CustomValueType, ShellError> { if let Some(df_cv) = val.as_any().downcast_ref::<NuDataFrameCustomValue>() { Ok(CustomValueType::NuDataFrame(df_cv.clone())) } else if let Some(lf_cv) = val.as_any().downcast_ref::<NuLazyFrameCustomValue>() { Ok(CustomValueType::NuLazyFrame(lf_cv.clone())) } else if let Some(e_cv) = val.as_any().downcast_ref::<NuExpressionCustomValue>() { Ok(CustomValueType::NuExpression(e_cv.clone())) } else if let Some(lg_cv) = val.as_any().downcast_ref::<NuLazyGroupByCustomValue>() { Ok(CustomValueType::NuLazyGroupBy(lg_cv.clone())) } else if let Some(w_cv) = val.as_any().downcast_ref::<NuWhenCustomValue>() { Ok(CustomValueType::NuWhen(w_cv.clone())) } else if let Some(w_cv) = val.as_any().downcast_ref::<NuDataTypeCustomValue>() { Ok(CustomValueType::NuDataType(w_cv.clone())) } else if let Some(w_cv) = val.as_any().downcast_ref::<NuSchemaCustomValue>() { Ok(CustomValueType::NuSchema(w_cv.clone())) } else { Err(ShellError::CantConvert { to_type: "physical type".into(), from_type: "value".into(), span: Span::unknown(), help: None, }) } } } pub fn cant_convert_err(value: &Value, expected_types: &[PolarsPluginType]) -> ShellError { let type_string = expected_types .iter() .map(ToString::to_string) .collect::<Vec<String>>() .join(", "); ShellError::CantConvert { to_type: type_string, from_type: value.get_type().to_string(), span: value.span(), help: None, } } pub trait PolarsPluginCustomValue: CustomValue { type PolarsPluginObjectType: Clone; fn id(&self) -> &Uuid; fn internal(&self) -> &Option<Self::PolarsPluginObjectType>; fn custom_value_to_base_value( &self, plugin: &PolarsPlugin, engine: &EngineInterface, ) -> Result<Value, ShellError>; fn custom_value_operation( &self, _plugin: &PolarsPlugin, _engine: &EngineInterface, lhs_span: Span, operator: Spanned<Operator>, _right: Value, ) -> Result<Value, ShellError> { Err(ShellError::OperatorUnsupportedType { op: operator.item, unsupported: Type::Custom(self.type_name().into()), op_span: operator.span, unsupported_span: lhs_span, help: None, }) } fn custom_value_follow_path_int( &self, _plugin: &PolarsPlugin, _engine: &EngineInterface, self_span: Span, _index: Spanned<usize>, ) -> Result<Value, ShellError> { Err(ShellError::IncompatiblePathAccess { type_name: self.type_name(), span: self_span, }) } fn custom_value_follow_path_string( &self, _plugin: &PolarsPlugin, _engine: &EngineInterface, self_span: Span, _column_name: Spanned<String>, ) -> Result<Value, ShellError> { Err(ShellError::IncompatiblePathAccess { type_name: self.type_name(), span: self_span, }) } fn custom_value_partial_cmp( &self, _plugin: &PolarsPlugin, _engine: &EngineInterface, _other_value: Value, ) -> Result<Option<Ordering>, ShellError> { Ok(None) } } /// Handles the ability for a PolarsObjectType implementations to convert between /// their respective CustValue type. /// PolarsPluginObjectType's (NuDataFrame, NuLazyFrame) should /// implement this trait. pub trait CustomValueSupport: Cacheable { type CV: PolarsPluginCustomValue<PolarsPluginObjectType = Self> + CustomValue + 'static; fn get_type(&self) -> PolarsPluginType { Self::get_type_static() } fn get_type_static() -> PolarsPluginType; fn custom_value(self) -> Self::CV; fn base_value(self, span: Span) -> Result<Value, ShellError>; fn into_value(self, span: Span) -> Value { Value::custom(Box::new(self.custom_value()), span) } fn try_from_custom_value(plugin: &PolarsPlugin, cv: &Self::CV) -> Result<Self, ShellError> { if let Some(internal) = cv.internal() { Ok(internal.clone()) } else { Self::get_cached(plugin, cv.id())?.ok_or_else(|| ShellError::GenericError { error: format!("Dataframe {:?} not found in cache", cv.id()), msg: "".into(), span: None, help: None, inner: vec![], }) } } fn try_from_value(plugin: &PolarsPlugin, value: &Value) -> Result<Self, ShellError> { if let Value::Custom { val, .. } = value { if let Some(cv) = val.as_any().downcast_ref::<Self::CV>() { Self::try_from_custom_value(plugin, cv) } else { Err(ShellError::CantConvert { to_type: Self::get_type_static().to_string(), from_type: value.get_type().to_string(), span: value.span(), help: None, }) } } else { Err(ShellError::CantConvert { to_type: Self::get_type_static().to_string(), from_type: value.get_type().to_string(), span: value.span(), help: None, }) } } fn try_from_pipeline( plugin: &PolarsPlugin, input: PipelineData, span: Span, ) -> Result<Self, ShellError> { let value = input.into_value(span)?; Self::try_from_value(plugin, &value) } fn can_downcast(value: &Value) -> bool { if let Value::Custom { val, .. } = value { val.as_any().downcast_ref::<Self::CV>().is_some() } else { false } } /// Wraps the cache and into_value calls. /// This function also does mapping back and forth /// between lazy and eager values and makes sure they /// are cached appropriately. fn cache_and_to_value( self, plugin: &PolarsPlugin, engine: &EngineInterface, span: Span, ) -> Result<Value, ShellError> { match self.to_cache_value()? { // if it was from a lazy value, make it lazy again PolarsPluginObject::NuDataFrame(df) if df.from_lazy => { let df = df.lazy(); Ok(df.cache(plugin, engine, span)?.into_value(span)) } // if it was from an eager value, make it eager again PolarsPluginObject::NuLazyFrame(lf) if lf.from_eager => { let lf = lf.collect(span)?; Ok(lf.cache(plugin, engine, span)?.into_value(span)) } _ => Ok(self.cache(plugin, engine, span)?.into_value(span)), } } /// Caches the object, converts it to a it's CustomValue counterpart /// And creates a pipeline data object out of it #[inline] fn to_pipeline_data( self, plugin: &PolarsPlugin, engine: &EngineInterface, span: Span, ) -> Result<PipelineData, ShellError> { Ok(PipelineData::value( self.cache_and_to_value(plugin, engine, span)?, None, )) } } #[cfg(test)] mod test { use polars::prelude::{DataType, TimeUnit, UnknownKind}; use polars_compute::decimal::DEC128_MAX_PREC; use crate::command::datetime::timezone_utc; use super::*; #[test] fn test_dtype_str_to_schema_simple_types() { let dtype = "bool"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::Boolean; assert_eq!(schema, expected); let dtype = "u8"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::UInt8; assert_eq!(schema, expected); let dtype = "u16"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::UInt16; assert_eq!(schema, expected); let dtype = "u32"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::UInt32; assert_eq!(schema, expected); let dtype = "u64"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::UInt64; assert_eq!(schema, expected); let dtype = "i8"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::Int8; assert_eq!(schema, expected); let dtype = "i16"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::Int16; assert_eq!(schema, expected); let dtype = "i32"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::Int32; assert_eq!(schema, expected); let dtype = "i64"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::Int64; assert_eq!(schema, expected); let dtype = "str"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::String; assert_eq!(schema, expected); let dtype = "binary"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::Binary; assert_eq!(schema, expected); let dtype = "date"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::Date; assert_eq!(schema, expected); let dtype = "time"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::Time; assert_eq!(schema, expected); let dtype = "null"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::Null; assert_eq!(schema, expected); let dtype = "unknown"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::Unknown(UnknownKind::Any); assert_eq!(schema, expected); let dtype = "object"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::Object("unknown"); assert_eq!(schema, expected); } #[test] fn test_dtype_str_schema_datetime() { let dtype = "datetime<ms, *>"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::Datetime(TimeUnit::Milliseconds, None); assert_eq!(schema, expected); let dtype = "datetime<us, *>"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::Datetime(TimeUnit::Microseconds, None); assert_eq!(schema, expected); let dtype = "datetime<μs, *>"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::Datetime(TimeUnit::Microseconds, None); assert_eq!(schema, expected); let dtype = "datetime<ns, *>"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::Datetime(TimeUnit::Nanoseconds, None); assert_eq!(schema, expected); let dtype = "datetime<ms, UTC>"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::Datetime(TimeUnit::Milliseconds, Some(timezone_utc())); assert_eq!(schema, expected); let dtype = "invalid"; let schema = str_to_dtype(dtype, Span::unknown()); assert!(schema.is_err()) } #[test] fn test_dtype_str_schema_duration() { let dtype = "duration<ms>"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::Duration(TimeUnit::Milliseconds); assert_eq!(schema, expected); let dtype = "duration<us>"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::Duration(TimeUnit::Microseconds); assert_eq!(schema, expected); let dtype = "duration<μs>"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::Duration(TimeUnit::Microseconds); assert_eq!(schema, expected); let dtype = "duration<ns>"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::Duration(TimeUnit::Nanoseconds); assert_eq!(schema, expected); } #[test] fn test_dtype_str_schema_decimal() { let dtype = "decimal<7,2>"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::Decimal(7usize, 2usize); assert_eq!(schema, expected); // "*" is not a permitted value for scale let dtype = "decimal<7,*>"; let schema = str_to_dtype(dtype, Span::unknown()); assert!(matches!(schema, Err(ShellError::GenericError { .. }))); let dtype = "decimal<*,2>"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::Decimal(DEC128_MAX_PREC, 2usize); assert_eq!(schema, expected); } #[test] fn test_dtype_str_to_schema_list_types() { let dtype = "list<i32>"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::List(Box::new(DataType::Int32)); assert_eq!(schema, expected); let dtype = "list<duration<ms>>"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::List(Box::new(DataType::Duration(TimeUnit::Milliseconds))); assert_eq!(schema, expected); let dtype = "list<datetime<ms, *>>"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::List(Box::new(DataType::Datetime(TimeUnit::Milliseconds, None))); assert_eq!(schema, expected); let dtype = "list<decimal<7,2>>"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::List(Box::new(DataType::Decimal(7usize, 2usize))); assert_eq!(schema, expected); let dtype = "list<decimal<*,2>>"; let schema = str_to_dtype(dtype, Span::unknown()).unwrap(); let expected = DataType::List(Box::new(DataType::Decimal(DEC128_MAX_PREC, 2usize))); assert_eq!(schema, expected); let dtype = "list<decimal<7,*>>"; let schema = str_to_dtype(dtype, Span::unknown()); assert!(matches!(schema, Err(ShellError::GenericError { .. }))); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/values/nu_expression/custom_value.rs
crates/nu_plugin_polars/src/dataframe/values/nu_expression/custom_value.rs
use crate::{ Cacheable, PolarsPlugin, values::{CustomValueSupport, PolarsPluginCustomValue, PolarsPluginType}, }; use std::ops::{Add, Div, Mul, Rem, Sub}; use super::NuExpression; use nu_plugin::EngineInterface; use nu_protocol::{ CustomValue, ShellError, Span, Type, Value, ast::{Boolean, Comparison, Math, Operator}, }; use polars::prelude::Expr; use serde::{Deserialize, Serialize}; use uuid::Uuid; const TYPE_NAME: &str = "polars_expression"; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct NuExpressionCustomValue { pub id: Uuid, #[serde(skip)] pub expr: Option<NuExpression>, } // CustomValue implementation for NuDataFrame #[typetag::serde] impl CustomValue for NuExpressionCustomValue { fn clone_value(&self, span: nu_protocol::Span) -> Value { let cloned = self.clone(); Value::custom(Box::new(cloned), span) } fn type_name(&self) -> String { PolarsPluginType::NuExpression.type_name().to_string() } fn to_base_value(&self, span: Span) -> Result<Value, ShellError> { Ok(Value::string( "NuExpressionCustomValue: custom_value_to_base_value should've been called", span, )) } fn as_mut_any(&mut self) -> &mut dyn std::any::Any { self } fn as_any(&self) -> &dyn std::any::Any { self } fn notify_plugin_on_drop(&self) -> bool { true } } fn compute_with_value( (plugin, engine): (&PolarsPlugin, &EngineInterface), left: &NuExpression, lhs_span: Span, operator: Operator, op: Span, right: &Value, ) -> Result<Value, ShellError> { let rhs = NuExpression::try_from_value(plugin, right)?; with_operator( (plugin, engine), operator, left, &rhs, lhs_span, right.span(), op, ) } fn with_operator( (plugin, engine): (&PolarsPlugin, &EngineInterface), operator: Operator, left: &NuExpression, right: &NuExpression, lhs_span: Span, _rhs_span: Span, op_span: Span, ) -> Result<Value, ShellError> { match operator { Operator::Math(Math::Add) => { apply_arithmetic(plugin, engine, left, right, lhs_span, Add::add) } Operator::Math(Math::Subtract) => { apply_arithmetic(plugin, engine, left, right, lhs_span, Sub::sub) } Operator::Math(Math::Multiply) => { apply_arithmetic(plugin, engine, left, right, lhs_span, Mul::mul) } Operator::Math(Math::Divide) => { apply_arithmetic(plugin, engine, left, right, lhs_span, Div::div) } Operator::Math(Math::Modulo) => { apply_arithmetic(plugin, engine, left, right, lhs_span, Rem::rem) } Operator::Math(Math::FloorDivide) => { apply_arithmetic(plugin, engine, left, right, lhs_span, Expr::floor_div) } Operator::Math(Math::Pow) => { apply_arithmetic(plugin, engine, left, right, lhs_span, Expr::pow) } Operator::Comparison(Comparison::Equal) => Ok(left .clone() .apply_with_expr(right.clone(), Expr::eq) .cache(plugin, engine, lhs_span)? .into_value(lhs_span)), Operator::Comparison(Comparison::NotEqual) => Ok(left .clone() .apply_with_expr(right.clone(), Expr::neq) .cache(plugin, engine, lhs_span)? .into_value(lhs_span)), Operator::Comparison(Comparison::GreaterThan) => Ok(left .clone() .apply_with_expr(right.clone(), Expr::gt) .cache(plugin, engine, lhs_span)? .into_value(lhs_span)), Operator::Comparison(Comparison::GreaterThanOrEqual) => Ok(left .clone() .apply_with_expr(right.clone(), Expr::gt_eq) .cache(plugin, engine, lhs_span)? .into_value(lhs_span)), Operator::Comparison(Comparison::LessThan) => Ok(left .clone() .apply_with_expr(right.clone(), Expr::lt) .cache(plugin, engine, lhs_span)? .into_value(lhs_span)), Operator::Comparison(Comparison::LessThanOrEqual) => Ok(left .clone() .apply_with_expr(right.clone(), Expr::lt_eq) .cache(plugin, engine, lhs_span)? .into_value(lhs_span)), Operator::Boolean(Boolean::And) => Ok(left .clone() .apply_with_expr(right.clone(), Expr::logical_and) .cache(plugin, engine, lhs_span)? .into_value(lhs_span)), Operator::Boolean(Boolean::Or) => Ok(left .clone() .apply_with_expr(right.clone(), Expr::logical_or) .cache(plugin, engine, lhs_span)? .into_value(lhs_span)), Operator::Boolean(Boolean::Xor) => Ok(left .clone() .apply_with_expr(right.clone(), logical_xor) .cache(plugin, engine, lhs_span)? .into_value(lhs_span)), op => Err(ShellError::OperatorUnsupportedType { op, unsupported: Type::Custom(TYPE_NAME.into()), op_span, unsupported_span: lhs_span, help: None, }), } } pub fn logical_xor(a: Expr, b: Expr) -> Expr { (a.clone().or(b.clone())) // A OR B .and((a.and(b)).not()) // AND with NOT (A AND B) } fn apply_arithmetic<F>( plugin: &PolarsPlugin, engine: &EngineInterface, left: &NuExpression, right: &NuExpression, span: Span, f: F, ) -> Result<Value, ShellError> where F: Fn(Expr, Expr) -> Expr, { let expr: NuExpression = f(left.as_ref().clone(), right.as_ref().clone()).into(); Ok(expr.cache(plugin, engine, span)?.into_value(span)) } impl PolarsPluginCustomValue for NuExpressionCustomValue { type PolarsPluginObjectType = NuExpression; fn custom_value_operation( &self, plugin: &crate::PolarsPlugin, engine: &nu_plugin::EngineInterface, lhs_span: Span, operator: nu_protocol::Spanned<nu_protocol::ast::Operator>, right: Value, ) -> Result<Value, ShellError> { let expr = NuExpression::try_from_custom_value(plugin, self)?; compute_with_value( (plugin, engine), &expr, lhs_span, operator.item, operator.span, &right, ) } fn custom_value_to_base_value( &self, plugin: &crate::PolarsPlugin, _engine: &nu_plugin::EngineInterface, ) -> Result<Value, ShellError> { let expr = NuExpression::try_from_custom_value(plugin, self)?; expr.base_value(Span::unknown()) } fn id(&self) -> &Uuid { &self.id } fn internal(&self) -> &Option<Self::PolarsPluginObjectType> { &self.expr } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/values/nu_expression/mod.rs
crates/nu_plugin_polars/src/dataframe/values/nu_expression/mod.rs
mod custom_value; use nu_protocol::{ShellError, Span, Value, record}; use polars::{ chunked_array::cast::CastOptions, prelude::{AggExpr, Expr, Literal, col}, }; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use uuid::Uuid; use crate::{Cacheable, PolarsPlugin, values::NuDataFrame}; pub use self::custom_value::NuExpressionCustomValue; use super::{CustomValueSupport, PolarsPluginObject, PolarsPluginType}; // Polars Expression wrapper for Nushell operations // Object is behind and Option to allow easy implementation of // the Deserialize trait #[derive(Default, Clone, Debug)] pub struct NuExpression { pub id: Uuid, expr: Option<Expr>, } // Mocked serialization of the LazyFrame object impl Serialize for NuExpression { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_none() } } // Mocked deserialization of the LazyFrame object impl<'de> Deserialize<'de> for NuExpression { fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { Ok(NuExpression::default()) } } // Referenced access to the real LazyFrame impl AsRef<Expr> for NuExpression { fn as_ref(&self) -> &polars::prelude::Expr { // The only case when there cannot be an expr is if it is created // using the default function or if created by deserializing something self.expr.as_ref().expect("there should always be a frame") } } impl AsMut<Expr> for NuExpression { fn as_mut(&mut self) -> &mut polars::prelude::Expr { // The only case when there cannot be an expr is if it is created // using the default function or if created by deserializing something self.expr.as_mut().expect("there should always be a frame") } } impl From<Expr> for NuExpression { fn from(expr: Expr) -> Self { Self::new(Some(expr)) } } impl NuExpression { fn new(expr: Option<Expr>) -> Self { Self { id: Uuid::new_v4(), expr, } } pub fn into_polars(self) -> Expr { self.expr.expect("Expression cannot be none to convert") } pub fn apply_with_expr<F>(self, other: NuExpression, f: F) -> Self where F: Fn(Expr, Expr) -> Expr, { let expr = self .expr .expect("Lazy expression must not be empty to apply"); let other = other .expr .expect("Lazy expression must not be empty to apply"); f(expr, other).into() } pub fn to_value(&self, span: Span) -> Result<Value, ShellError> { expr_to_value(self.as_ref(), span) } // Convenient function to extract multiple Expr that could be inside a nushell Value pub fn extract_exprs(plugin: &PolarsPlugin, value: Value) -> Result<Vec<Expr>, ShellError> { ExtractedExpr::extract_exprs(plugin, value).map(ExtractedExpr::into_exprs) } } #[derive(Debug)] // Enum to represent the parsing of the expressions from Value enum ExtractedExpr { Single(Expr), List(Vec<ExtractedExpr>), } impl ExtractedExpr { fn into_exprs(self) -> Vec<Expr> { match self { Self::Single(expr) => vec![expr], Self::List(expressions) => expressions .into_iter() .flat_map(ExtractedExpr::into_exprs) .collect(), } } fn extract_exprs(plugin: &PolarsPlugin, value: Value) -> Result<ExtractedExpr, ShellError> { match value { Value::String { val, .. } => Ok(ExtractedExpr::Single(col(val.as_str()))), Value::Custom { .. } => NuExpression::try_from_value(plugin, &value) .map(NuExpression::into_polars) .map(ExtractedExpr::Single), Value::Record { val, .. } => val .iter() .map(|(key, value)| { NuExpression::try_from_value(plugin, value) .map(NuExpression::into_polars) .map(|expr| expr.alias(key)) .map(ExtractedExpr::Single) }) .collect::<Result<Vec<ExtractedExpr>, ShellError>>() .map(ExtractedExpr::List), Value::List { vals, .. } => vals .into_iter() .map(|x| Self::extract_exprs(plugin, x)) .collect::<Result<Vec<ExtractedExpr>, ShellError>>() .map(ExtractedExpr::List), x => Err(ShellError::CantConvert { to_type: "expression".into(), from_type: x.get_type().to_string(), span: x.span(), help: None, }), } } } pub fn expr_to_value(expr: &Expr, span: Span) -> Result<Value, ShellError> { match expr { Expr::Alias(expr, alias) => Ok(Value::record( record! { "expr" => expr_to_value(expr.as_ref(), span)?, "alias" => Value::string(alias.as_str(), span), }, span, )), Expr::Column(name) => Ok(Value::record( record! { "expr" => Value::string("column", span), "value" => Value::string(name.to_string(), span), }, span, )), Expr::Literal(literal) => Ok(Value::record( record! { "expr" => Value::string("literal", span), "value" => Value::string(format!("{literal:?}"), span), }, span, )), Expr::BinaryExpr { left, op, right } => Ok(Value::record( record! { "left" => expr_to_value(left, span)?, "op" => Value::string(format!("{op:?}"), span), "right" => expr_to_value(right, span)?, }, span, )), Expr::Ternary { predicate, truthy, falsy, } => Ok(Value::record( record! { "predicate" => expr_to_value(predicate.as_ref(), span)?, "truthy" => expr_to_value(truthy.as_ref(), span)?, "falsy" => expr_to_value(falsy.as_ref(), span)?, }, span, )), Expr::Agg(agg_expr) => { let value = match agg_expr { AggExpr::Min { input: expr, .. } | AggExpr::Max { input: expr, .. } | AggExpr::Median(expr) | AggExpr::NUnique(expr) | AggExpr::First(expr) | AggExpr::Last(expr) | AggExpr::Mean(expr) | AggExpr::Implode(expr) | AggExpr::Count { input: expr, .. } | AggExpr::Sum(expr) | AggExpr::AggGroups(expr) | AggExpr::Std(expr, _) | AggExpr::Item { input: expr, .. } | AggExpr::Var(expr, _) => expr_to_value(expr.as_ref(), span), AggExpr::Quantile { expr, quantile, method, } => Ok(Value::record( record! { "expr" => expr_to_value(expr.as_ref(), span)?, "quantile" => expr_to_value(quantile.as_ref(), span)?, "method" => Value::string(format!("{method:?}"), span), }, span, )), }; Ok(Value::record( record! { "expr" => Value::string("agg", span), "value" => value?, }, span, )) } Expr::Len => Ok(Value::record( record! { "expr" => Value::string("count", span) }, span, )), Expr::Explode { input: expr, .. } => Ok(Value::record( record! { "expr" => expr_to_value(expr.as_ref(), span)? }, span, )), Expr::KeepName(expr) => Ok(Value::record( record! { "expr" => expr_to_value(expr.as_ref(), span)? }, span, )), Expr::Sort { expr, options } => Ok(Value::record( record! { "expr" => expr_to_value(expr.as_ref(), span)?, "options" => Value::string(format!("{options:?}"), span), }, span, )), Expr::Cast { expr, dtype: data_type, options, } => { let cast_option_str = match options { CastOptions::Strict => "STRICT", CastOptions::NonStrict => "NON_STRICT", CastOptions::Overflowing => "OVERFLOWING", }; Ok(Value::record( record! { "expr" => expr_to_value(expr.as_ref(), span)?, "dtype" => Value::string(format!("{data_type:?}"), span), "cast_options" => Value::string(cast_option_str, span) }, span, )) } Expr::Gather { expr, idx, returns_scalar: _, } => Ok(Value::record( record! { "expr" => expr_to_value(expr.as_ref(), span)?, "idx" => expr_to_value(idx.as_ref(), span)?, }, span, )), Expr::SortBy { expr, by, sort_options, } => { let by: Result<Vec<Value>, ShellError> = by.iter().map(|b| expr_to_value(b, span)).collect(); let descending: Vec<Value> = sort_options .descending .iter() .map(|r| Value::bool(*r, span)) .collect(); Ok(Value::record( record! { "expr" => expr_to_value(expr.as_ref(), span)?, "by" => Value::list(by?, span), "descending" => Value::list(descending, span), }, span, )) } Expr::Filter { input, by } => Ok(Value::record( record! { "input" => expr_to_value(input.as_ref(), span)?, "by" => expr_to_value(by.as_ref(), span)?, }, span, )), Expr::Slice { input, offset, length, } => Ok(Value::record( record! { "input" => expr_to_value(input.as_ref(), span)?, "offset" => expr_to_value(offset.as_ref(), span)?, "length" => expr_to_value(length.as_ref(), span)?, }, span, )), Expr::RenameAlias { expr, .. } => Ok(Value::record( record! { "expr" => expr_to_value(expr.as_ref(), span)?, }, span, )), Expr::AnonymousFunction { input, function, options, fmt_str, } => { let input: Result<Vec<Value>, ShellError> = input.iter().map(|e| expr_to_value(e, span)).collect(); Ok(Value::record( record! { "input" => Value::list(input?, span), "function" => Value::string(format!("{function:?}"), span), "options" => Value::string(format!("{options:?}"), span), "fmt_str" => Value::string(format!("{fmt_str:?}"), span), }, span, )) } Expr::Function { input, function } => { let input: Result<Vec<Value>, ShellError> = input.iter().map(|e| expr_to_value(e, span)).collect(); Ok(Value::record( record! { "input" => Value::list(input?, span), "function" => Value::string(format!("{function:?}"), span), }, span, )) } Expr::Window { function, partition_by, order_by, options, } => { let partition_by: Result<Vec<Value>, ShellError> = partition_by .iter() .map(|e| expr_to_value(e, span)) .collect(); Ok(Value::record( record! { "function" => expr_to_value(function, span)?, "partition_by" => Value::list(partition_by?, span), "order_by" => { if let Some((order_expr, sort_options)) = order_by { Value::record(record! { "expr" => expr_to_value(order_expr.as_ref(), span)?, "sort_options" => { Value::record(record!( "descending" => Value::bool(sort_options.descending, span), "nulls_last"=> Value::bool(sort_options.nulls_last, span), "multithreaded"=> Value::bool(sort_options.multithreaded, span), "maintain_order"=> Value::bool(sort_options.maintain_order, span), ), span) } }, span) } else { Value::nothing(span) } }, "options" => Value::string(format!("{options:?}"), span), }, span, )) } Expr::SubPlan(_, _) => Err(ShellError::UnsupportedInput { msg: "Expressions of type SubPlan are not yet supported".to_string(), input: format!("Expression is {expr:?}"), msg_span: span, input_span: Span::unknown(), }), // the parameter polars_plan::dsl::selector::Selector is not publicly exposed. // I am not sure what we can meaningfully do with this at this time. Expr::Selector(_) => Err(ShellError::UnsupportedInput { msg: "Expressions of type Selector to Nu Value is not yet supported".to_string(), input: format!("Expression is {expr:?}"), msg_span: span, input_span: Span::unknown(), }), Expr::Eval { .. } => Err(ShellError::UnsupportedInput { msg: "Expressions of type Eval to Nu Value is not yet supported".to_string(), input: format!("Expression is {expr:?}"), msg_span: span, input_span: Span::unknown(), }), Expr::Field(column_name) => { let fields: Vec<Value> = column_name .iter() .map(|s| Value::string(s.to_string(), span)) .collect(); Ok(Value::record( record!( "fields" => Value::list(fields, span) ), span, )) } Expr::DataTypeFunction(func) => Ok(Value::record( record! { "expr" => Value::string("data_type_function", span), "value" => Value::string(format!("{func:?}"), span), }, span, )), Expr::Element => Ok(Value::record( record! { "expr" => Value::string("element", span), }, span, )), } } impl Cacheable for NuExpression { fn cache_id(&self) -> &Uuid { &self.id } fn to_cache_value(&self) -> Result<PolarsPluginObject, ShellError> { Ok(PolarsPluginObject::NuExpression(self.clone())) } fn from_cache_value(cv: PolarsPluginObject) -> Result<Self, ShellError> { match cv { PolarsPluginObject::NuExpression(df) => Ok(df), _ => Err(ShellError::GenericError { error: "Cache value is not an expression".into(), msg: "".into(), span: None, help: None, inner: vec![], }), } } } impl CustomValueSupport for NuExpression { type CV = NuExpressionCustomValue; fn custom_value(self) -> Self::CV { NuExpressionCustomValue { id: self.id, expr: Some(self), } } fn get_type_static() -> PolarsPluginType { PolarsPluginType::NuExpression } fn try_from_value(plugin: &PolarsPlugin, value: &Value) -> Result<Self, ShellError> { match value { Value::Custom { val, .. } => { if let Some(cv) = val.as_any().downcast_ref::<Self::CV>() { Self::try_from_custom_value(plugin, cv) } else { Err(ShellError::CantConvert { to_type: Self::get_type_static().to_string(), from_type: value.get_type().to_string(), span: value.span(), help: None, }) } } Value::String { val, .. } => Ok(val.to_owned().lit().into()), Value::Int { val, .. } => Ok(val.to_owned().lit().into()), Value::Bool { val, .. } => Ok(val.to_owned().lit().into()), Value::Float { val, .. } => Ok(val.to_owned().lit().into()), Value::Date { val, .. } => val .to_owned() .timestamp_nanos_opt() .ok_or_else(|| ShellError::GenericError { error: "Integer overflow".into(), msg: "Provided datetime in nanoseconds is too large for i64".into(), span: Some(value.span()), help: None, inner: vec![], }) .map(|nanos| -> NuExpression { nanos .lit() .strict_cast(polars::prelude::DataType::Datetime( polars::prelude::TimeUnit::Nanoseconds, None, )) .into() }), Value::Duration { val, .. } => Ok(val .to_owned() .lit() .strict_cast(polars::prelude::DataType::Duration( polars::prelude::TimeUnit::Nanoseconds, )) .into()), Value::List { vals, .. } => { NuDataFrame::try_from_iter(plugin, vals.iter().cloned(), None).and_then(|ndf| { let series = ndf.as_series(value.span())?; Ok(series.lit().into()) }) } x => Err(ShellError::CantConvert { to_type: "lazy expression".into(), from_type: x.get_type().to_string(), span: x.span(), help: None, }), } } fn can_downcast(value: &Value) -> bool { match value { Value::Custom { val, .. } => val.as_any().downcast_ref::<Self::CV>().is_some(), Value::List { vals, .. } => vals.iter().all(Self::can_downcast), Value::Record { val, .. } => val.iter().all(|(_, value)| Self::can_downcast(value)), Value::String { .. } | Value::Int { .. } | Value::Bool { .. } | Value::Float { .. } => { true } _ => false, } } fn base_value(self, _span: Span) -> Result<Value, ShellError> { self.to_value(Span::unknown()) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/values/nu_schema/custom_value.rs
crates/nu_plugin_polars/src/dataframe/values/nu_schema/custom_value.rs
use nu_protocol::{CustomValue, ShellError, Span, Value}; use serde::{Deserialize, Serialize}; use uuid::Uuid; use crate::values::{CustomValueSupport, PolarsPluginCustomValue, PolarsPluginType}; use super::NuSchema; #[derive(Clone, Debug, Deserialize, Serialize)] pub struct NuSchemaCustomValue { pub id: Uuid, #[serde(skip)] pub datatype: Option<NuSchema>, } #[typetag::serde] impl CustomValue for NuSchemaCustomValue { fn clone_value(&self, span: nu_protocol::Span) -> Value { Value::custom(Box::new(self.clone()), span) } fn type_name(&self) -> String { PolarsPluginType::NuSchema.type_name().to_string() } fn to_base_value(&self, span: Span) -> Result<Value, ShellError> { Ok(Value::string( "NuSchema: custom_value_to_base_value should've been called", span, )) } fn as_mut_any(&mut self) -> &mut dyn std::any::Any { self } fn as_any(&self) -> &dyn std::any::Any { self } fn notify_plugin_on_drop(&self) -> bool { true } } impl PolarsPluginCustomValue for NuSchemaCustomValue { type PolarsPluginObjectType = NuSchema; fn id(&self) -> &Uuid { &self.id } fn internal(&self) -> &Option<Self::PolarsPluginObjectType> { &self.datatype } fn custom_value_to_base_value( &self, plugin: &crate::PolarsPlugin, _engine: &nu_plugin::EngineInterface, ) -> Result<Value, ShellError> { let dtype = NuSchema::try_from_custom_value(plugin, self)?; dtype.base_value(Span::unknown()) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/values/nu_schema/mod.rs
crates/nu_plugin_polars/src/dataframe/values/nu_schema/mod.rs
pub mod custom_value; use std::sync::Arc; use custom_value::NuSchemaCustomValue; use nu_protocol::{ShellError, Span, Value}; use polars::prelude::{DataType, Field, Schema, SchemaExt, SchemaRef}; use uuid::Uuid; use crate::{Cacheable, PolarsPlugin}; use super::{ CustomValueSupport, NuDataType, PolarsPluginObject, PolarsPluginType, nu_dtype::fields_to_value, str_to_dtype, }; #[derive(Debug, Clone)] pub struct NuSchema { pub id: Uuid, pub schema: SchemaRef, } impl NuSchema { pub fn new(schema: SchemaRef) -> Self { Self { id: Uuid::new_v4(), schema, } } } impl From<NuSchema> for SchemaRef { fn from(val: NuSchema) -> Self { Arc::clone(&val.schema) } } impl From<SchemaRef> for NuSchema { fn from(val: SchemaRef) -> Self { Self::new(val) } } impl Cacheable for NuSchema { fn cache_id(&self) -> &Uuid { &self.id } fn to_cache_value(&self) -> Result<super::PolarsPluginObject, ShellError> { Ok(PolarsPluginObject::NuSchema(self.clone())) } fn from_cache_value(cv: super::PolarsPluginObject) -> Result<Self, ShellError> { match cv { PolarsPluginObject::NuSchema(dt) => Ok(dt), _ => Err(ShellError::GenericError { error: "Cache value is not a dataframe".into(), msg: "".into(), span: None, help: None, inner: vec![], }), } } } impl CustomValueSupport for NuSchema { type CV = NuSchemaCustomValue; fn get_type_static() -> super::PolarsPluginType { PolarsPluginType::NuSchema } fn custom_value(self) -> Self::CV { NuSchemaCustomValue { id: self.id, datatype: Some(self), } } fn base_value(self, span: Span) -> Result<Value, ShellError> { Ok(fields_to_value(self.schema.iter_fields(), span)) } fn try_from_value(plugin: &PolarsPlugin, value: &Value) -> Result<Self, ShellError> { if let Value::Custom { val, .. } = value { if let Some(cv) = val.as_any().downcast_ref::<Self::CV>() { Self::try_from_custom_value(plugin, cv) } else { Err(ShellError::CantConvert { to_type: Self::get_type_static().to_string(), from_type: value.get_type().to_string(), span: value.span(), help: None, }) } } else { let schema = value_to_schema(plugin, value, Span::unknown())?; Ok(Self::new(Arc::new(schema))) } } } fn value_to_schema(plugin: &PolarsPlugin, value: &Value, span: Span) -> Result<Schema, ShellError> { let fields = value_to_fields(plugin, value, span)?; let schema = Schema::from_iter(fields); Ok(schema) } fn value_to_fields( plugin: &PolarsPlugin, value: &Value, span: Span, ) -> Result<Vec<Field>, ShellError> { let fields = value .as_record()? .into_iter() .map(|(col, val)| match val { Value::Record { .. } => { let fields = value_to_fields(plugin, val, span)?; let dtype = DataType::Struct(fields); Ok(Field::new(col.into(), dtype)) } Value::Custom { .. } => { let dtype = NuDataType::try_from_value(plugin, val)?; Ok(Field::new(col.into(), dtype.to_polars())) } _ => { let dtype = str_to_dtype(&val.coerce_string()?, span)?; Ok(Field::new(col.into(), dtype)) } }) .collect::<Result<Vec<Field>, ShellError>>()?; Ok(fields) } #[cfg(test)] mod test { use nu_protocol::record; use super::*; #[test] fn test_value_to_schema() { let plugin = PolarsPlugin::new_test_mode().expect("Failed to create plugin"); let address = record! { "street" => Value::test_string("str"), "city" => Value::test_string("str"), }; let value = Value::test_record(record! { "name" => Value::test_string("str"), "age" => Value::test_string("i32"), "address" => Value::test_record(address) }); let schema = value_to_schema(&plugin, &value, Span::unknown()).unwrap(); let expected = Schema::from_iter(vec![ Field::new("name".into(), DataType::String), Field::new("age".into(), DataType::Int32), Field::new( "address".into(), DataType::Struct(vec![ Field::new("street".into(), DataType::String), Field::new("city".into(), DataType::String), ]), ), ]); assert_eq!(schema, expected); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/values/nu_dtype/custom_value.rs
crates/nu_plugin_polars/src/dataframe/values/nu_dtype/custom_value.rs
use nu_protocol::{CustomValue, ShellError, Span, Value}; use serde::{Deserialize, Serialize}; use uuid::Uuid; use crate::values::{CustomValueSupport, PolarsPluginCustomValue, PolarsPluginType}; use super::NuDataType; #[derive(Clone, Debug, Deserialize, Serialize)] pub struct NuDataTypeCustomValue { pub id: Uuid, #[serde(skip)] pub datatype: Option<NuDataType>, } #[typetag::serde] impl CustomValue for NuDataTypeCustomValue { fn clone_value(&self, span: nu_protocol::Span) -> Value { Value::custom(Box::new(self.clone()), span) } fn type_name(&self) -> String { PolarsPluginType::NuDataType.type_name().to_string() } fn to_base_value(&self, span: Span) -> Result<Value, ShellError> { Ok(Value::string( "NuDataType: custom_value_to_base_value should've been called", span, )) } fn as_mut_any(&mut self) -> &mut dyn std::any::Any { self } fn as_any(&self) -> &dyn std::any::Any { self } fn notify_plugin_on_drop(&self) -> bool { true } } impl PolarsPluginCustomValue for NuDataTypeCustomValue { type PolarsPluginObjectType = NuDataType; fn id(&self) -> &Uuid { &self.id } fn internal(&self) -> &Option<Self::PolarsPluginObjectType> { &self.datatype } fn custom_value_to_base_value( &self, plugin: &crate::PolarsPlugin, _engine: &nu_plugin::EngineInterface, ) -> Result<Value, ShellError> { let dtype = NuDataType::try_from_custom_value(plugin, self)?; dtype.base_value(Span::unknown()) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/values/nu_dtype/mod.rs
crates/nu_plugin_polars/src/dataframe/values/nu_dtype/mod.rs
pub mod custom_value; use custom_value::NuDataTypeCustomValue; use nu_protocol::{ShellError, Span, Value, record}; use polars::prelude::{DataType, Field, TimeUnit, UnknownKind}; use polars_compute::decimal::DEC128_MAX_PREC; use uuid::Uuid; use crate::{Cacheable, PolarsPlugin, command::datetime::timezone_from_str}; use super::{CustomValueSupport, PolarsPluginObject, PolarsPluginType}; #[derive(Debug, Clone)] pub struct NuDataType { pub id: uuid::Uuid, dtype: DataType, } impl NuDataType { pub fn new(dtype: DataType) -> Self { Self { id: uuid::Uuid::new_v4(), dtype, } } pub fn new_with_str(dtype: &str, span: Span) -> Result<Self, ShellError> { let dtype = str_to_dtype(dtype, span)?; Ok(Self { id: uuid::Uuid::new_v4(), dtype, }) } pub fn to_polars(&self) -> DataType { self.dtype.clone() } } impl From<NuDataType> for Value { fn from(nu_dtype: NuDataType) -> Self { Value::string(nu_dtype.dtype.to_string(), Span::unknown()) } } impl Cacheable for NuDataType { fn cache_id(&self) -> &Uuid { &self.id } fn to_cache_value(&self) -> Result<super::PolarsPluginObject, ShellError> { Ok(PolarsPluginObject::NuDataType(self.clone())) } fn from_cache_value(cv: super::PolarsPluginObject) -> Result<Self, ShellError> { match cv { PolarsPluginObject::NuDataType(dt) => Ok(dt), _ => Err(ShellError::GenericError { error: "Cache value is not a dataframe".into(), msg: "".into(), span: None, help: None, inner: vec![], }), } } } impl CustomValueSupport for NuDataType { type CV = NuDataTypeCustomValue; fn get_type_static() -> super::PolarsPluginType { PolarsPluginType::NuDataType } fn custom_value(self) -> Self::CV { NuDataTypeCustomValue { id: self.id, datatype: Some(self), } } fn base_value(self, span: Span) -> Result<Value, ShellError> { Ok(dtype_to_value(&self.dtype, span)) } fn try_from_value(plugin: &PolarsPlugin, value: &Value) -> Result<Self, ShellError> { let span = value.span(); match value { Value::Custom { val, .. } => { if let Some(cv) = val.as_any().downcast_ref::<Self::CV>() { Self::try_from_custom_value(plugin, cv) } else { Err(ShellError::CantConvert { to_type: Self::get_type_static().to_string(), from_type: value.get_type().to_string(), span: value.span(), help: None, }) } } Value::String { val, .. } => NuDataType::new_with_str(val, span), _ => Err(ShellError::CantConvert { to_type: Self::get_type_static().to_string(), from_type: value.get_type().to_string(), span: value.span(), help: None, }), } } } pub fn datatype_list(span: Span) -> Value { let types: Vec<Value> = [ ("null", ""), ("bool", ""), ("u8", ""), ("u16", ""), ("u32", ""), ("u64", ""), ("i8", ""), ("i16", ""), ("i32", ""), ("i64", ""), ("f32", ""), ("f64", ""), ("str", ""), ("binary", ""), ("date", ""), ("datetime<time_unit: (ms, us, ns) timezone (optional)>", "Time Unit can be: milliseconds: ms, microseconds: us, nanoseconds: ns. Timezone wildcard is *. Other Timezone examples: UTC, America/Los_Angeles."), ("duration<time_unit: (ms, us, ns)>", "Time Unit can be: milliseconds: ms, microseconds: us, nanoseconds: ns."), ("time", ""), ("object", ""), ("unknown", ""), ("list<dtype>", ""), ] .iter() .map(|(dtype, note)| { Value::record(record! { "dtype" => Value::string(*dtype, span), "note" => Value::string(*note, span), }, span) }) .collect(); Value::list(types, span) } pub fn str_to_dtype(dtype: &str, span: Span) -> Result<DataType, ShellError> { match dtype { "bool" => Ok(DataType::Boolean), "u8" => Ok(DataType::UInt8), "u16" => Ok(DataType::UInt16), "u32" => Ok(DataType::UInt32), "u64" => Ok(DataType::UInt64), "i8" => Ok(DataType::Int8), "i16" => Ok(DataType::Int16), "i32" => Ok(DataType::Int32), "i64" => Ok(DataType::Int64), "f32" => Ok(DataType::Float32), "f64" => Ok(DataType::Float64), "str" => Ok(DataType::String), "binary" => Ok(DataType::Binary), "date" => Ok(DataType::Date), "time" => Ok(DataType::Time), "null" => Ok(DataType::Null), "unknown" => Ok(DataType::Unknown(UnknownKind::Any)), "object" => Ok(DataType::Object("unknown")), _ if dtype.starts_with("list") => { let dtype = dtype .trim_start_matches("list") .trim_start_matches('<') .trim_end_matches('>') .trim(); let dtype = str_to_dtype(dtype, span)?; Ok(DataType::List(Box::new(dtype))) } _ if dtype.starts_with("datetime") => { let dtype = dtype .trim_start_matches("datetime") .trim_start_matches('<') .trim_end_matches('>'); let mut split = dtype.split(','); let next = split .next() .ok_or_else(|| ShellError::GenericError { error: "Invalid polars data type".into(), msg: "Missing time unit".into(), span: Some(span), help: None, inner: vec![], })? .trim(); let time_unit = str_to_time_unit(next, span)?; let next = split .next() .ok_or_else(|| ShellError::GenericError { error: "Invalid polars data type".into(), msg: "Missing time zone".into(), span: Some(span), help: None, inner: vec![], })? .trim(); let timezone = if "*" == next { None } else { let zone_str = next.to_string(); Some(timezone_from_str(&zone_str, None)?) }; Ok(DataType::Datetime(time_unit, timezone)) } _ if dtype.starts_with("duration") => { let inner = dtype.trim_start_matches("duration<").trim_end_matches('>'); let next = inner .split(',') .next() .ok_or_else(|| ShellError::GenericError { error: "Invalid polars data type".into(), msg: "Missing time unit".into(), span: Some(span), help: None, inner: vec![], })? .trim(); let time_unit = str_to_time_unit(next, span)?; Ok(DataType::Duration(time_unit)) } _ if dtype.starts_with("decimal") => { let dtype = dtype .trim_start_matches("decimal") .trim_start_matches('<') .trim_end_matches('>'); let mut split = dtype.split(','); let next = split .next() .ok_or_else(|| ShellError::GenericError { error: "Invalid polars data type".into(), msg: "Missing decimal precision".into(), span: Some(span), help: None, inner: vec![], })? .trim(); let precision = match next { "*" => DEC128_MAX_PREC, _ => next .parse::<usize>() .map_err(|e| ShellError::GenericError { error: "Invalid polars data type".into(), msg: format!("Error in parsing decimal precision: {e}"), span: Some(span), help: None, inner: vec![], })?, }; let next = split .next() .ok_or_else(|| ShellError::GenericError { error: "Invalid polars data type".into(), msg: "Missing decimal scale".into(), span: Some(span), help: None, inner: vec![], })? .trim(); let scale = match next { "*" => Err(ShellError::GenericError { error: "Invalid polars data type".into(), msg: "`*` is not a permitted value for scale".into(), span: Some(span), help: None, inner: vec![], }), _ => next.parse::<usize>().map_err(|e| ShellError::GenericError { error: "Invalid polars data type".into(), msg: format!("Error in parsing decimal precision: {e}"), span: Some(span), help: None, inner: vec![], }), }?; Ok(DataType::Decimal(precision, scale)) } _ => Err(ShellError::GenericError { error: "Invalid polars data type".into(), msg: format!("Unknown type: {dtype}"), span: Some(span), help: None, inner: vec![], }), } } pub(crate) fn fields_to_value(fields: impl Iterator<Item = Field>, span: Span) -> Value { let record = fields .map(|field| { let col = field.name().to_string(); let val = dtype_to_value(field.dtype(), span); (col, val) }) .collect(); Value::record(record, Span::unknown()) } pub fn str_to_time_unit(ts_string: &str, span: Span) -> Result<TimeUnit, ShellError> { match ts_string { "ms" => Ok(TimeUnit::Milliseconds), "us" | "μs" => Ok(TimeUnit::Microseconds), "ns" => Ok(TimeUnit::Nanoseconds), _ => Err(ShellError::GenericError { error: "Invalid polars data type".into(), msg: "Invalid time unit".into(), span: Some(span), help: None, inner: vec![], }), } } pub(crate) fn dtype_to_value(dtype: &DataType, span: Span) -> Value { match dtype { DataType::Struct(fields) => fields_to_value(fields.iter().cloned(), span), DataType::Enum(_, _) => Value::list( get_categories(dtype) .unwrap_or_default() .iter() .map(|s| Value::string(s, span)) .collect(), span, ), _ => Value::string(dtype.to_string().replace('[', "<").replace(']', ">"), span), } } pub(super) fn get_categories(dtype: &DataType) -> Option<Vec<String>> { if let DataType::Enum(frozen_categories, _) = dtype { Some( frozen_categories .categories() .iter() .filter_map(|v| v.map(ToString::to_string)) .collect::<Vec<String>>(), ) } else { None } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/values/nu_lazyframe/custom_value.rs
crates/nu_plugin_polars/src/dataframe/values/nu_lazyframe/custom_value.rs
use std::cmp::Ordering; use nu_plugin::EngineInterface; use nu_protocol::{CustomValue, ShellError, Span, Value}; use polars::prelude::{col, nth}; use serde::{Deserialize, Serialize}; use uuid::Uuid; use crate::{ Cacheable, PolarsPlugin, values::{ CustomValueSupport, NuDataFrame, NuExpression, PolarsPluginCustomValue, PolarsPluginType, }, }; use super::NuLazyFrame; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct NuLazyFrameCustomValue { pub id: Uuid, #[serde(skip)] pub lazyframe: Option<NuLazyFrame>, } // CustomValue implementation for NuDataFrame #[typetag::serde] impl CustomValue for NuLazyFrameCustomValue { fn clone_value(&self, span: nu_protocol::Span) -> Value { Value::custom(Box::new(self.clone()), span) } fn type_name(&self) -> String { PolarsPluginType::NuLazyFrame.type_name().to_string() } fn to_base_value(&self, span: Span) -> Result<Value, ShellError> { Ok(Value::string( "NuLazyFrameCustomValue: custom_value_to_base_value should've been called", span, )) } fn as_mut_any(&mut self) -> &mut dyn std::any::Any { self } fn as_any(&self) -> &dyn std::any::Any { self } fn notify_plugin_on_drop(&self) -> bool { true } } impl PolarsPluginCustomValue for NuLazyFrameCustomValue { type PolarsPluginObjectType = NuLazyFrame; fn custom_value_to_base_value( &self, plugin: &crate::PolarsPlugin, _engine: &nu_plugin::EngineInterface, ) -> Result<Value, ShellError> { let lazy = NuLazyFrame::try_from_custom_value(plugin, self)?; lazy.base_value(Span::unknown()) } fn id(&self) -> &Uuid { &self.id } fn internal(&self) -> &Option<Self::PolarsPluginObjectType> { &self.lazyframe } fn custom_value_partial_cmp( &self, plugin: &PolarsPlugin, _engine: &EngineInterface, other_value: Value, ) -> Result<Option<Ordering>, ShellError> { let eager = NuLazyFrame::try_from_custom_value(plugin, self)?.collect(Span::unknown())?; let other = NuDataFrame::try_from_value_coerce(plugin, &other_value, other_value.span())?; let res = eager.is_equal(&other); Ok(res) } fn custom_value_operation( &self, plugin: &PolarsPlugin, engine: &EngineInterface, lhs_span: Span, operator: nu_protocol::Spanned<nu_protocol::ast::Operator>, right: Value, ) -> Result<Value, ShellError> { let eager = NuLazyFrame::try_from_custom_value(plugin, self)?.collect(Span::unknown())?; Ok(eager .compute_with_value(plugin, lhs_span, operator.item, operator.span, &right)? .cache(plugin, engine, lhs_span)? .into_value(lhs_span)) } fn custom_value_follow_path_int( &self, plugin: &PolarsPlugin, engine: &EngineInterface, _self_span: Span, index: nu_protocol::Spanned<usize>, ) -> Result<Value, ShellError> { let expr = NuExpression::from(nth(index.item as i64).as_expr()); expr.cache_and_to_value(plugin, engine, index.span) } fn custom_value_follow_path_string( &self, plugin: &PolarsPlugin, engine: &EngineInterface, _self_span: Span, column_name: nu_protocol::Spanned<String>, ) -> Result<Value, ShellError> { let expr = NuExpression::from(col(column_name.item)); expr.cache_and_to_value(plugin, engine, column_name.span) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/values/nu_lazyframe/mod.rs
crates/nu_plugin_polars/src/dataframe/values/nu_lazyframe/mod.rs
mod custom_value; use crate::{Cacheable, PolarsPlugin}; use super::{ CustomValueSupport, NuDataFrame, NuExpression, NuSchema, PolarsPluginObject, PolarsPluginType, cant_convert_err, }; use core::fmt; use nu_protocol::{PipelineData, ShellError, Span, Value, record}; use polars::prelude::{Expr, IntoLazy, LazyFrame}; use std::sync::Arc; use uuid::Uuid; pub use custom_value::NuLazyFrameCustomValue; // Lazyframe wrapper for Nushell operations // Polars LazyFrame is behind and Option to allow easy implementation of // the Deserialize trait #[derive(Default, Clone)] pub struct NuLazyFrame { pub id: Uuid, pub lazy: Arc<LazyFrame>, pub from_eager: bool, } impl fmt::Debug for NuLazyFrame { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "NuLazyframe") } } impl From<LazyFrame> for NuLazyFrame { fn from(lazy_frame: LazyFrame) -> Self { NuLazyFrame::new(false, lazy_frame) } } impl NuLazyFrame { pub fn new(from_eager: bool, lazy: LazyFrame) -> Self { Self { id: Uuid::new_v4(), lazy: Arc::new(lazy), from_eager, } } pub fn from_dataframe(df: NuDataFrame) -> Self { let lazy = df.as_ref().clone().lazy(); NuLazyFrame::new(true, lazy) } pub fn to_polars(&self) -> LazyFrame { (*self.lazy).clone() } pub fn collect(self, span: Span) -> Result<NuDataFrame, ShellError> { crate::handle_panic( || { self.to_polars() .collect() .map_err(|e| ShellError::GenericError { error: "Error collecting lazy frame".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], }) .map(|df| NuDataFrame::new(true, df)) }, span, ) } pub fn apply_with_expr<F>(self, expr: NuExpression, f: F) -> Self where F: Fn(LazyFrame, Expr) -> LazyFrame, { let df = self.to_polars(); let expr = expr.into_polars(); let new_frame = f(df, expr); Self::new(self.from_eager, new_frame) } pub fn schema(&mut self) -> Result<NuSchema, ShellError> { let internal_schema = Arc::make_mut(&mut self.lazy) .collect_schema() .map_err(|e| ShellError::GenericError { error: "Error getting schema from lazy frame".into(), msg: e.to_string(), span: None, help: None, inner: vec![], })?; Ok(internal_schema.into()) } /// Get a NuLazyFrame from the value. This differs from try_from_value as it will coerce a /// NuDataFrame into a NuLazyFrame pub fn try_from_value_coerce( plugin: &PolarsPlugin, value: &Value, ) -> Result<NuLazyFrame, ShellError> { match PolarsPluginObject::try_from_value(plugin, value)? { PolarsPluginObject::NuDataFrame(df) => Ok(df.lazy()), PolarsPluginObject::NuLazyFrame(lazy) => Ok(lazy), _ => Err(cant_convert_err( value, &[PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame], )), } } /// This differs from try_from_pipeline as it will attempt to coerce the type into a NuDataFrame. /// So, if the pipeline type is a NuLazyFrame it will be collected and returned as NuDataFrame. pub fn try_from_pipeline_coerce( plugin: &PolarsPlugin, input: PipelineData, span: Span, ) -> Result<Self, ShellError> { let value = input.into_value(span)?; Self::try_from_value_coerce(plugin, &value) } } impl Cacheable for NuLazyFrame { fn cache_id(&self) -> &Uuid { &self.id } fn to_cache_value(&self) -> Result<PolarsPluginObject, ShellError> { Ok(PolarsPluginObject::NuLazyFrame(self.clone())) } fn from_cache_value(cv: PolarsPluginObject) -> Result<Self, ShellError> { match cv { PolarsPluginObject::NuLazyFrame(df) => Ok(df), _ => Err(ShellError::GenericError { error: "Cache value is not a lazyframe".into(), msg: "".into(), span: None, help: None, inner: vec![], }), } } } impl CustomValueSupport for NuLazyFrame { type CV = NuLazyFrameCustomValue; fn custom_value(self) -> Self::CV { NuLazyFrameCustomValue { id: self.id, lazyframe: Some(self), } } fn get_type_static() -> PolarsPluginType { PolarsPluginType::NuLazyFrame } fn base_value(self, span: Span) -> Result<Value, ShellError> { let optimized_plan = self .lazy .describe_optimized_plan() .unwrap_or_else(|_| "<NOT AVAILABLE>".to_string()); Ok(Value::record( record! { "plan" => Value::string( self.lazy.describe_plan().map_err(|e| ShellError::GenericError { error: "Error getting plan".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], })?, span), "optimized_plan" => Value::string(optimized_plan, span), }, span, )) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/values/nu_dataframe/between_values.rs
crates/nu_plugin_polars/src/dataframe/values/nu_dataframe/between_values.rs
use super::{NuDataFrame, operations::Axis}; use nu_protocol::{ ShellError, Span, Spanned, Value, ast::{Boolean, Comparison, Math, Operator}, }; use num::Zero; use polars::prelude::{ BooleanType, ChunkCompareEq, ChunkCompareIneq, ChunkedArray, DataType, Float64Type, Int64Type, IntoSeries, NumOpsDispatchChecked, PolarsError, Series, StringNameSpaceImpl, }; use std::ops::{Add, BitAnd, BitOr, Div, Mul, Sub}; pub(super) fn between_dataframes( operator: Spanned<Operator>, left: &Value, lhs: &NuDataFrame, right: &Value, rhs: &NuDataFrame, ) -> Result<NuDataFrame, ShellError> { match operator.item { Operator::Math(Math::Add) => { lhs.append_df(rhs, Axis::Row, Span::merge(left.span(), right.span())) } op => Err(ShellError::OperatorUnsupportedType { op, unsupported: left.get_type(), op_span: operator.span, unsupported_span: left.span(), help: None, }), } } pub(super) fn compute_between_series( operator: Spanned<Operator>, left: &Value, lhs: &Series, right: &Value, rhs: &Series, ) -> Result<NuDataFrame, ShellError> { let operation_span = Span::merge(left.span(), right.span()); match operator.item { Operator::Math(Math::Add) => { let mut res = (lhs + rhs).map_err(|e| ShellError::GenericError { error: format!("Addition error: {e}"), msg: "".into(), span: Some(operation_span), help: None, inner: vec![], })?; let name = format!("sum_{}_{}", lhs.name(), rhs.name()); res.rename(name.into()); NuDataFrame::try_from_series(res, operation_span) } Operator::Math(Math::Subtract) => { let mut res = (lhs - rhs).map_err(|e| ShellError::GenericError { error: format!("Subtraction error: {e}"), msg: "".into(), span: Some(operation_span), help: None, inner: vec![], })?; let name = format!("sub_{}_{}", lhs.name(), rhs.name()); res.rename(name.into()); NuDataFrame::try_from_series(res, operation_span) } Operator::Math(Math::Multiply) => { let mut res = (lhs * rhs).map_err(|e| ShellError::GenericError { error: format!("Multiplication error: {e}"), msg: "".into(), span: Some(operation_span), help: None, inner: vec![], })?; let name = format!("mul_{}_{}", lhs.name(), rhs.name()); res.rename(name.into()); NuDataFrame::try_from_series(res, operation_span) } Operator::Math(Math::Divide) => { let res = lhs.checked_div(rhs); match res { Ok(mut res) => { let name = format!("div_{}_{}", lhs.name(), rhs.name()); res.rename(name.into()); NuDataFrame::try_from_series(res, operation_span) } Err(e) => Err(ShellError::GenericError { error: "Division error".into(), msg: e.to_string(), span: Some(right.span()), help: None, inner: vec![], }), } } Operator::Comparison(Comparison::Equal) => { let name = format!("eq_{}_{}", lhs.name(), rhs.name()); let res = compare_series(lhs, rhs, name.as_str(), right.span(), Series::equal)?; NuDataFrame::try_from_series(res, operation_span) } Operator::Comparison(Comparison::NotEqual) => { let name = format!("neq_{}_{}", lhs.name(), rhs.name()); let res = compare_series(lhs, rhs, name.as_str(), right.span(), Series::not_equal)?; NuDataFrame::try_from_series(res, operation_span) } Operator::Comparison(Comparison::LessThan) => { let name = format!("lt_{}_{}", lhs.name(), rhs.name()); let res = compare_series(lhs, rhs, name.as_str(), right.span(), Series::lt)?; NuDataFrame::try_from_series(res, operation_span) } Operator::Comparison(Comparison::LessThanOrEqual) => { let name = format!("lte_{}_{}", lhs.name(), rhs.name()); let res = compare_series(lhs, rhs, name.as_str(), right.span(), Series::lt_eq)?; NuDataFrame::try_from_series(res, operation_span) } Operator::Comparison(Comparison::GreaterThan) => { let name = format!("gt_{}_{}", lhs.name(), rhs.name()); let res = compare_series(lhs, rhs, name.as_str(), right.span(), Series::gt)?; NuDataFrame::try_from_series(res, operation_span) } Operator::Comparison(Comparison::GreaterThanOrEqual) => { let name = format!("gte_{}_{}", lhs.name(), rhs.name()); let res = compare_series(lhs, rhs, name.as_str(), right.span(), Series::gt_eq)?; NuDataFrame::try_from_series(res, operation_span) } Operator::Boolean(Boolean::And) => match lhs.dtype() { DataType::Boolean => { let lhs_cast = lhs.bool(); let rhs_cast = rhs.bool(); match (lhs_cast, rhs_cast) { (Ok(l), Ok(r)) => { let mut res = l.bitand(r).into_series(); let name = format!("and_{}_{}", lhs.name(), rhs.name()); res.rename(name.into()); NuDataFrame::try_from_series(res, operation_span) } _ => Err(ShellError::GenericError { error: "Incompatible types".into(), msg: "unable to cast to boolean".into(), span: Some(right.span()), help: None, inner: vec![], }), } } _ => Err(ShellError::IncompatibleParametersSingle { msg: format!( "Operation {} can only be done with boolean values", operator.item ), span: operation_span, }), }, Operator::Boolean(Boolean::Or) => match lhs.dtype() { DataType::Boolean => { let lhs_cast = lhs.bool(); let rhs_cast = rhs.bool(); match (lhs_cast, rhs_cast) { (Ok(l), Ok(r)) => { let mut res = l.bitor(r).into_series(); let name = format!("or_{}_{}", lhs.name(), rhs.name()); res.rename(name.into()); NuDataFrame::try_from_series(res, operation_span) } _ => Err(ShellError::GenericError { error: "Incompatible types".into(), msg: "unable to cast to boolean".into(), span: Some(right.span()), help: None, inner: vec![], }), } } _ => Err(ShellError::IncompatibleParametersSingle { msg: format!( "Operation {} can only be done with boolean values", operator.item ), span: operation_span, }), }, op => Err(ShellError::OperatorUnsupportedType { op, unsupported: left.get_type(), op_span: operator.span, unsupported_span: left.span(), help: None, }), } } fn compare_series<'s, F>( lhs: &'s Series, rhs: &'s Series, name: &'s str, span: Span, f: F, ) -> Result<Series, ShellError> where F: Fn(&'s Series, &'s Series) -> Result<ChunkedArray<BooleanType>, PolarsError>, { let mut res = f(lhs, rhs) .map_err(|e| ShellError::GenericError { error: "Equality error".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], })? .into_series(); res.rename(name.into()); Ok(res) } pub(super) fn compute_series_single_value( operator: Spanned<Operator>, left: &Value, lhs: &NuDataFrame, right: &Value, ) -> Result<NuDataFrame, ShellError> { if !lhs.is_series() { return Err(ShellError::OperatorUnsupportedType { op: operator.item, unsupported: left.get_type(), op_span: operator.span, unsupported_span: left.span(), help: None, }); } let lhs_span = left.span(); let lhs = lhs.as_series(lhs_span)?; match operator.item { Operator::Math(Math::Add) => match &right { Value::Int { val, .. } => { compute_series_i64(&lhs, *val, <ChunkedArray<Int64Type>>::add, lhs_span) } Value::Float { val, .. } => { compute_series_float(&lhs, *val, <ChunkedArray<Float64Type>>::add, lhs_span) } Value::String { val, .. } => add_string_to_series(&lhs, val, lhs_span), _ => Err(ShellError::OperatorUnsupportedType { op: operator.item, unsupported: right.get_type(), op_span: operator.span, unsupported_span: right.span(), help: None, }), }, Operator::Math(Math::Subtract) => match &right { Value::Int { val, .. } => { compute_series_i64(&lhs, *val, <ChunkedArray<Int64Type>>::sub, lhs_span) } Value::Float { val, .. } => { compute_series_float(&lhs, *val, <ChunkedArray<Float64Type>>::sub, lhs_span) } _ => Err(ShellError::OperatorUnsupportedType { op: operator.item, unsupported: right.get_type(), op_span: operator.span, unsupported_span: right.span(), help: None, }), }, Operator::Math(Math::Multiply) => match &right { Value::Int { val, .. } => { compute_series_i64(&lhs, *val, <ChunkedArray<Int64Type>>::mul, lhs_span) } Value::Float { val, .. } => { compute_series_float(&lhs, *val, <ChunkedArray<Float64Type>>::mul, lhs_span) } _ => Err(ShellError::OperatorUnsupportedType { op: operator.item, unsupported: right.get_type(), op_span: operator.span, unsupported_span: right.span(), help: None, }), }, Operator::Math(Math::Divide) => { let span = right.span(); match &right { Value::Int { val, .. } => { if *val == 0 { Err(ShellError::DivisionByZero { span }) } else { compute_series_i64(&lhs, *val, <ChunkedArray<Int64Type>>::div, lhs_span) } } Value::Float { val, .. } => { if val.is_zero() { Err(ShellError::DivisionByZero { span }) } else { compute_series_float(&lhs, *val, <ChunkedArray<Float64Type>>::div, lhs_span) } } _ => Err(ShellError::OperatorUnsupportedType { op: operator.item, unsupported: right.get_type(), op_span: operator.span, unsupported_span: right.span(), help: None, }), } } Operator::Comparison(Comparison::Equal) => match &right { Value::Int { val, .. } => compare_series_i64(&lhs, *val, ChunkedArray::equal, lhs_span), Value::Float { val, .. } => { compare_series_float(&lhs, *val, ChunkedArray::equal, lhs_span) } Value::String { val, .. } => { let equal_pattern = format!("^{}$", fancy_regex::escape(val)); contains_series_pat(&lhs, &equal_pattern, lhs_span) } Value::Date { val, .. } => { compare_series_i64(&lhs, val.timestamp_millis(), ChunkedArray::equal, lhs_span) } _ => Err(ShellError::OperatorUnsupportedType { op: operator.item, unsupported: right.get_type(), op_span: operator.span, unsupported_span: right.span(), help: None, }), }, Operator::Comparison(Comparison::NotEqual) => match &right { Value::Int { val, .. } => { compare_series_i64(&lhs, *val, ChunkedArray::not_equal, lhs_span) } Value::Float { val, .. } => { compare_series_float(&lhs, *val, ChunkedArray::not_equal, lhs_span) } Value::String { val, .. } => { let equal_pattern = format!("^{}$", fancy_regex::escape(val)); contains_series_pat(&lhs, &equal_pattern, lhs_span) } Value::Date { val, .. } => compare_series_i64( &lhs, val.timestamp_millis(), ChunkedArray::not_equal, lhs_span, ), _ => Err(ShellError::OperatorUnsupportedType { op: operator.item, unsupported: right.get_type(), op_span: operator.span, unsupported_span: right.span(), help: None, }), }, Operator::Comparison(Comparison::LessThan) => match &right { Value::Int { val, .. } => compare_series_i64(&lhs, *val, ChunkedArray::lt, lhs_span), Value::Float { val, .. } => { compare_series_float(&lhs, *val, ChunkedArray::lt, lhs_span) } Value::Date { val, .. } => { compare_series_i64(&lhs, val.timestamp_millis(), ChunkedArray::lt, lhs_span) } _ => Err(ShellError::OperatorUnsupportedType { op: operator.item, unsupported: right.get_type(), op_span: operator.span, unsupported_span: right.span(), help: None, }), }, Operator::Comparison(Comparison::LessThanOrEqual) => match &right { Value::Int { val, .. } => compare_series_i64(&lhs, *val, ChunkedArray::lt_eq, lhs_span), Value::Float { val, .. } => { compare_series_float(&lhs, *val, ChunkedArray::lt_eq, lhs_span) } Value::Date { val, .. } => { compare_series_i64(&lhs, val.timestamp_millis(), ChunkedArray::lt_eq, lhs_span) } _ => Err(ShellError::OperatorUnsupportedType { op: operator.item, unsupported: right.get_type(), op_span: operator.span, unsupported_span: right.span(), help: None, }), }, Operator::Comparison(Comparison::GreaterThan) => match &right { Value::Int { val, .. } => compare_series_i64(&lhs, *val, ChunkedArray::gt, lhs_span), Value::Float { val, .. } => { compare_series_float(&lhs, *val, ChunkedArray::gt, lhs_span) } Value::Date { val, .. } => { compare_series_i64(&lhs, val.timestamp_millis(), ChunkedArray::gt, lhs_span) } _ => Err(ShellError::OperatorUnsupportedType { op: operator.item, unsupported: right.get_type(), op_span: operator.span, unsupported_span: right.span(), help: None, }), }, Operator::Comparison(Comparison::GreaterThanOrEqual) => match &right { Value::Int { val, .. } => compare_series_i64(&lhs, *val, ChunkedArray::gt_eq, lhs_span), Value::Float { val, .. } => { compare_series_float(&lhs, *val, ChunkedArray::gt_eq, lhs_span) } Value::Date { val, .. } => { compare_series_i64(&lhs, val.timestamp_millis(), ChunkedArray::gt_eq, lhs_span) } _ => Err(ShellError::OperatorUnsupportedType { op: operator.item, unsupported: right.get_type(), op_span: operator.span, unsupported_span: right.span(), help: None, }), }, // TODO: update this to do a regex match instead of a simple contains? Operator::Comparison(Comparison::RegexMatch) => match &right { Value::String { val, .. } => contains_series_pat(&lhs, val, lhs_span), _ => Err(ShellError::OperatorUnsupportedType { op: operator.item, unsupported: right.get_type(), op_span: operator.span, unsupported_span: right.span(), help: None, }), }, Operator::Comparison(Comparison::StartsWith) => match &right { Value::String { val, .. } => { let starts_with_pattern = format!("^{}", fancy_regex::escape(val)); contains_series_pat(&lhs, &starts_with_pattern, lhs_span) } _ => Err(ShellError::OperatorUnsupportedType { op: operator.item, unsupported: right.get_type(), op_span: operator.span, unsupported_span: right.span(), help: None, }), }, Operator::Comparison(Comparison::EndsWith) => match &right { Value::String { val, .. } => { let ends_with_pattern = format!("{}$", fancy_regex::escape(val)); contains_series_pat(&lhs, &ends_with_pattern, lhs_span) } _ => Err(ShellError::OperatorUnsupportedType { op: operator.item, unsupported: right.get_type(), op_span: operator.span, unsupported_span: right.span(), help: None, }), }, _ => Err(ShellError::OperatorUnsupportedType { op: operator.item, unsupported: left.get_type(), op_span: operator.span, unsupported_span: left.span(), help: None, }), } } fn compute_series_i64<F>( series: &Series, val: i64, f: F, span: Span, ) -> Result<NuDataFrame, ShellError> where F: Fn(ChunkedArray<Int64Type>, i64) -> ChunkedArray<Int64Type>, { match series.dtype() { DataType::UInt32 | DataType::Int32 | DataType::UInt64 => { let to_i64 = series.cast(&DataType::Int64); match to_i64 { Ok(series) => { let casted = series.i64(); compute_casted_i64(casted, val, f, span) } Err(e) => Err(ShellError::GenericError { error: "Unable to cast to i64".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], }), } } DataType::Int64 => { let casted = series.i64(); compute_casted_i64(casted, val, f, span) } _ => Err(ShellError::GenericError { error: "Incorrect type".into(), msg: format!( "Series of type {} can not be used for operations with an i64 value", series.dtype() ), span: Some(span), help: None, inner: vec![], }), } } fn compute_casted_i64<F>( casted: Result<&ChunkedArray<Int64Type>, PolarsError>, val: i64, f: F, span: Span, ) -> Result<NuDataFrame, ShellError> where F: Fn(ChunkedArray<Int64Type>, i64) -> ChunkedArray<Int64Type>, { match casted { Ok(casted) => { let res = f(casted.clone(), val); let res = res.into_series(); NuDataFrame::try_from_series(res, span) } Err(e) => Err(ShellError::GenericError { error: "Unable to cast to i64".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], }), } } fn compute_series_float<F>( series: &Series, val: f64, f: F, span: Span, ) -> Result<NuDataFrame, ShellError> where F: Fn(ChunkedArray<Float64Type>, f64) -> ChunkedArray<Float64Type>, { match series.dtype() { DataType::Float32 => { let to_f64 = series.cast(&DataType::Float64); match to_f64 { Ok(series) => { let casted = series.f64(); compute_casted_f64(casted, val, f, span) } Err(e) => Err(ShellError::GenericError { error: "Unable to cast to f64".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], }), } } DataType::Float64 => { let casted = series.f64(); compute_casted_f64(casted, val, f, span) } _ => Err(ShellError::GenericError { error: "Incorrect type".into(), msg: format!( "Series of type {} can not be used for operations with a float value", series.dtype() ), span: Some(span), help: None, inner: vec![], }), } } fn compute_casted_f64<F>( casted: Result<&ChunkedArray<Float64Type>, PolarsError>, val: f64, f: F, span: Span, ) -> Result<NuDataFrame, ShellError> where F: Fn(ChunkedArray<Float64Type>, f64) -> ChunkedArray<Float64Type>, { match casted { Ok(casted) => { let res = f(casted.clone(), val); let res = res.into_series(); NuDataFrame::try_from_series(res, span) } Err(e) => Err(ShellError::GenericError { error: "Unable to cast to f64".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], }), } } fn compare_series_i64<F>( series: &Series, val: i64, f: F, span: Span, ) -> Result<NuDataFrame, ShellError> where F: Fn(&ChunkedArray<Int64Type>, i64) -> ChunkedArray<BooleanType>, { match series.dtype() { DataType::UInt32 | DataType::Int32 | DataType::UInt64 | DataType::Datetime(_, _) => { let to_i64 = series.cast(&DataType::Int64); match to_i64 { Ok(series) => { let casted = series.i64(); compare_casted_i64(casted, val, f, span) } Err(e) => Err(ShellError::GenericError { error: "Unable to cast to f64".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], }), } } DataType::Date => { let to_i64 = series.cast(&DataType::Int64); match to_i64 { Ok(series) => { let nanosecs_per_day: i64 = 24 * 60 * 60 * 1_000_000_000; let casted = series .i64() .map(|chunked| chunked.mul(nanosecs_per_day)) .expect("already checked for casting"); compare_casted_i64(Ok(&casted), val, f, span) } Err(e) => Err(ShellError::GenericError { error: "Unable to cast to f64".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], }), } } DataType::Int64 => { let casted = series.i64(); compare_casted_i64(casted, val, f, span) } _ => Err(ShellError::GenericError { error: "Incorrect type".into(), msg: format!( "Series of type {} can not be used for operations with an i64 value", series.dtype() ), span: Some(span), help: None, inner: vec![], }), } } fn compare_casted_i64<F>( casted: Result<&ChunkedArray<Int64Type>, PolarsError>, val: i64, f: F, span: Span, ) -> Result<NuDataFrame, ShellError> where F: Fn(&ChunkedArray<Int64Type>, i64) -> ChunkedArray<BooleanType>, { match casted { Ok(casted) => { let res = f(casted, val); let res = res.into_series(); NuDataFrame::try_from_series(res, span) } Err(e) => Err(ShellError::GenericError { error: "Unable to cast to i64".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], }), } } fn compare_series_float<F>( series: &Series, val: f64, f: F, span: Span, ) -> Result<NuDataFrame, ShellError> where F: Fn(&ChunkedArray<Float64Type>, f64) -> ChunkedArray<BooleanType>, { match series.dtype() { DataType::Float32 => { let to_f64 = series.cast(&DataType::Float64); match to_f64 { Ok(series) => { let casted = series.f64(); compare_casted_f64(casted, val, f, span) } Err(e) => Err(ShellError::GenericError { error: "Unable to cast to i64".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], }), } } DataType::Float64 => { let casted = series.f64(); compare_casted_f64(casted, val, f, span) } _ => Err(ShellError::GenericError { error: "Incorrect type".into(), msg: format!( "Series of type {} can not be used for operations with a float value", series.dtype() ), span: Some(span), help: None, inner: vec![], }), } } fn compare_casted_f64<F>( casted: Result<&ChunkedArray<Float64Type>, PolarsError>, val: f64, f: F, span: Span, ) -> Result<NuDataFrame, ShellError> where F: Fn(&ChunkedArray<Float64Type>, f64) -> ChunkedArray<BooleanType>, { match casted { Ok(casted) => { let res = f(casted, val); let res = res.into_series(); NuDataFrame::try_from_series(res, span) } Err(e) => Err(ShellError::GenericError { error: "Unable to cast to f64".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], }), } } fn contains_series_pat(series: &Series, pat: &str, span: Span) -> Result<NuDataFrame, ShellError> { let casted = series.str(); match casted { Ok(casted) => { let res = casted.contains(pat, false); match res { Ok(res) => { let res = res.into_series(); NuDataFrame::try_from_series(res, span) } Err(e) => Err(ShellError::GenericError { error: "Error using contains".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], }), } } Err(e) => Err(ShellError::GenericError { error: "Unable to cast to string".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], }), } } fn add_string_to_series(series: &Series, pat: &str, span: Span) -> Result<NuDataFrame, ShellError> { let casted = series.str(); match casted { Ok(casted) => { let res = casted + pat; let res = res.into_series(); NuDataFrame::try_from_series(res, span) } Err(e) => Err(ShellError::GenericError { error: "Unable to cast to string".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], }), } } #[cfg(test)] mod test { use super::*; use nu_protocol::Span; use polars::{prelude::NamedFrom, series::Series}; use crate::{dataframe::values::NuDataFrame, values::CustomValueSupport}; #[test] fn test_compute_between_series_comparisons() { let series = Series::new("c".into(), &[1, 2]); let df = NuDataFrame::try_from_series_vec(vec![series], Span::test_data()) .expect("should be able to create a simple dataframe"); let c0 = df .column("c", Span::test_data()) .expect("should be able to get column c"); let c0_series = c0 .as_series(Span::test_data()) .expect("should be able to get series"); let c0_value = c0.into_value(Span::test_data()); let c1 = df .column("c", Span::test_data()) .expect("should be able to get column c"); let c1_series = c1 .as_series(Span::test_data()) .expect("should be able to get series"); let c1_value = c1.into_value(Span::test_data()); let op = Spanned { item: Operator::Comparison(Comparison::NotEqual), span: Span::test_data(), }; let result = compute_between_series(op, &c0_value, &c0_series, &c1_value, &c1_series) .expect("compare should not fail"); let result = result .as_series(Span::test_data()) .expect("should be convert to a series"); assert_eq!(result, Series::new("neq_c_c".into(), &[false, false])); let op = Spanned { item: Operator::Comparison(Comparison::Equal), span: Span::test_data(), }; let result = compute_between_series(op, &c0_value, &c0_series, &c1_value, &c1_series) .expect("compare should not fail"); let result = result .as_series(Span::test_data()) .expect("should be convert to a series"); assert_eq!(result, Series::new("eq_c_c".into(), &[true, true])); let op = Spanned { item: Operator::Comparison(Comparison::LessThan), span: Span::test_data(), }; let result = compute_between_series(op, &c0_value, &c0_series, &c1_value, &c1_series) .expect("compare should not fail"); let result = result .as_series(Span::test_data()) .expect("should be convert to a series"); assert_eq!(result, Series::new("lt_c_c".into(), &[false, false])); let op = Spanned { item: Operator::Comparison(Comparison::LessThanOrEqual), span: Span::test_data(), }; let result = compute_between_series(op, &c0_value, &c0_series, &c1_value, &c1_series) .expect("compare should not fail"); let result = result .as_series(Span::test_data()) .expect("should be convert to a series"); assert_eq!(result, Series::new("lte_c_c".into(), &[true, true])); let op = Spanned { item: Operator::Comparison(Comparison::GreaterThan), span: Span::test_data(), }; let result = compute_between_series(op, &c0_value, &c0_series, &c1_value, &c1_series) .expect("compare should not fail"); let result = result .as_series(Span::test_data()) .expect("should be convert to a series"); assert_eq!(result, Series::new("gt_c_c".into(), &[false, false])); let op = Spanned { item: Operator::Comparison(Comparison::GreaterThanOrEqual), span: Span::test_data(), };
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
true
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/values/nu_dataframe/custom_value.rs
crates/nu_plugin_polars/src/dataframe/values/nu_dataframe/custom_value.rs
use std::cmp::Ordering; use nu_plugin::EngineInterface; use nu_protocol::{CustomValue, ShellError, Span, Spanned, Value}; use serde::{Deserialize, Serialize}; use uuid::Uuid; use crate::{ Cacheable, PolarsPlugin, values::{CustomValueSupport, PolarsPluginCustomValue, PolarsPluginType}, }; use super::NuDataFrame; #[derive(Debug, Clone, Deserialize, Serialize)] pub struct NuDataFrameCustomValue { pub id: Uuid, #[serde(skip)] pub dataframe: Option<NuDataFrame>, } // CustomValue implementation for NuDataFrame #[typetag::serde] impl CustomValue for NuDataFrameCustomValue { fn clone_value(&self, span: nu_protocol::Span) -> Value { Value::custom(Box::new(self.clone()), span) } fn type_name(&self) -> String { PolarsPluginType::NuDataFrame.type_name().to_string() } fn to_base_value(&self, span: Span) -> Result<Value, ShellError> { Ok(Value::string( "NuDataFrameValue: custom_value_to_base_value should've been called", span, )) } fn as_mut_any(&mut self) -> &mut dyn std::any::Any { self } fn as_any(&self) -> &dyn std::any::Any { self } fn notify_plugin_on_drop(&self) -> bool { true } } impl PolarsPluginCustomValue for NuDataFrameCustomValue { type PolarsPluginObjectType = NuDataFrame; fn id(&self) -> &Uuid { &self.id } fn internal(&self) -> &Option<Self::PolarsPluginObjectType> { &self.dataframe } fn custom_value_to_base_value( &self, plugin: &crate::PolarsPlugin, _engine: &nu_plugin::EngineInterface, ) -> Result<Value, ShellError> { let df = NuDataFrame::try_from_custom_value(plugin, self)?; df.base_value(Span::unknown()) } fn custom_value_operation( &self, plugin: &crate::PolarsPlugin, engine: &nu_plugin::EngineInterface, lhs_span: Span, operator: nu_protocol::Spanned<nu_protocol::ast::Operator>, right: Value, ) -> Result<Value, ShellError> { let df = NuDataFrame::try_from_custom_value(plugin, self)?; Ok(df .compute_with_value(plugin, lhs_span, operator.item, operator.span, &right)? .cache(plugin, engine, lhs_span)? .into_value(lhs_span)) } fn custom_value_follow_path_int( &self, plugin: &PolarsPlugin, _engine: &EngineInterface, _self_span: Span, index: Spanned<usize>, ) -> Result<Value, ShellError> { let df = NuDataFrame::try_from_custom_value(plugin, self)?; df.get_value(index.item, index.span) } fn custom_value_follow_path_string( &self, plugin: &PolarsPlugin, engine: &EngineInterface, self_span: Span, column_name: Spanned<String>, ) -> Result<Value, ShellError> { let df = NuDataFrame::try_from_custom_value(plugin, self)?; let column = df.column(&column_name.item, self_span)?; Ok(column .cache(plugin, engine, self_span)? .into_value(self_span)) } fn custom_value_partial_cmp( &self, plugin: &PolarsPlugin, _engine: &EngineInterface, other_value: Value, ) -> Result<Option<Ordering>, ShellError> { let df = NuDataFrame::try_from_custom_value(plugin, self)?; let other = NuDataFrame::try_from_value_coerce(plugin, &other_value, other_value.span())?; let res = df.is_equal(&other); Ok(res) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/values/nu_dataframe/conversion.rs
crates/nu_plugin_polars/src/dataframe/values/nu_dataframe/conversion.rs
use std::collections::HashMap; use std::ops::{Deref, DerefMut}; use std::sync::Arc; use chrono::{DateTime, Duration, FixedOffset, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Utc}; use chrono_tz::Tz; use indexmap::map::{Entry, IndexMap}; use polars::chunked_array::ChunkedArray; use polars::chunked_array::builder::AnonymousOwnedListBuilder; use polars::chunked_array::object::builder::ObjectChunkedBuilder; use polars::datatypes::{AnyValue, PlSmallStr}; use polars::prelude::{ CatSize, ChunkAnyValue, Column as PolarsColumn, DataFrame, DataType, DatetimeChunked, Float32Type, Float64Type, Int8Type, Int16Type, Int32Type, Int64Type, IntoSeries, ListBooleanChunkedBuilder, ListBuilderTrait, ListPrimitiveChunkedBuilder, ListStringChunkedBuilder, ListType, LogicalType, NamedFrom, NewChunkedArray, ObjectType, PolarsError, Schema, SchemaExt, Series, StructChunked, TemporalMethods, TimeUnit, TimeZone as PolarsTimeZone, UInt8Type, UInt16Type, UInt32Type, UInt64Type, }; use nu_protocol::{Record, ShellError, Span, Value}; use polars_arrow::Either; use polars_arrow::array::Utf8ViewArray; use crate::command::datetime::timezone_utc; use crate::dataframe::values::NuSchema; use super::{DataFrameValue, NuDataFrame}; const NANOS_PER_DAY: i64 = 86_400_000_000_000; // The values capacity is for the size of an vec. // Since this is impossible to determine without traversing every value // I just picked one. Since this is for converting back and forth // between nushell tables the values shouldn't be too extremely large for // practical reasons (~ a few thousand rows). const VALUES_CAPACITY: usize = 10; macro_rules! value_to_primitive { ($value:ident, u8) => { value_to_int($value).map(|v| v as u8) }; ($value:ident, u16) => { value_to_int($value).map(|v| v as u16) }; ($value:ident, u32) => { value_to_int($value).map(|v| v as u32) }; ($value:ident, u64) => { value_to_int($value).map(|v| v as u64) }; ($value:ident, i8) => { value_to_int($value).map(|v| v as i8) }; ($value:ident, i16) => { value_to_int($value).map(|v| v as i16) }; ($value:ident, i32) => { value_to_int($value).map(|v| v as i32) }; ($value:ident, i64) => { value_to_int($value) }; ($value:ident, f32) => { $value.as_float().map(|v| v as f32) }; ($value:ident, f64) => { $value.as_float() }; } #[derive(Debug)] pub struct Column { name: PlSmallStr, values: Vec<Value>, } impl Column { pub fn new(name: impl Into<PlSmallStr>, values: Vec<Value>) -> Self { Self { name: name.into(), values, } } pub fn new_empty(name: PlSmallStr) -> Self { Self { name, values: Vec::new(), } } pub fn name(&self) -> &PlSmallStr { &self.name } } impl IntoIterator for Column { type Item = Value; type IntoIter = std::vec::IntoIter<Self::Item>; fn into_iter(self) -> Self::IntoIter { self.values.into_iter() } } impl Deref for Column { type Target = Vec<Value>; fn deref(&self) -> &Self::Target { &self.values } } impl DerefMut for Column { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.values } } #[derive(Debug)] pub struct TypedColumn { column: Column, column_type: Option<DataType>, } impl TypedColumn { fn new_empty(name: PlSmallStr) -> Self { Self { column: Column::new_empty(name), column_type: None, } } } impl Deref for TypedColumn { type Target = Column; fn deref(&self) -> &Self::Target { &self.column } } impl DerefMut for TypedColumn { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.column } } pub type ColumnMap = IndexMap<PlSmallStr, TypedColumn>; pub fn create_column( column: &PolarsColumn, from_row: usize, to_row: usize, span: Span, ) -> Result<Column, ShellError> { let series = column.as_materialized_series(); create_column_from_series(series, from_row, to_row, span) } pub fn create_column_from_series( series: &Series, from_row: usize, to_row: usize, span: Span, ) -> Result<Column, ShellError> { let size = to_row - from_row; let values = series_to_values(series, Some(from_row), Some(size), span)?; Ok(Column::new(series.name().clone(), values)) } // Adds a separator to the vector of values using the column names from the // dataframe to create the Values Row // returns true if there is an index column contained in the dataframe pub fn add_separator(values: &mut Vec<Value>, df: &DataFrame, has_index: bool, span: Span) { let mut record = Record::new(); if !has_index { record.push("index", Value::string("...", span)); } for name in df.get_column_names() { // there should only be one index field record.push(name.as_str(), Value::string("...", span)) } values.push(Value::record(record, span)); } // Inserting the values found in a Value::List or Value::Record pub fn insert_record( column_values: &mut ColumnMap, record: Record, maybe_schema: &Option<NuSchema>, ) -> Result<(), ShellError> { for (col, value) in record { insert_value(value, col.into(), column_values, maybe_schema)?; } Ok(()) } pub fn insert_value( value: Value, key: PlSmallStr, column_values: &mut ColumnMap, maybe_schema: &Option<NuSchema>, ) -> Result<(), ShellError> { // If we have a schema but a key is not provided, do not create that column if let Some(schema) = maybe_schema && !schema.schema.contains(&key) { return Ok(()); } let col_val = match column_values.entry(key.clone()) { Entry::Vacant(entry) => entry.insert(TypedColumn::new_empty(key.clone())), Entry::Occupied(entry) => entry.into_mut(), }; // If we have a schema, use that for determining how things should be added to each column if let Some(schema) = maybe_schema && let Some(field) = schema.schema.get_field(&key) { col_val.column_type = Some(field.dtype().clone()); col_val.values.push(value); return Ok(()); } // If we do not have a schema, use defaults specified in `value_to_data_type` let current_data_type = value_to_data_type(&value); if col_val.column_type.is_none() { col_val.column_type = value_to_data_type(&value); } else if let Some(current_data_type) = current_data_type && col_val.column_type.as_ref() != Some(&current_data_type) { col_val.column_type = Some(DataType::Object("Value")); } col_val.values.push(value); Ok(()) } fn value_to_data_type(value: &Value) -> Option<DataType> { match &value { Value::Int { .. } => Some(DataType::Int64), Value::Float { .. } => Some(DataType::Float64), Value::String { .. } => Some(DataType::String), Value::Bool { .. } => Some(DataType::Boolean), Value::Date { .. } => Some(DataType::Datetime( TimeUnit::Nanoseconds, Some(timezone_utc()), )), Value::Duration { .. } => Some(DataType::Duration(TimeUnit::Nanoseconds)), Value::Filesize { .. } => Some(DataType::Int64), Value::Binary { .. } => Some(DataType::Binary), Value::List { vals, .. } => { // We need to determined the type inside of the list. // Since Value::List does not have any kind of // type information, we need to look inside the list. // This will cause errors if lists have inconsistent types. // Basically, if a list column needs to be converted to dataframe, // needs to have consistent types. let list_type = vals .iter() .filter(|v| !matches!(v, Value::Nothing { .. })) .map(value_to_data_type) .nth(1) .flatten() .unwrap_or(DataType::Object("Value")); Some(DataType::List(Box::new(list_type))) } _ => None, } } fn typed_column_to_series(name: PlSmallStr, column: TypedColumn) -> Result<Series, ShellError> { let column_type = &column .column_type .clone() .unwrap_or(DataType::Object("Value")); match column_type { DataType::Float32 => { let series_values: Result<Vec<_>, _> = column .values .iter() .map(|v| { value_to_option(v, |v| match v { Value::Float { val, .. } => Ok(*val as f32), Value::Int { val, .. } => Ok(*val as f32), x => Err(ShellError::GenericError { error: "Error converting to f32".into(), msg: "".into(), span: None, help: Some(format!("Unexpected type: {x:?}")), inner: vec![], }), }) }) .collect(); Ok(Series::new(name, series_values?)) } DataType::Float64 => { let series_values: Result<Vec<_>, _> = column .values .iter() .map(|v| { value_to_option(v, |v| match v { Value::Float { val, .. } => Ok(*val), Value::Int { val, .. } => Ok(*val as f64), x => Err(ShellError::GenericError { error: "Error converting to f64".into(), msg: "".into(), span: None, help: Some(format!("Unexpected type: {x:?}")), inner: vec![], }), }) }) .collect(); Ok(Series::new(name, series_values?)) } DataType::Decimal(precision, scale) => { let series_values: Result<Vec<_>, _> = column .values .iter() .map(|v| { value_to_option(v, |v| match v { Value::Float { val, .. } => Ok(*val), Value::Int { val, .. } => Ok(*val as f64), x => Err(ShellError::GenericError { error: "Error converting to decimal".into(), msg: "".into(), span: None, help: Some(format!("Unexpected type: {x:?}")), inner: vec![], }), }) }) .collect(); Series::new(name, series_values?) .cast_with_options(&DataType::Decimal(*precision, *scale), Default::default()) .map_err(|e| ShellError::GenericError { error: "Error parsing decimal".into(), msg: "".into(), span: None, help: Some(e.to_string()), inner: vec![], }) } DataType::UInt8 => { let series_values: Result<Vec<_>, _> = column .values .iter() .map(|v| value_to_option(v, |v| value_to_int(v).map(|v| v as u8))) .collect(); Ok(Series::new(name, series_values?)) } DataType::UInt16 => { let series_values: Result<Vec<_>, _> = column .values .iter() .map(|v| value_to_option(v, |v| value_to_int(v).map(|v| v as u16))) .collect(); Ok(Series::new(name, series_values?)) } DataType::UInt32 => { let series_values: Result<Vec<_>, _> = column .values .iter() .map(|v| value_to_option(v, |v| value_to_int(v).map(|v| v as u32))) .collect(); Ok(Series::new(name, series_values?)) } DataType::UInt64 => { let series_values: Result<Vec<_>, _> = column .values .iter() .map(|v| value_to_option(v, |v| value_to_int(v).map(|v| v as u64))) .collect(); Ok(Series::new(name, series_values?)) } DataType::Int8 => { let series_values: Result<Vec<_>, _> = column .values .iter() .map(|v| value_to_option(v, |v| value_to_int(v).map(|v| v as i8))) .collect(); Ok(Series::new(name, series_values?)) } DataType::Int16 => { let series_values: Result<Vec<_>, _> = column .values .iter() .map(|v| value_to_option(v, |v| value_to_int(v).map(|v| v as i16))) .collect(); Ok(Series::new(name, series_values?)) } DataType::Int32 => { let series_values: Result<Vec<_>, _> = column .values .iter() .map(|v| value_to_option(v, |v| value_to_int(v).map(|v| v as i32))) .collect(); Ok(Series::new(name, series_values?)) } DataType::Int64 => { let series_values: Result<Vec<_>, _> = column .values .iter() .map(|v| value_to_option(v, value_to_int)) .collect(); Ok(Series::new(name, series_values?)) } DataType::Boolean => { let series_values: Result<Vec<_>, _> = column .values .iter() .map(|v| value_to_option(v, |v| v.as_bool())) .collect(); Ok(Series::new(name, series_values?)) } DataType::String => { let series_values: Result<Vec<_>, _> = column .values .iter() .map(|v| value_to_option(v, |v| v.coerce_string())) .collect(); Ok(Series::new(name, series_values?)) } DataType::Binary | DataType::BinaryOffset => { let series_values: Result<Vec<_>, _> = column.values.iter().map(|v| v.coerce_binary()).collect(); Ok(Series::new(name, series_values?)) } DataType::Object(_) => value_to_series(name, &column.values), DataType::Duration(time_unit) => { let series_values: Result<Vec<_>, _> = column .values .iter() .map(|v| { value_to_option(v, |v| { v.as_duration().map(|v| nanos_to_timeunit(v, *time_unit)) }?) }) .collect(); Ok(Series::new(name, series_values?)) } DataType::List(list_type) => { match input_type_list_to_series(&name, list_type.as_ref(), &column.values) { Ok(series) => Ok(series), Err(_) => { // An error case will occur when there are lists of mixed types. // If this happens, fallback to object list input_type_list_to_series(&name, &DataType::Object("unknown"), &column.values) } } } DataType::Date => { let it = column .values .iter() .map(|v| match &v { Value::Date { val, .. } => { Ok(Some(val.timestamp_nanos_opt().unwrap_or_default())) } Value::String { val, .. } => { let expected_format = "%Y-%m-%d"; let nanos = NaiveDate::parse_from_str(val, expected_format) .map_err(|e| ShellError::GenericError { error: format!("Error parsing date from string: {e}"), msg: "".into(), span: None, help: Some(format!("Expected format {expected_format}. If you need to parse with another format, please set the schema to `str` and parse with `polars as-date <format>`.")), inner: vec![], })? .and_hms_nano_opt(0, 0, 0, 0) .and_then(|dt| dt.and_utc().timestamp_nanos_opt()); Ok(nanos) } _ => Ok(None), }) .collect::<Result<Vec<_>, ShellError>>()?; ChunkedArray::<Int64Type>::from_iter_options(name, it.into_iter()) .into_datetime(TimeUnit::Nanoseconds, None) .cast_with_options(&DataType::Date, Default::default()) .map_err(|e| ShellError::GenericError { error: "Error parsing date".into(), msg: "".into(), span: None, help: Some(e.to_string()), inner: vec![], }) } DataType::Datetime(tu, maybe_tz) => { let dates = column .values .iter() .map(|v| { match (maybe_tz, &v) { (Some(tz), Value::Date { val, .. }) => { // If there is a timezone specified, make sure // the value is converted to it tz.parse::<Tz>() .map(|tz| val.with_timezone(&tz)) .map_err(|e| ShellError::GenericError { error: "Error parsing timezone".into(), msg: "".into(), span: None, help: Some(e.to_string()), inner: vec![], })? .timestamp_nanos_opt() .map(|nanos| nanos_to_timeunit(nanos, *tu)) .transpose() } (None, Value::Date { val, .. }) => val .timestamp_nanos_opt() .map(|nanos| nanos_to_timeunit(nanos, *tu)) .transpose(), (Some(_), Value::String { val, .. }) => { // because we're converting to the number of nano seconds since epoch, the timezone is irrelevant let expected_format = "%Y-%m-%d %H:%M:%S%:z"; DateTime::parse_from_str(val, expected_format) .map_err(|e| ShellError::GenericError { error: format!("Error parsing datetime from string: {e}"), msg: "".into(), span: None, help: Some(format!("Expected format {expected_format}. If you need to parse with another format, please set the schema to `str` and parse with `polars as-datetime <format>`.")), inner: vec![], })? .timestamp_nanos_opt() .map(|nanos| nanos_to_timeunit(nanos, *tu)) .transpose() } (None, Value::String { val, .. }) => { let expected_format = "%Y-%m-%d %H:%M:%S"; NaiveDateTime::parse_from_str(val, expected_format) .map_err(|e| ShellError::GenericError { error: format!("Error parsing datetime from string: {e}"), msg: "".into(), span: None, help: Some(format!("Expected format {expected_format}. If you need to parse with another format, please set the schema to `str` and parse with `polars as-datetime <format>`.")), inner: vec![], })? .and_utc() .timestamp_nanos_opt() .map(|nanos| nanos_to_timeunit(nanos, *tu)) .transpose() } _ => Ok(None), } }) .collect::<Result<Vec<Option<i64>>, ShellError>>()?; let res: DatetimeChunked = ChunkedArray::<Int64Type>::from_iter_options(name, dates.into_iter()) .into_datetime(*tu, maybe_tz.clone()); Ok(res.into_series()) } DataType::Struct(fields) => { let schema = Some(NuSchema::new(Arc::new(Schema::from_iter(fields.clone())))); // let mut structs: Vec<Series> = Vec::new(); let mut structs: HashMap<PlSmallStr, Series> = HashMap::new(); for v in column.values.iter() { let mut column_values: ColumnMap = IndexMap::new(); let record = v.as_record()?; insert_record(&mut column_values, record.clone(), &schema)?; let df = from_parsed_columns(column_values)?; for name in df.df.get_column_names() { let series = df .df .column(name) .map_err(|e| ShellError::GenericError { error: format!( "Error creating struct, could not get column name {name}: {e}" ), msg: "".into(), span: None, help: None, inner: vec![], })? .as_materialized_series(); if let Some(v) = structs.get_mut(name) { let _ = v.append(series) .map_err(|e| ShellError::GenericError { error: format!("Error creating struct, could not append to series for col {name}: {e}"), msg: "".into(), span: None, help: None, inner: vec![], })?; } else { structs.insert(name.clone(), series.to_owned()); } } } let structs: Vec<Series> = structs.into_values().collect(); let chunked = StructChunked::from_series(column.name().to_owned(), structs.len(), structs.iter()) .map_err(|e| ShellError::GenericError { error: format!("Error creating struct: {e}"), msg: "".into(), span: None, help: None, inner: vec![], })?; Ok(chunked.into_series()) } _ => Err(ShellError::GenericError { error: format!("Error creating dataframe: Unsupported type: {column_type:?}"), msg: "".into(), span: None, help: None, inner: vec![], }), } } // The ColumnMap has the parsed data from the StreamInput // This data can be used to create a Series object that can initialize // the dataframe based on the type of data that is found pub fn from_parsed_columns(column_values: ColumnMap) -> Result<NuDataFrame, ShellError> { let mut df_columns: Vec<PolarsColumn> = Vec::new(); for (name, column) in column_values { let series = typed_column_to_series(name, column)?; df_columns.push(series.into()); } DataFrame::new(df_columns) .map(|df| NuDataFrame::new(false, df)) .map_err(|e| ShellError::GenericError { error: "Error creating dataframe".into(), msg: e.to_string(), span: None, help: None, inner: vec![], }) } fn value_to_series(name: PlSmallStr, values: &[Value]) -> Result<Series, ShellError> { let mut builder = ObjectChunkedBuilder::<DataFrameValue>::new(name, values.len()); for v in values { builder.append_value(DataFrameValue::new(v.clone())); } let res = builder.finish(); Ok(res.into_series()) } fn input_type_list_to_series( name: &PlSmallStr, data_type: &DataType, values: &[Value], ) -> Result<Series, ShellError> { let inconsistent_error = |_| ShellError::GenericError { error: format!( "column {name} contains a list with inconsistent types: Expecting: {data_type:?}" ), msg: "".into(), span: None, help: None, inner: vec![], }; macro_rules! primitive_list_series { ($list_type:ty, $vec_type:tt) => {{ let mut builder = ListPrimitiveChunkedBuilder::<$list_type>::new( name.clone(), values.len(), VALUES_CAPACITY, data_type.clone(), ); for v in values { let value_list = v .as_list()? .iter() .map(|v| value_to_primitive!(v, $vec_type)) .collect::<Result<Vec<$vec_type>, _>>() .map_err(inconsistent_error)?; builder.append_values_iter(value_list.iter().copied()); } let res = builder.finish(); Ok(res.into_series()) }}; } match *data_type { // list of boolean values DataType::Boolean => { let mut builder = ListBooleanChunkedBuilder::new(name.clone(), values.len(), VALUES_CAPACITY); for v in values { let value_list = v .as_list()? .iter() .map(|v| v.as_bool()) .collect::<Result<Vec<bool>, _>>() .map_err(inconsistent_error)?; builder.append_iter(value_list.iter().map(|v| Some(*v))); } let res = builder.finish(); Ok(res.into_series()) } DataType::Duration(_) => primitive_list_series!(Int64Type, i64), DataType::UInt8 => primitive_list_series!(UInt8Type, u8), DataType::UInt16 => primitive_list_series!(UInt16Type, u16), DataType::UInt32 => primitive_list_series!(UInt32Type, u32), DataType::UInt64 => primitive_list_series!(UInt64Type, u64), DataType::Int8 => primitive_list_series!(Int8Type, i8), DataType::Int16 => primitive_list_series!(Int16Type, i16), DataType::Int32 => primitive_list_series!(Int32Type, i32), DataType::Int64 => primitive_list_series!(Int64Type, i64), DataType::Float32 => primitive_list_series!(Float32Type, f32), DataType::Float64 => primitive_list_series!(Float64Type, f64), DataType::String => { let mut builder = ListStringChunkedBuilder::new(name.clone(), values.len(), VALUES_CAPACITY); for v in values { let value_list = v .as_list()? .iter() .map(|v| v.coerce_string()) .collect::<Result<Vec<String>, _>>() .map_err(inconsistent_error)?; builder.append_values_iter(value_list.iter().map(AsRef::as_ref)); } let res = builder.finish(); Ok(res.into_series()) } DataType::Date => { let mut builder = AnonymousOwnedListBuilder::new( name.clone(), values.len(), Some(DataType::Datetime(TimeUnit::Nanoseconds, None)), ); for (i, v) in values.iter().enumerate() { let list_name = i.to_string(); let it = v.as_list()?.iter().map(|v| { if let Value::Date { val, .. } = &v { Some(val.timestamp_nanos_opt().unwrap_or_default()) } else { None } }); let dt_chunked = ChunkedArray::<Int64Type>::from_iter_options(list_name.into(), it) .into_datetime(TimeUnit::Nanoseconds, None); builder .append_series(&dt_chunked.into_series()) .map_err(|e| ShellError::GenericError { error: "Error appending to series".into(), msg: "".into(), span: None, help: Some(e.to_string()), inner: vec![], })? } let res = builder.finish(); Ok(res.into_series()) } DataType::List(ref sub_list_type) => { Ok(input_type_list_to_series(name, sub_list_type, values)?) } // treat everything else as an object _ => Ok(value_to_series(name.clone(), values)?), } } fn series_to_values( series: &Series, maybe_from_row: Option<usize>, maybe_size: Option<usize>, span: Span, ) -> Result<Vec<Value>, ShellError> { match series.dtype() { DataType::Null => { if let Some(size) = maybe_size { Ok(vec![Value::nothing(span); size]) } else { Ok(vec![Value::nothing(span); series.len()]) } } DataType::UInt8 => { let casted = series.u8().map_err(|e| ShellError::GenericError { error: "Error casting column to u8".into(), msg: "".into(), span: None, help: Some(e.to_string()), inner: vec![], })?; let it = casted.into_iter(); let values = if let (Some(size), Some(from_row)) = (maybe_size, maybe_from_row) { Either::Left(it.skip(from_row).take(size)) } else { Either::Right(it) } .map(|v| match v { Some(a) => Value::int(a as i64, span), None => Value::nothing(span), }) .collect::<Vec<Value>>(); Ok(values) } DataType::UInt16 => { let casted = series.u16().map_err(|e| ShellError::GenericError { error: "Error casting column to u16".into(), msg: "".into(), span: None, help: Some(e.to_string()), inner: vec![], })?; let it = casted.into_iter(); let values = if let (Some(size), Some(from_row)) = (maybe_size, maybe_from_row) { Either::Left(it.skip(from_row).take(size)) } else { Either::Right(it) } .map(|v| match v { Some(a) => Value::int(a as i64, span), None => Value::nothing(span), }) .collect::<Vec<Value>>(); Ok(values) } DataType::UInt32 => { let casted = series.u32().map_err(|e| ShellError::GenericError { error: "Error casting column to u32".into(), msg: "".into(), span: None, help: Some(e.to_string()), inner: vec![], })?; let it = casted.into_iter(); let values = if let (Some(size), Some(from_row)) = (maybe_size, maybe_from_row) { Either::Left(it.skip(from_row).take(size)) } else { Either::Right(it) } .map(|v| match v { Some(a) => Value::int(a as i64, span), None => Value::nothing(span), }) .collect::<Vec<Value>>(); Ok(values) } DataType::UInt64 => {
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
true
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/values/nu_dataframe/operations.rs
crates/nu_plugin_polars/src/dataframe/values/nu_dataframe/operations.rs
use nu_protocol::{ShellError, Span, Spanned, Value, ast::Operator}; use polars::prelude::{Column as PolarsColumn, DataFrame}; use crate::PolarsPlugin; use crate::values::CustomValueSupport; use super::between_values::{ between_dataframes, compute_between_series, compute_series_single_value, }; use super::NuDataFrame; pub enum Axis { Row, Column, } impl NuDataFrame { pub fn compute_with_value( &self, plugin: &PolarsPlugin, lhs_span: Span, operator: Operator, op_span: Span, right: &Value, ) -> Result<NuDataFrame, ShellError> { let rhs_span = right.span(); match right { Value::Custom { .. } => { let rhs = NuDataFrame::try_from_value_coerce(plugin, right, rhs_span)?; match (self.is_series(), rhs.is_series()) { (true, true) => { let lhs = &self .as_series(lhs_span) .expect("Already checked that is a series"); let rhs = &rhs .as_series(rhs_span) .expect("Already checked that is a series"); if lhs.dtype() != rhs.dtype() { return Err(ShellError::IncompatibleParameters { left_message: format!("datatype {}", lhs.dtype()), left_span: lhs_span, right_message: format!("datatype {}", lhs.dtype()), right_span: rhs_span, }); } if lhs.len() != rhs.len() { return Err(ShellError::IncompatibleParameters { left_message: format!("len {}", lhs.len()), left_span: lhs_span, right_message: format!("len {}", rhs.len()), right_span: rhs_span, }); } let op = Spanned { item: operator, span: op_span, }; compute_between_series( op, &NuDataFrame::default().into_value(lhs_span), lhs, right, rhs, ) } _ => { if self.df.height() != rhs.df.height() { return Err(ShellError::IncompatibleParameters { left_message: format!("rows {}", self.df.height()), left_span: lhs_span, right_message: format!("rows {}", rhs.df.height()), right_span: rhs_span, }); } let op = Spanned { item: operator, span: op_span, }; between_dataframes( op, &NuDataFrame::default().into_value(lhs_span), self, right, &rhs, ) } } } _ => { let op = Spanned { item: operator, span: op_span, }; compute_series_single_value( op, &NuDataFrame::default().into_value(lhs_span), self, right, ) } } } pub fn append_df( &self, other: &NuDataFrame, axis: Axis, span: Span, ) -> Result<NuDataFrame, ShellError> { match axis { Axis::Row => { let mut columns: Vec<&str> = Vec::new(); let new_cols = self .df .get_columns() .iter() .chain(other.df.get_columns()) .map(|s| { let name = if columns.contains(&s.name().as_str()) { format!("{}_{}", s.name(), "x") } else { columns.push(s.name()); s.name().to_string() }; let mut series = s.clone(); series.rename(name.into()); series }) .collect::<Vec<PolarsColumn>>(); let df_new = DataFrame::new(new_cols).map_err(|e| ShellError::GenericError { error: "Error creating dataframe".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], })?; Ok(NuDataFrame::new(false, df_new)) } Axis::Column => { if self.df.width() != other.df.width() { return Err(ShellError::IncompatibleParametersSingle { msg: "Dataframes with different number of columns".into(), span, }); } if !self .df .get_column_names() .iter() .all(|col| other.df.get_column_names().contains(col)) { return Err(ShellError::IncompatibleParametersSingle { msg: "Dataframes with different columns names".into(), span, }); } let new_cols = self .df .get_columns() .iter() .map(|s| { let other_col = other .df .column(s.name()) .expect("Already checked that dataframes have same columns"); let mut tmp = s.clone(); let res = tmp.append(other_col); match res { Ok(s) => Ok(s.clone()), Err(e) => Err({ ShellError::GenericError { error: "Error appending dataframe".into(), msg: format!("Unable to append: {e}"), span: Some(span), help: None, inner: vec![], } }), } }) .collect::<Result<Vec<PolarsColumn>, ShellError>>()?; let df_new = DataFrame::new(new_cols).map_err(|e| ShellError::GenericError { error: "Error appending dataframe".into(), msg: format!("Unable to append dataframes: {e}"), span: Some(span), help: None, inner: vec![], })?; Ok(NuDataFrame::new(false, df_new)) } } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/values/nu_dataframe/mod.rs
crates/nu_plugin_polars/src/dataframe/values/nu_dataframe/mod.rs
mod between_values; mod conversion; mod custom_value; mod operations; pub use conversion::{Column, ColumnMap}; pub use operations::Axis; use indexmap::map::IndexMap; use nu_protocol::{PipelineData, Record, ShellError, Span, Value, did_you_mean}; use polars::prelude::{ Column as PolarsColumn, DataFrame, DataType, IntoLazy, PolarsObject, Series, }; use polars_plan::prelude::{Expr, Null, lit}; use polars_utils::total_ord::{TotalEq, TotalHash}; use std::fmt; use std::{ cmp::Ordering, collections::HashSet, fmt::Display, hash::{Hash, Hasher}, sync::Arc, }; use uuid::Uuid; use crate::{Cacheable, PolarsPlugin}; pub use self::custom_value::NuDataFrameCustomValue; use super::{ CustomValueSupport, NuLazyFrame, PolarsPluginObject, PolarsPluginType, cant_convert_err, nu_schema::NuSchema, utils::DEFAULT_ROWS, }; // DataFrameValue is an encapsulation of Nushell Value that can be used // to define the PolarsObject Trait. The polars object trait allows to // create dataframes with mixed datatypes #[derive(Clone, Debug)] pub struct DataFrameValue(Value); impl DataFrameValue { fn new(value: Value) -> Self { Self(value) } fn get_value(&self) -> Value { self.0.clone() } } impl TotalHash for DataFrameValue { fn tot_hash<H>(&self, state: &mut H) where H: Hasher, { (*self).hash(state) } } impl Display for DataFrameValue { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0.get_type()) } } impl Default for DataFrameValue { fn default() -> Self { Self(Value::nothing(Span::unknown())) } } impl PartialEq for DataFrameValue { fn eq(&self, other: &Self) -> bool { self.0.partial_cmp(&other.0).is_some_and(Ordering::is_eq) } } impl Eq for DataFrameValue {} impl Hash for DataFrameValue { fn hash<H: Hasher>(&self, state: &mut H) { match &self.0 { Value::Nothing { .. } => 0.hash(state), Value::Int { val, .. } => val.hash(state), Value::String { val, .. } => val.hash(state), // TODO. Define hash for the rest of types _ => {} } } } impl TotalEq for DataFrameValue { fn tot_eq(&self, other: &Self) -> bool { self == other } } impl PolarsObject for DataFrameValue { fn type_name() -> &'static str { "object" } } #[derive(Debug, Default, Clone)] pub struct NuDataFrame { pub id: Uuid, pub df: Arc<DataFrame>, pub from_lazy: bool, } impl AsRef<DataFrame> for NuDataFrame { fn as_ref(&self) -> &polars::prelude::DataFrame { &self.df } } impl From<DataFrame> for NuDataFrame { fn from(df: DataFrame) -> Self { Self::new(false, df) } } impl fmt::Display for NuDataFrame { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.df) } } impl NuDataFrame { pub fn new(from_lazy: bool, df: DataFrame) -> Self { let id = Uuid::new_v4(); Self { id, df: Arc::new(df), from_lazy, } } pub fn to_polars(&self) -> DataFrame { (*self.df).clone() } pub fn lazy(&self) -> NuLazyFrame { NuLazyFrame::new(true, self.to_polars().lazy()) } pub fn try_from_series(series: Series, span: Span) -> Result<Self, ShellError> { match DataFrame::new(vec![series.into()]) { Ok(dataframe) => Ok(NuDataFrame::new(false, dataframe)), Err(e) => Err(ShellError::GenericError { error: "Error creating dataframe".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], }), } } pub fn try_from_iter<T>( plugin: &PolarsPlugin, iter: T, maybe_schema: Option<NuSchema>, ) -> Result<Self, ShellError> where T: Iterator<Item = Value>, { // Dictionary to store the columnar data extracted from // the input. During the iteration we check if the values // have different type let mut column_values: ColumnMap = IndexMap::new(); for value in iter { match value { Value::Custom { .. } => { return Self::try_from_value_coerce(plugin, &value, value.span()); } Value::List { vals, .. } => { let record = vals .into_iter() .enumerate() .map(|(i, val)| (format!("{i}"), val)) .collect(); conversion::insert_record(&mut column_values, record, &maybe_schema)? } Value::Record { val: record, .. } => conversion::insert_record( &mut column_values, record.into_owned(), &maybe_schema, )?, _ => { let key = "0".to_string(); conversion::insert_value(value, key.into(), &mut column_values, &maybe_schema)? } } } let df = conversion::from_parsed_columns(column_values)?; add_missing_columns(df, &maybe_schema, Span::unknown()) } pub fn try_from_series_vec(columns: Vec<Series>, span: Span) -> Result<Self, ShellError> { let columns_converted: Vec<PolarsColumn> = columns.into_iter().map(Into::into).collect(); let dataframe = DataFrame::new(columns_converted).map_err(|e| ShellError::GenericError { error: "Error creating dataframe".into(), msg: format!("Unable to create DataFrame: {e}"), span: Some(span), help: None, inner: vec![], })?; Ok(Self::new(false, dataframe)) } pub fn try_from_columns( columns: Vec<Column>, maybe_schema: Option<NuSchema>, ) -> Result<Self, ShellError> { let mut column_values: ColumnMap = IndexMap::new(); for column in columns { let name = column.name().clone(); for value in column { conversion::insert_value(value, name.clone(), &mut column_values, &maybe_schema)?; } } let df = conversion::from_parsed_columns(column_values)?; add_missing_columns(df, &maybe_schema, Span::unknown()) } pub fn fill_list_nan(list: Vec<Value>, list_span: Span, fill: Value) -> Value { let newlist = list .into_iter() .map(|value| { let span = value.span(); match value { Value::Float { val, .. } => { if val.is_nan() { fill.clone() } else { value } } Value::List { vals, .. } => Self::fill_list_nan(vals, span, fill.clone()), _ => value, } }) .collect::<Vec<Value>>(); Value::list(newlist, list_span) } pub fn columns(&self, span: Span) -> Result<Vec<Column>, ShellError> { let height = self.df.height(); self.df .get_columns() .iter() .map(|col| conversion::create_column(col, 0, height, span)) .collect::<Result<Vec<Column>, ShellError>>() } pub fn column(&self, column: &str, span: Span) -> Result<Self, ShellError> { let s = self.df.column(column).map_err(|_| { let possibilities = self .df .get_column_names() .iter() .map(|name| name.to_string()) .collect::<Vec<String>>(); let option = did_you_mean(&possibilities, column).unwrap_or_else(|| column.to_string()); ShellError::DidYouMean { suggestion: option, span, } })?; let df = DataFrame::new(vec![s.clone()]).map_err(|e| ShellError::GenericError { error: "Error creating dataframe".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], })?; Ok(Self::new(false, df)) } pub fn is_series(&self) -> bool { self.df.width() == 1 } pub fn as_series(&self, span: Span) -> Result<Series, ShellError> { if !self.is_series() { return Err(ShellError::GenericError { error: "Error using as series".into(), msg: "dataframe has more than one column".into(), span: Some(span), help: None, inner: vec![], }); } let series = self .df .get_columns() .first() .expect("We have already checked that the width is 1") .as_materialized_series(); Ok(series.clone()) } pub fn get_value(&self, row: usize, span: Span) -> Result<Value, ShellError> { let series = self.as_series(span)?; let column = conversion::create_column_from_series(&series, row, row + 1, span)?; if column.is_empty() { Err(ShellError::AccessEmptyContent { span }) } else { let value = column .into_iter() .next() .expect("already checked there is a value"); Ok(value) } } pub fn has_index(&self) -> bool { self.columns(Span::unknown()) .unwrap_or_default() // just assume there isn't an index .iter() .any(|col| col.name() == "index") } // Print is made out a head and if the dataframe is too large, then a tail pub fn print(&self, include_index: bool, span: Span) -> Result<Vec<Value>, ShellError> { let df = &self.df; let size: usize = 20; if df.height() > size { let sample_size = size / 2; let mut values = self.head(Some(sample_size), include_index, span)?; conversion::add_separator(&mut values, df, self.has_index(), span); let remaining = df.height() - sample_size; let tail_size = remaining.min(sample_size); let mut tail_values = self.tail(Some(tail_size), include_index, span)?; values.append(&mut tail_values); Ok(values) } else { Ok(self.head(Some(size), include_index, span)?) } } pub fn height(&self) -> usize { self.df.height() } pub fn head( &self, rows: Option<usize>, include_index: bool, span: Span, ) -> Result<Vec<Value>, ShellError> { let to_row = rows.unwrap_or(5); let values = self.to_rows(0, to_row, include_index, span)?; Ok(values) } pub fn tail( &self, rows: Option<usize>, include_index: bool, span: Span, ) -> Result<Vec<Value>, ShellError> { let df = &self.df; let to_row = df.height(); let size = rows.unwrap_or(DEFAULT_ROWS); let from_row = to_row.saturating_sub(size); let values = self.to_rows(from_row, to_row, include_index, span)?; Ok(values) } /// Converts the dataframe to a nushell list of values pub fn to_rows( &self, from_row: usize, to_row: usize, include_index: bool, span: Span, ) -> Result<Vec<Value>, ShellError> { let df = &self.df; let upper_row = to_row.min(df.height()); let mut size: usize = 0; let columns = self .df .get_columns() .iter() .map( |col| match conversion::create_column(col, from_row, upper_row, span) { Ok(col) => { size = col.len(); Ok(col) } Err(e) => Err(e), }, ) .collect::<Result<Vec<Column>, ShellError>>()?; let mut iterators = columns .into_iter() .map(|col| (col.name().to_string(), col.into_iter())) .collect::<Vec<(String, std::vec::IntoIter<Value>)>>(); let has_index = self.has_index(); let values = (0..size) .map(|i| { let mut record = Record::new(); if !has_index && include_index { record.push("index", Value::int((i + from_row) as i64, span)); } for (name, col) in &mut iterators { record.push(name.clone(), col.next().unwrap_or(Value::nothing(span))); } Value::record(record, span) }) .collect::<Vec<Value>>(); Ok(values) } // Dataframes are considered equal if they have the same shape, column name and values pub fn is_equal(&self, other: &Self) -> Option<Ordering> { let polars_self = self.to_polars(); let polars_other = other.to_polars(); if polars_self == polars_other { Some(Ordering::Equal) } else { None } } pub fn schema(&self) -> NuSchema { NuSchema::new(Arc::clone(self.df.schema())) } /// This differs from try_from_value as it will attempt to coerce the type into a NuDataFrame. /// So, if the pipeline type is a NuLazyFrame it will be collected and returned as NuDataFrame. pub fn try_from_value_coerce( plugin: &PolarsPlugin, value: &Value, span: Span, ) -> Result<Self, ShellError> { match PolarsPluginObject::try_from_value(plugin, value)? { PolarsPluginObject::NuDataFrame(df) => Ok(df), PolarsPluginObject::NuLazyFrame(lazy) => lazy.collect(span), _ => Err(cant_convert_err( value, &[PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame], )), } } /// This differs from try_from_pipeline as it will attempt to coerce the type into a NuDataFrame. /// So, if the pipeline type is a NuLazyFrame it will be collected and returned as NuDataFrame. pub fn try_from_pipeline_coerce( plugin: &PolarsPlugin, input: PipelineData, span: Span, ) -> Result<Self, ShellError> { let value = input.into_value(span)?; Self::try_from_value_coerce(plugin, &value, span) } } fn add_missing_columns( df: NuDataFrame, maybe_schema: &Option<NuSchema>, span: Span, ) -> Result<NuDataFrame, ShellError> { // If there are fields that are in the schema, but not in the dataframe // add them to the dataframe. if let Some(schema) = maybe_schema { let fields = df.df.fields(); let df_field_names: HashSet<&str> = fields.iter().map(|f| f.name().as_str()).collect(); let missing: Vec<(&str, &DataType)> = schema .schema .iter() .filter_map(|(name, dtype)| { let name = name.as_str(); if !df_field_names.contains(name) { Some((name, dtype)) } else { None } }) .collect(); let missing_exprs: Vec<Expr> = missing .iter() .map(|(name, dtype)| lit(Null {}).cast((*dtype).to_owned()).alias(*name)) .collect(); let df = if !missing.is_empty() { let lazy: NuLazyFrame = df.lazy().to_polars().with_columns(missing_exprs).into(); lazy.collect(span)? } else { df }; Ok(df) } else { Ok(df) } } impl Cacheable for NuDataFrame { fn cache_id(&self) -> &Uuid { &self.id } fn to_cache_value(&self) -> Result<PolarsPluginObject, ShellError> { Ok(PolarsPluginObject::NuDataFrame(self.clone())) } fn from_cache_value(cv: PolarsPluginObject) -> Result<Self, ShellError> { match cv { PolarsPluginObject::NuDataFrame(df) => Ok(df), _ => Err(ShellError::GenericError { error: "Cache value is not a dataframe".into(), msg: "".into(), span: None, help: None, inner: vec![], }), } } } impl CustomValueSupport for NuDataFrame { type CV = NuDataFrameCustomValue; fn custom_value(self) -> Self::CV { NuDataFrameCustomValue { id: self.id, dataframe: Some(self), } } fn base_value(self, span: Span) -> Result<Value, ShellError> { let vals = self.print(true, span)?; Ok(Value::list(vals, span)) } fn get_type_static() -> PolarsPluginType { PolarsPluginType::NuDataFrame } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/values/nu_when/custom_value.rs
crates/nu_plugin_polars/src/dataframe/values/nu_when/custom_value.rs
use crate::values::{CustomValueSupport, PolarsPluginCustomValue, PolarsPluginType}; use super::NuWhen; use nu_protocol::{CustomValue, ShellError, Span, Value}; use serde::{Deserialize, Serialize}; use uuid::Uuid; #[derive(Debug, Clone, Deserialize, Serialize)] pub struct NuWhenCustomValue { pub id: uuid::Uuid, #[serde(skip)] pub when: Option<NuWhen>, } // CustomValue implementation for NuWhen #[typetag::serde] impl CustomValue for NuWhenCustomValue { fn clone_value(&self, span: nu_protocol::Span) -> Value { Value::custom(Box::new(self.clone()), span) } fn type_name(&self) -> String { PolarsPluginType::NuWhen.type_name().to_string() } fn to_base_value(&self, span: Span) -> Result<Value, ShellError> { Ok(Value::string( "NuWhenCustomValue: custom_value_to_base_value should've been called", span, )) } fn as_mut_any(&mut self) -> &mut dyn std::any::Any { self } fn as_any(&self) -> &dyn std::any::Any { self } fn notify_plugin_on_drop(&self) -> bool { true } } impl PolarsPluginCustomValue for NuWhenCustomValue { type PolarsPluginObjectType = NuWhen; fn custom_value_to_base_value( &self, plugin: &crate::PolarsPlugin, _engine: &nu_plugin::EngineInterface, ) -> Result<Value, ShellError> { let when = NuWhen::try_from_custom_value(plugin, self)?; when.base_value(Span::unknown()) } fn id(&self) -> &Uuid { &self.id } fn internal(&self) -> &Option<Self::PolarsPluginObjectType> { &self.when } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/values/nu_when/mod.rs
crates/nu_plugin_polars/src/dataframe/values/nu_when/mod.rs
mod custom_value; use core::fmt; use nu_protocol::{ShellError, Span, Value}; use polars::prelude::{ChainedThen, Then}; use serde::{Serialize, Serializer}; use uuid::Uuid; use crate::Cacheable; pub use self::custom_value::NuWhenCustomValue; use super::{CustomValueSupport, PolarsPluginObject, PolarsPluginType}; #[derive(Debug, Clone)] pub struct NuWhen { pub id: Uuid, pub when_type: NuWhenType, } #[derive(Clone)] pub enum NuWhenType { Then(Box<Then>), ChainedThen(ChainedThen), } // Mocked serialization of the LazyFrame object impl Serialize for NuWhen { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_none() } } impl fmt::Debug for NuWhenType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "NuWhen") } } impl From<Then> for NuWhenType { fn from(then: Then) -> Self { NuWhenType::Then(Box::new(then)) } } impl From<ChainedThen> for NuWhenType { fn from(chained_when: ChainedThen) -> Self { NuWhenType::ChainedThen(chained_when) } } impl From<NuWhenType> for NuWhen { fn from(when_type: NuWhenType) -> Self { Self::new(when_type) } } impl From<Then> for NuWhen { fn from(then: Then) -> Self { Self::new(then.into()) } } impl From<ChainedThen> for NuWhen { fn from(chained_then: ChainedThen) -> Self { Self::new(chained_then.into()) } } impl NuWhen { pub fn new(when_type: NuWhenType) -> Self { Self { id: Uuid::new_v4(), when_type, } } } impl Cacheable for NuWhen { fn cache_id(&self) -> &Uuid { &self.id } fn to_cache_value(&self) -> Result<PolarsPluginObject, ShellError> { Ok(PolarsPluginObject::NuWhen(self.clone())) } fn from_cache_value(cv: PolarsPluginObject) -> Result<Self, ShellError> { match cv { PolarsPluginObject::NuWhen(when) => Ok(when), _ => Err(ShellError::GenericError { error: "Cache value is not a dataframe".into(), msg: "".into(), span: None, help: None, inner: vec![], }), } } } impl CustomValueSupport for NuWhen { type CV = NuWhenCustomValue; fn custom_value(self) -> Self::CV { NuWhenCustomValue { id: self.id, when: Some(self), } } fn get_type_static() -> PolarsPluginType { PolarsPluginType::NuWhen } fn base_value(self, _span: nu_protocol::Span) -> Result<nu_protocol::Value, ShellError> { let val: String = match self.when_type { NuWhenType::Then(_) => "whenthen".into(), NuWhenType::ChainedThen(_) => "whenthenthen".into(), }; let value = Value::string(val, Span::unknown()); Ok(value) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/values/nu_lazygroupby/custom_value.rs
crates/nu_plugin_polars/src/dataframe/values/nu_lazygroupby/custom_value.rs
use crate::values::{CustomValueSupport, PolarsPluginCustomValue, PolarsPluginType}; use super::NuLazyGroupBy; use nu_protocol::{CustomValue, ShellError, Span, Value}; use serde::{Deserialize, Serialize}; use uuid::Uuid; #[derive(Debug, Clone, Deserialize, Serialize)] pub struct NuLazyGroupByCustomValue { pub id: Uuid, #[serde(skip)] pub groupby: Option<NuLazyGroupBy>, } #[typetag::serde] impl CustomValue for NuLazyGroupByCustomValue { fn clone_value(&self, span: nu_protocol::Span) -> Value { Value::custom(Box::new(self.clone()), span) } fn type_name(&self) -> String { PolarsPluginType::NuLazyGroupBy.type_name().to_string() } fn to_base_value(&self, span: Span) -> Result<Value, ShellError> { Ok(Value::string( "NuLazyGroupByCustomValue: custom_value_to_base_value should've been called", span, )) } fn as_mut_any(&mut self) -> &mut dyn std::any::Any { self } fn as_any(&self) -> &dyn std::any::Any { self } fn notify_plugin_on_drop(&self) -> bool { true } } impl PolarsPluginCustomValue for NuLazyGroupByCustomValue { type PolarsPluginObjectType = NuLazyGroupBy; fn custom_value_to_base_value( &self, plugin: &crate::PolarsPlugin, _engine: &nu_plugin::EngineInterface, ) -> Result<Value, ShellError> { NuLazyGroupBy::try_from_custom_value(plugin, self)?.base_value(Span::unknown()) } fn id(&self) -> &Uuid { &self.id } fn internal(&self) -> &Option<Self::PolarsPluginObjectType> { &self.groupby } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/values/nu_lazygroupby/mod.rs
crates/nu_plugin_polars/src/dataframe/values/nu_lazygroupby/mod.rs
mod custom_value; use core::fmt; use nu_protocol::{ShellError, Span, Value, record}; use polars::prelude::LazyGroupBy; use std::sync::Arc; use uuid::Uuid; use crate::Cacheable; pub use self::custom_value::NuLazyGroupByCustomValue; use super::{CustomValueSupport, NuSchema, PolarsPluginObject, PolarsPluginType}; // Lazyframe wrapper for Nushell operations // Polars LazyFrame is behind and Option to allow easy implementation of // the Deserialize trait #[derive(Clone)] pub struct NuLazyGroupBy { pub id: Uuid, pub group_by: Arc<LazyGroupBy>, pub schema: NuSchema, pub from_eager: bool, } impl fmt::Debug for NuLazyGroupBy { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "NuLazyGroupBy") } } impl NuLazyGroupBy { pub fn new(group_by: LazyGroupBy, from_eager: bool, schema: NuSchema) -> Self { NuLazyGroupBy { id: Uuid::new_v4(), group_by: Arc::new(group_by), from_eager, schema, } } pub fn to_polars(&self) -> LazyGroupBy { (*self.group_by).clone() } } impl Cacheable for NuLazyGroupBy { fn cache_id(&self) -> &Uuid { &self.id } fn to_cache_value(&self) -> Result<PolarsPluginObject, ShellError> { Ok(PolarsPluginObject::NuLazyGroupBy(self.clone())) } fn from_cache_value(cv: PolarsPluginObject) -> Result<Self, ShellError> { match cv { PolarsPluginObject::NuLazyGroupBy(df) => Ok(df), _ => Err(ShellError::GenericError { error: "Cache value is not a group by".into(), msg: "".into(), span: None, help: None, inner: vec![], }), } } } impl CustomValueSupport for NuLazyGroupBy { type CV = NuLazyGroupByCustomValue; fn custom_value(self) -> Self::CV { NuLazyGroupByCustomValue { id: self.id, groupby: Some(self), } } fn get_type_static() -> PolarsPluginType { PolarsPluginType::NuLazyGroupBy } fn base_value(self, _span: nu_protocol::Span) -> Result<nu_protocol::Value, ShellError> { Ok(Value::record( record! { "LazyGroupBy" => Value::string("apply aggregation to complete execution plan", Span::unknown()) }, Span::unknown(), )) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/cloud/gcp.rs
crates/nu_plugin_polars/src/cloud/gcp.rs
use object_store::gcp::GoogleCloudStorageBuilder; use polars_io::cloud::{CloudOptions, GoogleConfigKey}; struct GoogleOptionsBuilder { builder: GoogleCloudStorageBuilder, } impl GoogleOptionsBuilder { fn new() -> Self { Self { builder: GoogleCloudStorageBuilder::new(), } } fn get_config_value(&self, key: GoogleConfigKey) -> Option<(GoogleConfigKey, String)> { self.builder.get_config_value(&key).map(|v| (key, v)) } } pub(crate) fn build_cloud_options() -> Result<CloudOptions, nu_protocol::ShellError> { let builder = GoogleOptionsBuilder::new(); // GOOGLE_SERVICE_ACCOUNT: location of service account file // GOOGLE_SERVICE_ACCOUNT_PATH: (alias) location of service account file // SERVICE_ACCOUNT: (alias) location of service account file // GOOGLE_SERVICE_ACCOUNT_KEY: JSON serialized service account key // GOOGLE_BUCKET: bucket name // GOOGLE_BUCKET_NAME: (alias) bucket name let configs = vec![ GoogleConfigKey::ServiceAccount, GoogleConfigKey::ServiceAccountKey, GoogleConfigKey::Bucket, ] .into_iter() .filter_map(|key| builder.get_config_value(key)) .collect::<Vec<(GoogleConfigKey, String)>>(); Ok(CloudOptions::default().with_gcp(configs)) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/cloud/aws.rs
crates/nu_plugin_polars/src/cloud/aws.rs
use std::error::Error; use aws_config::{BehaviorVersion, SdkConfig}; use aws_credential_types::{Credentials, provider::ProvideCredentials}; use nu_protocol::ShellError; use object_store::aws::AmazonS3ConfigKey; use polars_io::cloud::CloudOptions; use crate::PolarsPlugin; async fn load_aws_config() -> SdkConfig { aws_config::load_defaults(BehaviorVersion::latest()).await } async fn aws_creds(aws_config: &SdkConfig) -> Result<Option<Credentials>, ShellError> { if let Some(provider) = aws_config.credentials_provider() { Ok(Some(provider.provide_credentials().await.map_err(|e| { ShellError::GenericError { error: format!( "Could not fetch AWS credentials: {} - {}", e, e.source().map(|e| format!("{e}")).unwrap_or("".to_string()) ), msg: "".into(), span: None, help: None, inner: vec![], } })?)) } else { Ok(None) } } async fn build_aws_cloud_configs() -> Result<Vec<(AmazonS3ConfigKey, String)>, ShellError> { let sdk_config = load_aws_config().await; let creds = aws_creds(&sdk_config) .await? .ok_or(ShellError::GenericError { error: "Could not determine AWS credentials".into(), msg: "".into(), span: None, help: None, inner: vec![], })?; let mut configs = vec![ (AmazonS3ConfigKey::AccessKeyId, creds.access_key_id().into()), ( AmazonS3ConfigKey::SecretAccessKey, creds.secret_access_key().into(), ), ]; if let Some(token) = creds.session_token() { configs.push((AmazonS3ConfigKey::Token, token.into())) } Ok(configs) } pub(crate) fn build_cloud_options(plugin: &PolarsPlugin) -> Result<CloudOptions, ShellError> { let configs = plugin.runtime.block_on(build_aws_cloud_configs())?; Ok(CloudOptions::default().with_aws(configs)) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/cloud/azure.rs
crates/nu_plugin_polars/src/cloud/azure.rs
use object_store::azure::MicrosoftAzureBuilder; use polars_io::cloud::{AzureConfigKey, CloudOptions}; struct AzureOptionsBuilder { builder: MicrosoftAzureBuilder, } impl AzureOptionsBuilder { fn new() -> Self { Self { builder: MicrosoftAzureBuilder::new(), } } fn get_config_value(&self, key: AzureConfigKey) -> Option<(AzureConfigKey, String)> { self.builder.get_config_value(&key).map(|v| (key, v)) } } pub(crate) fn build_cloud_options() -> Result<CloudOptions, nu_protocol::ShellError> { let builder = AzureOptionsBuilder::new(); // Variables extracted from environment: // * AZURE_STORAGE_ACCOUNT_NAME: storage account name // * AZURE_STORAGE_ACCOUNT_KEY: storage account master key // * AZURE_STORAGE_ACCESS_KEY: alias for AZURE_STORAGE_ACCOUNT_KEY // * AZURE_STORAGE_CLIENT_ID -> client id for service principal authorization // * AZURE_STORAGE_CLIENT_SECRET -> client secret for service principal authorization // * AZURE_STORAGE_TENANT_ID -> tenant id used in oauth flows let configs = vec![ AzureConfigKey::AccountName, AzureConfigKey::AccessKey, AzureConfigKey::AccessKey, AzureConfigKey::ClientId, AzureConfigKey::ClientSecret, AzureConfigKey::AuthorityId, ] .into_iter() .filter_map(|key| builder.get_config_value(key)) .collect::<Vec<(AzureConfigKey, String)>>(); Ok(CloudOptions::default().with_azure(configs)) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/cloud/mod.rs
crates/nu_plugin_polars/src/cloud/mod.rs
use nu_protocol::ShellError; use polars::prelude::PlPath; use polars_io::cloud::{CloudOptions, CloudType}; use crate::PolarsPlugin; mod aws; mod azure; mod gcp; pub(crate) fn build_cloud_options( plugin: &PolarsPlugin, path: &PlPath, ) -> Result<Option<CloudOptions>, ShellError> { match path .cloud_scheme() .map(|ref scheme| CloudType::from_cloud_scheme(scheme)) { Some(CloudType::Aws) => aws::build_cloud_options(plugin).map(Some), Some(CloudType::Azure) => azure::build_cloud_options().map(Some), Some(CloudType::Gcp) => gcp::build_cloud_options().map(Some), _ => Ok(None), } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/lib.rs
crates/nu-explore/src/lib.rs
#![doc = include_str!("../README.md")] mod default_context; mod explore; mod explore_config; mod explore_regex; pub use default_context::add_explore_context; pub use explore::{Explore, ExploreConfig}; pub use explore_regex::ExploreRegex;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/default_context.rs
crates/nu-explore/src/default_context.rs
use crate::explore::Explore; use crate::explore_config::ExploreConfigCommand; use crate::explore_regex::ExploreRegex; use nu_protocol::engine::{EngineState, StateWorkingSet}; pub fn add_explore_context(mut engine_state: EngineState) -> EngineState { let delta = { let mut working_set = StateWorkingSet::new(&engine_state); working_set.add_decl(Box::new(Explore)); working_set.add_decl(Box::new(ExploreRegex)); working_set.add_decl(Box::new(ExploreConfigCommand)); working_set.render() }; if let Err(err) = engine_state.merge_delta(delta) { eprintln!("Error creating explore command context: {err:?}"); } engine_state }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/config.rs
crates/nu-explore/src/explore/config.rs
//! Configuration types for the explore command. use crate::explore::nu_common::create_map; use nu_ansi_term::{Color, Style}; use nu_color_config::get_color_map; use nu_protocol::Config; #[derive(Debug, Clone)] pub struct ExploreConfig { pub table: TableConfig, pub selected_cell: Style, pub status_info: Style, pub status_success: Style, pub status_warn: Style, pub status_error: Style, pub status_bar_background: Style, pub status_bar_text: Style, pub cmd_bar_text: Style, pub cmd_bar_background: Style, pub highlight: Style, pub title_bar_background: Style, pub title_bar_text: Style, /// if true, the explore view will immediately try to run the command as it is typed pub try_reactive: bool, } impl Default for ExploreConfig { fn default() -> Self { Self { table: TableConfig::default(), selected_cell: color(None, Some(Color::LightBlue)), status_info: color(None, None), status_success: color(Some(Color::Black), Some(Color::Green)), status_warn: color(None, None), status_error: color(Some(Color::White), Some(Color::Red)), // Use None to inherit from terminal/nushell theme status_bar_background: color(None, None), status_bar_text: color(None, None), cmd_bar_text: color(None, None), cmd_bar_background: color(None, None), highlight: color(Some(Color::Black), Some(Color::Yellow)), // Use None to inherit from terminal/nushell theme title_bar_background: color(None, None), title_bar_text: color(None, None), try_reactive: false, } } } impl ExploreConfig { /// take the default explore config and update it with relevant values from the nu config pub fn from_nu_config(config: &Config) -> Self { let mut ret = Self::default(); ret.table.column_padding_left = config.table.padding.left; ret.table.column_padding_right = config.table.padding.right; let explore_cfg_hash_map = config.explore.clone(); let colors = get_color_map(&explore_cfg_hash_map); if let Some(s) = colors.get("status_bar_text") { ret.status_bar_text = *s; } if let Some(s) = colors.get("status_bar_background") { ret.status_bar_background = *s; } if let Some(s) = colors.get("command_bar_text") { ret.cmd_bar_text = *s; } if let Some(s) = colors.get("command_bar_background") { ret.cmd_bar_background = *s; } if let Some(s) = colors.get("command_bar_background") { ret.cmd_bar_background = *s; } if let Some(s) = colors.get("selected_cell") { ret.selected_cell = *s; } if let Some(s) = colors.get("title_bar_text") { ret.title_bar_text = *s; } if let Some(s) = colors.get("title_bar_background") { ret.title_bar_background = *s; } if let Some(hm) = explore_cfg_hash_map.get("status").and_then(create_map) { let colors = get_color_map(&hm); if let Some(s) = colors.get("info") { ret.status_info = *s; } if let Some(s) = colors.get("success") { ret.status_success = *s; } if let Some(s) = colors.get("warn") { ret.status_warn = *s; } if let Some(s) = colors.get("error") { ret.status_error = *s; } } if let Some(hm) = explore_cfg_hash_map.get("try").and_then(create_map) && let Some(reactive) = hm.get("reactive") && let Ok(b) = reactive.as_bool() { ret.try_reactive = b; } ret } } #[derive(Debug, Default, Clone, Copy)] pub struct TableConfig { pub separator_style: Style, pub show_index: bool, pub show_header: bool, pub column_padding_left: usize, pub column_padding_right: usize, } const fn color(foreground: Option<Color>, background: Option<Color>) -> Style { Style { background, foreground, is_blink: false, is_bold: false, is_dimmed: false, is_hidden: false, is_italic: false, is_reverse: false, is_strikethrough: false, is_underline: false, prefix_with_reset: false, } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/command.rs
crates/nu-explore/src/explore/command.rs
//! The explore command implementation. use crate::explore::config::ExploreConfig; use crate::explore::nu_common::create_lscolors; use crate::explore::pager::PagerConfig; use crate::explore::run_pager; use nu_ansi_term::Style; use nu_color_config::StyleComputer; use nu_engine::command_prelude::*; /// A `less` like program to render a [`Value`] as a table. #[derive(Clone)] pub struct Explore; impl Command for Explore { fn name(&self) -> &str { "explore" } fn description(&self) -> &str { "Explore acts as a table pager, just like `less` does for text." } fn signature(&self) -> nu_protocol::Signature { // todo: Fix error message when it's empty // if we set h i short flags it panics???? Signature::build("explore") .input_output_types(vec![(Type::Any, Type::Any)]) .named( "head", SyntaxShape::Boolean, "Show or hide column headers (default true)", None, ) .switch("index", "Show row indexes when viewing a list", Some('i')) .switch( "tail", "Start with the viewport scrolled to the bottom", Some('t'), ) .switch( "peek", "When quitting, output the value of the cell the cursor was on", Some('p'), ) .category(Category::Viewers) } fn extra_description(&self) -> &str { r#"Press `:` then `h` to get a help menu."# } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let show_head: bool = call.get_flag(engine_state, stack, "head")?.unwrap_or(true); let show_index: bool = call.has_flag(engine_state, stack, "index")?; let tail: bool = call.has_flag(engine_state, stack, "tail")?; let peek_value: bool = call.has_flag(engine_state, stack, "peek")?; let nu_config = stack.get_config(engine_state); let style_computer = StyleComputer::from_config(engine_state, stack); let mut explore_config = ExploreConfig::from_nu_config(&nu_config); explore_config.table.show_header = show_head; explore_config.table.show_index = show_index; explore_config.table.separator_style = lookup_color(&style_computer, "separator"); let lscolors = create_lscolors(engine_state, stack); let cwd = engine_state.cwd(Some(stack)).map_or(String::new(), |path| { path.to_str().unwrap_or("").to_string() }); let config = PagerConfig::new( &nu_config, &explore_config, &style_computer, &lscolors, peek_value, tail, &cwd, ); let result = run_pager(engine_state, &mut stack.clone(), input, config); match result { Ok(Some(value)) => Ok(PipelineData::value(value, None)), Ok(None) => Ok(PipelineData::value(Value::default(), None)), Err(err) => { let shell_error = match err.downcast::<ShellError>() { Ok(e) => e, Err(e) => ShellError::GenericError { error: e.to_string(), msg: "".into(), span: None, help: None, inner: vec![], }, }; Ok(PipelineData::value( Value::error(shell_error, call.head), None, )) } } } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Explore the system host information record", example: r#"sys host | explore"#, result: None, }, Example { description: "Explore the output of `ls` without column names", example: r#"ls | explore --head false"#, result: None, }, Example { description: "Explore a list of Markdown files' contents, with row indexes", example: r#"glob *.md | each {|| open } | explore --index"#, result: None, }, Example { description: "Explore a JSON file, then save the last visited sub-structure to a file", example: r#"open file.json | explore --peek | to json | save part.json"#, result: None, }, ] } } fn lookup_color(style_computer: &StyleComputer, key: &str) -> Style { style_computer.compute(key, &Value::nothing(Span::unknown())) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/mod.rs
crates/nu-explore/src/explore/mod.rs
//! The explore command module. //! //! This module contains the `explore` command implementation and all //! its supporting infrastructure including views, pager, and internal commands. mod command; mod commands; mod config; mod nu_common; mod pager; mod registry; mod views; use anyhow::Result; pub use command::Explore; use commands::{ExpandCmd, HelpCmd, NuCmd, QuitCmd, TableCmd, TryCmd}; pub use config::ExploreConfig; use crossterm::terminal::size; use nu_common::{collect_pipeline, has_simple_value}; use nu_protocol::{ PipelineData, Value, engine::{EngineState, Stack}, }; use pager::{Page, Pager, PagerConfig}; use registry::CommandRegistry; use views::{BinaryView, Orientation, Preview, RecordView}; pub(crate) fn run_pager( engine_state: &EngineState, stack: &mut Stack, input: PipelineData, config: PagerConfig, ) -> Result<Option<Value>> { let mut p = Pager::new(config.clone()); let commands = create_command_registry(); let is_record = matches!(input, PipelineData::Value(Value::Record { .. }, ..)); let is_binary = matches!( input, PipelineData::Value(Value::Binary { .. }, ..) | PipelineData::ByteStream(..) ); if is_binary { p.show_message("Viewing binary data"); let view = binary_view(input, config.explore_config)?; return p.run(engine_state, stack, Some(view), commands); } let (columns, data) = collect_pipeline(input)?; let has_no_input = columns.is_empty() && data.is_empty(); if has_no_input { return p.run(engine_state, stack, help_view(), commands); } p.show_message("Ready"); if let Some(value) = has_simple_value(&data) { let text = value.to_abbreviated_string(config.nu_config); let view = Some(Page::new(Preview::new(&text), false)); return p.run(engine_state, stack, view, commands); } let view = create_record_view(columns, data, is_record, config); p.run(engine_state, stack, view, commands) } fn create_record_view( columns: Vec<String>, data: Vec<Vec<Value>>, // wait, why would we use RecordView for something that isn't a record? is_record: bool, config: PagerConfig, ) -> Option<Page> { let mut view = RecordView::new(columns, data, config.explore_config.clone()); if is_record { view.set_top_layer_orientation(Orientation::Left); } if config.tail && let Ok((w, h)) = size() { view.tail(w, h); } Some(Page::new(view, true)) } fn help_view() -> Option<Page> { Some(Page::new(HelpCmd::view(), false)) } fn binary_view(input: PipelineData, config: &ExploreConfig) -> Result<Page> { let data = match input { PipelineData::Value(Value::Binary { val, .. }, _) => val, PipelineData::ByteStream(bs, _) => bs.into_bytes()?, _ => unreachable!("checked beforehand"), }; let view = BinaryView::new(data, config); Ok(Page::new(view, true)) } fn create_command_registry() -> CommandRegistry { let mut registry = CommandRegistry::new(); create_commands(&mut registry); create_aliases(&mut registry); registry } fn create_commands(registry: &mut CommandRegistry) { registry.register_command_view(NuCmd::new(), true); registry.register_command_view(TableCmd::new(), true); registry.register_command_view(ExpandCmd::new(), false); registry.register_command_view(TryCmd::new(), false); registry.register_command_view(HelpCmd::default(), false); registry.register_command_reactive(QuitCmd); } fn create_aliases(registry: &mut CommandRegistry) { registry.create_aliases("h", HelpCmd::NAME); registry.create_aliases("e", ExpandCmd::NAME); registry.create_aliases("q", QuitCmd::NAME); registry.create_aliases("q!", QuitCmd::NAME); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/commands/expand.rs
crates/nu-explore/src/explore/commands/expand.rs
use super::super::{ nu_common::{self, collect_input}, views::{Preview, ViewConfig}, }; use super::ViewCommand; use anyhow::Result; use nu_color_config::StyleComputer; use nu_protocol::{ Value, engine::{EngineState, Stack}, }; #[derive(Default, Clone)] pub struct ExpandCmd; impl ExpandCmd { pub fn new() -> Self { Self } } impl ExpandCmd { pub const NAME: &'static str = "expand"; } impl ViewCommand for ExpandCmd { type View = Preview; fn name(&self) -> &'static str { Self::NAME } fn description(&self) -> &'static str { "" } fn parse(&mut self, _: &str) -> Result<()> { Ok(()) } fn spawn( &mut self, engine_state: &EngineState, stack: &mut Stack, value: Option<Value>, _: &ViewConfig, ) -> Result<Self::View> { if let Some(value) = value { let value_as_string = convert_value_to_string(value, engine_state, stack)?; Ok(Preview::new(&value_as_string)) } else { Ok(Preview::new("")) } } } fn convert_value_to_string( value: Value, engine_state: &EngineState, stack: &mut Stack, ) -> Result<String> { let (cols, vals) = collect_input(value.clone())?; let has_no_head = cols.is_empty() || (cols.len() == 1 && cols[0].is_empty()); let has_single_value = vals.len() == 1 && vals[0].len() == 1; let config = stack.get_config(engine_state); if !has_no_head && has_single_value { Ok(vals[0][0].to_abbreviated_string(&config)) } else { let style_computer = StyleComputer::from_config(engine_state, stack); let table = nu_common::try_build_table(value, engine_state.signals(), &config, style_computer); Ok(table) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/commands/nu.rs
crates/nu-explore/src/explore/commands/nu.rs
use super::super::{ config::ExploreConfig, nu_common::{NuText, run_command_with_value}, pager::{ Frame, Transition, ViewInfo, report::{Report, Severity}, }, views::{Layout, Orientation, Preview, RecordView, View, ViewConfig}, }; use super::ViewCommand; use anyhow::Result; use crossterm::event::KeyEvent; use nu_engine::get_columns; use nu_protocol::{ PipelineData, Value, engine::{EngineState, Stack}, }; use ratatui::layout::Rect; use std::sync::mpsc::{self, Receiver, TryRecvError}; use std::thread::{self, JoinHandle}; #[derive(Debug, Default, Clone)] pub struct NuCmd { command: String, } impl NuCmd { pub fn new() -> Self { Self { command: String::new(), } } pub const NAME: &'static str = "nu"; } impl ViewCommand for NuCmd { type View = NuView; fn name(&self) -> &'static str { Self::NAME } fn description(&self) -> &'static str { "" } fn parse(&mut self, args: &str) -> Result<()> { args.trim().clone_into(&mut self.command); Ok(()) } fn spawn( &mut self, engine_state: &EngineState, stack: &mut Stack, value: Option<Value>, config: &ViewConfig, ) -> Result<Self::View> { let value = value.unwrap_or_default(); // Clone what we need for the background thread let engine_state = engine_state.clone(); let mut stack = stack.clone(); let command = self.command.clone(); let explore_config = config.explore_config.clone(); // Create channel for communicating results let (sender, receiver) = mpsc::channel(); // Spawn background thread to run the command let handle = thread::spawn(move || { stream_command( &command, &value, &engine_state, &mut stack, &explore_config, sender, ); }); Ok(NuView { state: ViewState::Loading, receiver: Some(receiver), _handle: Some(handle), command_text: self.command.clone(), explore_config: config.explore_config.clone(), frame_count: 0, // Streaming state columns: Vec::new(), rows: Vec::new(), is_record: false, stream_done: false, last_row_count: 0, }) } } /// Messages sent from the background thread to the UI enum StreamMessage { /// Column names (sent once, when first determined) Columns(Vec<String>), /// A batch of rows Rows(Vec<Vec<Value>>), /// This is a record (single row with orientation left) IsRecord, /// Simple value result (not a table) SimpleValue(String), /// Streaming is complete Done, /// An error occurred Error(String), } /// Run the nu command and stream results back via the channel fn stream_command( command: &str, value: &Value, engine_state: &EngineState, stack: &mut Stack, _explore_config: &ExploreConfig, sender: mpsc::Sender<StreamMessage>, ) { let pipeline = match run_command_with_value(command, value, engine_state, stack) { Ok(p) => p, Err(e) => { let _ = sender.send(StreamMessage::Error(format!("Command failed: {e}"))); return; } }; match pipeline { PipelineData::Empty => { let _ = sender.send(StreamMessage::Done); } PipelineData::Value(Value::Record { val, .. }, ..) => { // Record - show with left orientation let _ = sender.send(StreamMessage::IsRecord); let (cols, vals): (Vec<_>, Vec<_>) = val.into_owned().into_iter().unzip(); let _ = sender.send(StreamMessage::Columns(cols)); if !vals.is_empty() { let _ = sender.send(StreamMessage::Rows(vec![vals])); } let _ = sender.send(StreamMessage::Done); } PipelineData::Value(Value::List { vals, .. }, ..) => { // List value - stream it stream_values(vals.into_iter(), &sender); } PipelineData::Value(Value::String { val, .. }, ..) => { // String - show as preview let _ = sender.send(StreamMessage::SimpleValue(val)); } PipelineData::Value(value, ..) => { // Other simple value - show as preview let text = value.to_abbreviated_string(&engine_state.config); let _ = sender.send(StreamMessage::SimpleValue(text)); } PipelineData::ListStream(stream, ..) => { // Stream values as they arrive stream_values(stream.into_iter(), &sender); } PipelineData::ByteStream(stream, ..) => { // ByteStream - collect to string and show as preview let span = stream.span(); match stream.into_string() { Ok(text) => { let _ = sender.send(StreamMessage::SimpleValue(text)); } Err(e) => { let _ = sender.send(StreamMessage::Error(format!( "Failed to read stream: {}", Value::error(e, span).to_debug_string() ))); } } } } } /// Stream values from an iterator, sending rows in batches fn stream_values<I>(iter: I, sender: &mpsc::Sender<StreamMessage>) where I: Iterator<Item = Value>, { const BATCH_SIZE: usize = 1; const INITIAL_ROWS_FOR_COLUMNS: usize = 1; let mut columns: Option<Vec<String>> = None; let mut batch: Vec<Vec<Value>> = Vec::with_capacity(BATCH_SIZE); let mut initial_values: Vec<Value> = Vec::new(); for value in iter { if columns.is_none() { // Buffer initial values to determine columns initial_values.push(value); if initial_values.len() >= INITIAL_ROWS_FOR_COLUMNS { // Determine columns from buffered values let cols = get_columns(&initial_values); if !cols.is_empty() { let _ = sender.send(StreamMessage::Columns(cols.clone())); } // Convert buffered values to rows and send let rows: Vec<Vec<Value>> = initial_values .drain(..) .map(|v| value_to_row(&cols, &v)) .collect(); if sender.send(StreamMessage::Rows(rows)).is_err() { return; // Receiver dropped } columns = Some(cols); } } else if let Some(ref cols) = columns { // We have columns, add to batch batch.push(value_to_row(cols, &value)); if batch.len() >= BATCH_SIZE { if sender .send(StreamMessage::Rows(std::mem::take(&mut batch))) .is_err() { return; // Receiver dropped } batch = Vec::with_capacity(BATCH_SIZE); } } } // Handle case where we never got enough values to determine columns if columns.is_none() && !initial_values.is_empty() { let cols = get_columns(&initial_values); if !cols.is_empty() { let _ = sender.send(StreamMessage::Columns(cols.clone())); } let rows: Vec<Vec<Value>> = initial_values .drain(..) .map(|v| value_to_row(&cols, &v)) .collect(); let _ = sender.send(StreamMessage::Rows(rows)); } // Send any remaining batch if !batch.is_empty() { let _ = sender.send(StreamMessage::Rows(batch)); } let _ = sender.send(StreamMessage::Done); } /// Convert a Value to a row based on expected columns fn value_to_row(cols: &[String], value: &Value) -> Vec<Value> { if cols.is_empty() { vec![value.clone()] } else if let Value::Record { val, .. } = value { cols.iter() .map(|col| val.get(col).cloned().unwrap_or_default()) .collect() } else { // Non-record value in a list - put it in the first column let mut row = vec![Value::default(); cols.len()]; if !row.is_empty() { row[0] = value.clone(); } row } } /// The current state of the view enum ViewState { /// Waiting for first data Loading, /// Streaming/showing a RecordView Records(Box<RecordView>), /// Showing a simple preview Preview(Preview), /// Command completed with no output Empty, /// An error occurred Error(String), } /// A view that runs a command in the background and streams results pub struct NuView { state: ViewState, receiver: Option<Receiver<StreamMessage>>, _handle: Option<JoinHandle<()>>, command_text: String, explore_config: ExploreConfig, frame_count: usize, // Streaming state - used to accumulate data before/while view exists columns: Vec<String>, rows: Vec<Vec<Value>>, is_record: bool, stream_done: bool, last_row_count: usize, } impl NuView { /// Process any pending messages from the background thread fn process_messages(&mut self) { // Take receiver temporarily to avoid borrow issues let receiver = match self.receiver.take() { Some(r) => r, None => return, }; // Process all available messages let mut should_update_view = false; loop { match receiver.try_recv() { Ok(StreamMessage::Columns(cols)) => { self.columns = cols; } Ok(StreamMessage::Rows(new_rows)) => { self.rows.extend(new_rows); should_update_view = true; } Ok(StreamMessage::IsRecord) => { self.is_record = true; } Ok(StreamMessage::SimpleValue(text)) => { self.state = ViewState::Preview(Preview::new(&text)); self.stream_done = true; // Don't put receiver back - we're done return; } Ok(StreamMessage::Done) => { self.stream_done = true; // If we have no data yet, mark as empty if self.rows.is_empty() && !matches!(self.state, ViewState::Records(_) | ViewState::Preview(_)) { self.state = ViewState::Empty; } // Don't put receiver back - we're done if should_update_view { self.update_record_view(); } return; } Ok(StreamMessage::Error(e)) => { self.state = ViewState::Error(e); self.stream_done = true; // Don't put receiver back - we're done return; } Err(TryRecvError::Empty) => { // No more messages available right now // Put receiver back for next time self.receiver = Some(receiver); if should_update_view { self.update_record_view(); } return; } Err(TryRecvError::Disconnected) => { // Thread finished self.stream_done = true; if self.rows.is_empty() && !matches!(self.state, ViewState::Records(_) | ViewState::Preview(_)) { self.state = ViewState::Empty; } // Don't put receiver back - we're done if should_update_view { self.update_record_view(); } return; } } } } /// Create or update the RecordView with current data fn update_record_view(&mut self) { if self.rows.is_empty() { return; } let cols = if self.columns.is_empty() { vec![String::new()] } else { self.columns.clone() }; match &mut self.state { ViewState::Records(existing_view) => { // Append new rows to existing view let layer = existing_view.get_top_layer_mut(); layer.record_values = self.rows.clone(); // Update cursor limits let _ = layer.cursor.y.view.set_size(layer.record_values.len()); let _ = layer.cursor.x.view.set_size(layer.column_names.len()); // Invalidate text to force redraw layer.record_text = None; } _ => { // Create new view with all accumulated data let mut view = RecordView::new(cols, self.rows.clone(), self.explore_config.clone()); if self.is_record { view.set_top_layer_orientation(Orientation::Left); } self.state = ViewState::Records(Box::new(view)); } } } fn spinner_char(&self) -> char { const SPINNER: &[char] = &['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']; SPINNER[self.frame_count % SPINNER.len()] } fn row_count(&self) -> usize { self.rows.len() } fn is_streaming(&self) -> bool { !self.stream_done } } impl View for NuView { fn draw(&mut self, f: &mut Frame, area: Rect, cfg: ViewConfig<'_>, layout: &mut Layout) { self.frame_count = self.frame_count.wrapping_add(1); // Tail the view if new rows have been added during streaming if self.rows.len() > self.last_row_count { self.last_row_count = self.rows.len(); if let ViewState::Records(view) = &mut self.state { view.tail(area.width, area.height); } } match &mut self.state { ViewState::Loading => { // Don't draw anything in the content area while loading // The status bar will show the spinner } ViewState::Records(view) => { view.draw(f, area, cfg, layout); } ViewState::Preview(view) => { view.draw(f, area, cfg, layout); } ViewState::Empty => { // Nothing to display } ViewState::Error(_) => { // Error is shown in status bar } } } fn handle_input( &mut self, engine_state: &EngineState, stack: &mut Stack, layout: &Layout, info: &mut ViewInfo, key: KeyEvent, ) -> Transition { match &mut self.state { ViewState::Records(view) => view.handle_input(engine_state, stack, layout, info, key), ViewState::Preview(view) => view.handle_input(engine_state, stack, layout, info, key), _ => Transition::None, } } fn update(&mut self, info: &mut ViewInfo) -> bool { // Process any pending messages from the stream self.process_messages(); // Update the status bar based on current state match &self.state { ViewState::Loading => { let spinner = self.spinner_char(); let msg = format!("{} Running: {}", spinner, self.command_text); info.status = Some(Report::message(msg, Severity::Info)); true // Keep polling } ViewState::Records(_) => { let row_count = self.row_count(); if self.is_streaming() { let spinner = self.spinner_char(); let msg = format!("{} Streaming: {} rows", spinner, row_count); info.status = Some(Report::message(msg, Severity::Info)); true // Keep polling } else { info.status = Some(Report::new( format!("{} rows", row_count), Severity::Info, String::new(), String::new(), String::new(), )); false // Done polling } } ViewState::Preview(_) => { info.status = Some(Report::message("Preview", Severity::Info)); false // Done polling } ViewState::Empty => { info.status = Some(Report::message("No output", Severity::Info)); false // Done polling } ViewState::Error(msg) => { info.status = Some(Report::error(msg.clone())); false // Done polling } } } fn show_data(&mut self, i: usize) -> bool { match &mut self.state { ViewState::Records(view) => view.show_data(i), ViewState::Preview(view) => view.show_data(i), _ => false, } } fn collect_data(&self) -> Vec<NuText> { match &self.state { ViewState::Records(view) => view.collect_data(), ViewState::Preview(view) => view.collect_data(), _ => Vec::new(), } } fn exit(&mut self) -> Option<Value> { match &mut self.state { ViewState::Records(view) => view.exit(), ViewState::Preview(view) => view.exit(), _ => None, } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/commands/help.rs
crates/nu-explore/src/explore/commands/help.rs
use super::super::views::{Preview, ViewConfig}; use super::ViewCommand; use anyhow::Result; use nu_ansi_term::Color; use nu_protocol::{ Value, engine::{EngineState, Stack}, }; use std::sync::LazyLock; #[derive(Debug, Default, Clone)] pub struct HelpCmd {} impl HelpCmd { pub const NAME: &'static str = "help"; pub fn view() -> Preview { Preview::new(&HELP_MESSAGE) } } static HELP_MESSAGE: LazyLock<String> = LazyLock::new(|| { let title = nu_ansi_term::Style::new().bold(); let section = nu_ansi_term::Style::new().bold().fg(Color::Cyan); let code = nu_ansi_term::Style::new().bold().fg(Color::Blue); let key = nu_ansi_term::Style::new().bold().fg(Color::Green); let dim = nu_ansi_term::Style::new().dimmed(); format!( r#" {} Explore Help {} Explore helps you dynamically navigate through your data. Launch it by piping data into the command: {} {} Navigation {} Move cursor up/down/left/right {} Drill into a cell (select it) {} Go back / exit current view {} Page up / Page down {} Data Manipulation {} Transpose (flip rows and columns) {} Expand (show all nested data) {} Commands {} {} Show this help page {} Open interactive REPL {} Run a Nushell command on current data {} Exit Explore {} Search {} Start forward search {} Start reverse search {} {} {} Navigate search results "#, title.paint("━━"), title.paint("━━"), code.paint("ls | explore"), section.paint("▸"), key.paint("↑ ↓ ← →"), key.paint("Enter"), key.paint("Esc / q"), key.paint("PgUp / PgDn"), section.paint("▸"), key.paint("t"), key.paint("e"), section.paint("▸"), dim.paint("(type : then command)"), key.paint(":help"), key.paint(":try"), key.paint(":nu <cmd>"), key.paint(":q"), section.paint("▸"), key.paint("/"), key.paint("?"), key.paint("n"), key.paint("N"), key.paint("Enter"), ) }); // TODO: search help could use some updating... search results get shown immediately after typing, don't need to press Enter // const HELP_MESSAGE: &str = r#"# Explore // Explore helps you dynamically navigate through your data // ## Basics // Move around: Use the cursor keys // Drill down into records+tables: Press <Enter> to select a cell, move around with cursor keys, then press <Enter> again // Go back/up a level: Press <Esc> // Transpose data (flip rows and columns): Press "t" // Expand data (show all nested data): Press "e" // Open this help page : Type ":help" then <Enter> // Open an interactive REPL: Type ":try" then <Enter> // Scroll up/down: Use the "Page Up" and "Page Down" keys // Exit Explore: Type ":q" then <Enter>, or Ctrl+D. Alternately, press <Esc> until Explore exits // ## Search // Most commands support search via regular expressions. // You can type "/" and type a pattern you want to search on. // Then hit <Enter> and you will see the search results. // To go to the next hit use "<n>" key. // You also can do a reverse search by using "?" instead of "/". // "#; impl ViewCommand for HelpCmd { type View = Preview; fn name(&self) -> &'static str { Self::NAME } fn description(&self) -> &'static str { "" } fn parse(&mut self, _: &str) -> Result<()> { Ok(()) } fn spawn( &mut self, _: &EngineState, _: &mut Stack, _: Option<Value>, _: &ViewConfig, ) -> Result<Self::View> { Ok(HelpCmd::view()) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/commands/table.rs
crates/nu-explore/src/explore/commands/table.rs
use super::super::{ nu_common::collect_input, views::{Orientation, RecordView, ViewConfig}, }; use super::ViewCommand; use anyhow::Result; use nu_protocol::{ Value, engine::{EngineState, Stack}, }; #[derive(Debug, Default, Clone)] pub struct TableCmd { // todo: add arguments to override config right from CMD settings: TableSettings, } #[derive(Debug, Default, Clone)] struct TableSettings { orientation: Option<Orientation>, turn_on_cursor_mode: bool, } impl TableCmd { pub fn new() -> Self { Self::default() } pub const NAME: &'static str = "table"; } impl ViewCommand for TableCmd { type View = RecordView; fn name(&self) -> &'static str { Self::NAME } fn description(&self) -> &'static str { "" } fn parse(&mut self, _: &str) -> Result<()> { Ok(()) } fn spawn( &mut self, _: &EngineState, _: &mut Stack, value: Option<Value>, config: &ViewConfig, ) -> Result<Self::View> { let value = value.unwrap_or_default(); let is_record = matches!(value, Value::Record { .. }); let (columns, data) = collect_input(value)?; let mut view = RecordView::new(columns, data, config.explore_config.clone()); if is_record { view.set_top_layer_orientation(Orientation::Left); } if let Some(o) = self.settings.orientation { view.set_top_layer_orientation(o); } if self.settings.turn_on_cursor_mode { view.set_cursor_mode(); } Ok(view) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/commands/quit.rs
crates/nu-explore/src/explore/commands/quit.rs
use super::super::pager::{Pager, Transition}; use super::SimpleCommand; use anyhow::Result; use nu_protocol::{ Value, engine::{EngineState, Stack}, }; #[derive(Default, Clone)] pub struct QuitCmd; impl QuitCmd { pub const NAME: &'static str = "quit"; } impl SimpleCommand for QuitCmd { fn name(&self) -> &'static str { Self::NAME } fn description(&self) -> &'static str { "" } fn parse(&mut self, _: &str) -> Result<()> { Ok(()) } fn react( &mut self, _: &EngineState, _: &mut Stack, _: &mut Pager<'_>, _: Option<Value>, ) -> Result<Transition> { Ok(Transition::Exit) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/commands/mod.rs
crates/nu-explore/src/explore/commands/mod.rs
use super::pager::{Pager, Transition}; use super::views::ViewConfig; use anyhow::Result; use nu_protocol::{ Value, engine::{EngineState, Stack}, }; mod expand; mod help; mod nu; mod quit; mod table; mod r#try; pub use expand::ExpandCmd; pub use help::HelpCmd; pub use nu::NuCmd; pub use quit::QuitCmd; pub use table::TableCmd; pub use r#try::TryCmd; pub trait SimpleCommand { fn name(&self) -> &'static str; fn description(&self) -> &'static str; fn parse(&mut self, args: &str) -> Result<()>; fn react( &mut self, engine_state: &EngineState, stack: &mut Stack, pager: &mut Pager<'_>, value: Option<Value>, ) -> Result<Transition>; } pub trait ViewCommand { type View; fn name(&self) -> &'static str; fn description(&self) -> &'static str; fn parse(&mut self, args: &str) -> Result<()>; fn spawn( &mut self, engine_state: &EngineState, stack: &mut Stack, value: Option<Value>, config: &ViewConfig, ) -> Result<Self::View>; }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/commands/try.rs
crates/nu-explore/src/explore/commands/try.rs
use super::super::views::{TryView, ViewConfig}; use super::ViewCommand; use anyhow::Result; use nu_protocol::{ Value, engine::{EngineState, Stack}, }; #[derive(Debug, Default, Clone)] pub struct TryCmd { command: String, } impl TryCmd { pub fn new() -> Self { Self { command: String::new(), } } pub const NAME: &'static str = "try"; } impl ViewCommand for TryCmd { type View = TryView; fn name(&self) -> &'static str { Self::NAME } fn description(&self) -> &'static str { "" } fn parse(&mut self, args: &str) -> Result<()> { args.trim().clone_into(&mut self.command); Ok(()) } fn spawn( &mut self, engine_state: &EngineState, stack: &mut Stack, value: Option<Value>, config: &ViewConfig, ) -> Result<Self::View> { let value = value.unwrap_or_default(); let mut view = TryView::new(value, config.explore_config.clone()); view.init(self.command.clone()); view.try_run(engine_state, stack)?; Ok(view) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/views/colored_text_widget.rs
crates/nu-explore/src/explore/views/colored_text_widget.rs
use std::borrow::Cow; use ansi_str::{AnsiStr, get_blocks}; use nu_table::{string_truncate, string_width}; use ratatui::{ layout::Rect, style::{Color, Modifier, Style}, widgets::Widget, }; /// A widget that represents a single line of text with ANSI styles. pub struct ColoredTextWidget<'a> { text: &'a str, /// Column to start rendering from col: usize, } impl<'a> ColoredTextWidget<'a> { pub fn new(text: &'a str, col: usize) -> Self { Self { text, col } } /// Return a window of the text that fits into the given width, with ANSI styles stripped. pub fn get_plain_text(&self, max_width: usize) -> String { cut_string(self.text, self.col, max_width) .ansi_strip() .into_owned() } } impl Widget for ColoredTextWidget<'_> { fn render(self, area: Rect, buf: &mut ratatui::buffer::Buffer) { let text = cut_string(self.text, self.col, area.width as usize); let mut offset = 0; for block in get_blocks(&text) { let text = block.text(); let style = style_to_tui(block.style()); let x = area.x + offset; let (o, _) = buf.set_stringn(x, area.y, text, area.width as usize, style); offset = o } } } fn cut_string(source: &str, skip: usize, width: usize) -> Cow<'_, str> { if source.is_empty() { return Cow::Borrowed(source); } let mut text = Cow::Borrowed(source); if skip > 0 { let skip_chars = source .ansi_strip() .chars() .scan((0usize, 0usize), |acc, c| { acc.0 += unicode_width::UnicodeWidthChar::width(c).unwrap_or(0); if acc.0 > skip { return None; } acc.1 = c.len_utf8(); Some(*acc) }) .map(|(_, b)| b) .sum::<usize>(); let cut_text = source .ansi_get(skip_chars..) .expect("must be OK") .into_owned(); text = Cow::Owned(cut_text); } if string_width(&text) > width { text = Cow::Owned(string_truncate(&text, width)); } text } fn style_to_tui(style: &ansi_str::Style) -> Style { let mut out = Style::default(); if let Some(clr) = style.background() { out.bg = ansi_color_to_tui_color(clr); } if let Some(clr) = style.foreground() { out.fg = ansi_color_to_tui_color(clr); } if style.is_slow_blink() || style.is_rapid_blink() { out.add_modifier |= Modifier::SLOW_BLINK; } if style.is_bold() { out.add_modifier |= Modifier::BOLD; } if style.is_faint() { out.add_modifier |= Modifier::DIM; } if style.is_hide() { out.add_modifier |= Modifier::HIDDEN; } if style.is_italic() { out.add_modifier |= Modifier::ITALIC; } if style.is_inverse() { out.add_modifier |= Modifier::REVERSED; } if style.is_underline() { out.add_modifier |= Modifier::UNDERLINED; } out } fn ansi_color_to_tui_color(clr: ansi_str::Color) -> Option<Color> { use ansi_str::Color::*; let clr = match clr { Black => Color::Black, BrightBlack => Color::DarkGray, Red => Color::Red, BrightRed => Color::LightRed, Green => Color::Green, BrightGreen => Color::LightGreen, Yellow => Color::Yellow, BrightYellow => Color::LightYellow, Blue => Color::Blue, BrightBlue => Color::LightBlue, Magenta => Color::Magenta, BrightMagenta => Color::LightMagenta, Cyan => Color::Cyan, BrightCyan => Color::LightCyan, White => Color::White, Fixed(i) => Color::Indexed(i), Rgb(r, g, b) => Color::Rgb(r, g, b), BrightWhite => Color::Gray, BrightPurple => Color::LightMagenta, Purple => Color::Magenta, }; Some(clr) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/views/util.rs
crates/nu-explore/src/explore/views/util.rs
use super::super::nu_common::{NuColor, NuStyle, NuText, truncate_str}; use nu_color_config::{Alignment, StyleComputer}; use nu_protocol::{ShellError, Value}; use nu_table::{TextStyle, string_width}; use ratatui::{ buffer::Buffer, style::{Color, Modifier, Style}, text::Span, }; use std::borrow::Cow; pub fn set_span( buf: &mut Buffer, (x, y): (u16, u16), text: &str, style: Style, max_width: u16, ) -> u16 { let mut text = Cow::Borrowed(text); let mut text_width = string_width(&text); if text_width > max_width as usize { let mut s = text.into_owned(); truncate_str(&mut s, max_width as usize); text = Cow::Owned(s); text_width = max_width as usize; } let span = Span::styled(text.as_ref(), style); buf.set_span(x, y, &span, text_width as u16); text_width as u16 } pub fn nu_style_to_tui(style: NuStyle) -> ratatui::style::Style { let mut out = ratatui::style::Style::default(); if let Some(clr) = style.background { out.bg = nu_ansi_color_to_tui_color(clr); } if let Some(clr) = style.foreground { out.fg = nu_ansi_color_to_tui_color(clr); } if style.is_blink { out.add_modifier |= Modifier::SLOW_BLINK; } if style.is_bold { out.add_modifier |= Modifier::BOLD; } if style.is_dimmed { out.add_modifier |= Modifier::DIM; } if style.is_hidden { out.add_modifier |= Modifier::HIDDEN; } if style.is_italic { out.add_modifier |= Modifier::ITALIC; } if style.is_reverse { out.add_modifier |= Modifier::REVERSED; } if style.is_underline { out.add_modifier |= Modifier::UNDERLINED; } out } pub fn nu_ansi_color_to_tui_color(clr: NuColor) -> Option<ratatui::style::Color> { use NuColor::*; let clr = match clr { Black => Color::Black, DarkGray => Color::DarkGray, Red => Color::Red, LightRed => Color::LightRed, Green => Color::Green, LightGreen => Color::LightGreen, Yellow => Color::Yellow, LightYellow => Color::LightYellow, Blue => Color::Blue, LightBlue => Color::LightBlue, Magenta => Color::Magenta, LightMagenta => Color::LightMagenta, Cyan => Color::Cyan, LightCyan => Color::LightCyan, White => Color::White, Fixed(i) => Color::Indexed(i), Rgb(r, g, b) => ratatui::style::Color::Rgb(r, g, b), LightGray => Color::Gray, LightPurple => Color::LightMagenta, Purple => Color::Magenta, Default => return None, }; Some(clr) } pub fn text_style_to_tui_style(style: TextStyle) -> ratatui::style::Style { let mut out = ratatui::style::Style::default(); if let Some(style) = style.color_style { out = nu_style_to_tui(style); } out } // This is identical to the same function in nu-explore/src/nu_common pub fn make_styled_string( style_computer: &StyleComputer, text: String, value: Option<&Value>, // None represents table holes. float_precision: usize, ) -> NuText { match value { Some(value) => { match value { Value::Float { .. } => { // set dynamic precision from config let precise_number = match convert_with_precision(&text, float_precision) { Ok(num) => num, Err(e) => e.to_string(), }; (precise_number, style_computer.style_primitive(value)) } _ => (text, style_computer.style_primitive(value)), } } None => { // Though holes are not the same as null, the closure for "empty" is passed a null anyway. ( text, TextStyle::with_style( Alignment::Center, style_computer.compute("empty", &Value::nothing(nu_protocol::Span::unknown())), ), ) } } } fn convert_with_precision(val: &str, precision: usize) -> Result<String, ShellError> { // val will always be a f64 so convert it with precision formatting let val_float = match val.trim().parse::<f64>() { Ok(f) => f, Err(e) => { return Err(ShellError::GenericError { error: format!("error converting string [{}] to f64", &val), msg: "".into(), span: None, help: Some(e.to_string()), inner: vec![], }); } }; Ok(format!("{val_float:.precision$}")) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/views/mod.rs
crates/nu-explore/src/explore/views/mod.rs
mod binary; mod colored_text_widget; mod cursor; mod preview; mod record; mod r#try; pub mod util; use super::{ config::ExploreConfig, nu_common::{NuConfig, NuText}, pager::{Frame, Transition, ViewInfo}, }; use crossterm::event::KeyEvent; use lscolors::LsColors; use nu_color_config::StyleComputer; use nu_protocol::{ Value, engine::{EngineState, Stack}, }; use ratatui::layout::Rect; pub use binary::BinaryView; pub use preview::Preview; pub use record::{Orientation, RecordView}; pub use r#try::TryView; #[derive(Debug, Default)] pub struct Layout { pub data: Vec<ElementInfo>, } impl Layout { fn push(&mut self, text: &str, x: u16, y: u16, width: u16, height: u16) { self.data.push(ElementInfo::new(text, x, y, width, height)); } } #[derive(Debug, Default, Clone)] pub struct ElementInfo { // todo: make it a Cow pub text: String, pub area: Rect, } impl ElementInfo { pub fn new(text: impl Into<String>, x: u16, y: u16, width: u16, height: u16) -> Self { Self { text: text.into(), area: Rect::new(x, y, width, height), } } } #[derive(Debug, Clone, Copy)] pub struct ViewConfig<'a> { pub nu_config: &'a NuConfig, pub explore_config: &'a ExploreConfig, pub style_computer: &'a StyleComputer<'a>, pub lscolors: &'a LsColors, pub cwd: &'a str, } impl<'a> ViewConfig<'a> { pub fn new( nu_config: &'a NuConfig, explore_config: &'a ExploreConfig, style_computer: &'a StyleComputer<'a>, lscolors: &'a LsColors, cwd: &'a str, ) -> Self { Self { nu_config, explore_config, style_computer, lscolors, cwd, } } } pub trait View { fn draw(&mut self, f: &mut Frame, area: Rect, cfg: ViewConfig<'_>, layout: &mut Layout); fn handle_input( &mut self, engine_state: &EngineState, stack: &mut Stack, layout: &Layout, info: &mut ViewInfo, key: KeyEvent, ) -> Transition; /// Called every frame to allow the view to update its internal state /// (e.g., check for streaming data) and update the status bar. /// Returns true if the view has pending updates that require continued polling. fn update(&mut self, _info: &mut ViewInfo) -> bool { false } fn show_data(&mut self, _: usize) -> bool { false } fn collect_data(&self) -> Vec<NuText> { Vec::new() } fn exit(&mut self) -> Option<Value> { None } } impl View for Box<dyn View> { fn draw(&mut self, f: &mut Frame, area: Rect, cfg: ViewConfig<'_>, layout: &mut Layout) { self.as_mut().draw(f, area, cfg, layout) } fn handle_input( &mut self, engine_state: &EngineState, stack: &mut Stack, layout: &Layout, info: &mut ViewInfo, key: KeyEvent, ) -> Transition { self.as_mut() .handle_input(engine_state, stack, layout, info, key) } fn update(&mut self, info: &mut ViewInfo) -> bool { self.as_mut().update(info) } fn collect_data(&self) -> Vec<NuText> { self.as_ref().collect_data() } fn exit(&mut self) -> Option<Value> { self.as_mut().exit() } fn show_data(&mut self, i: usize) -> bool { self.as_mut().show_data(i) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/views/try.rs
crates/nu-explore/src/explore/views/try.rs
use super::super::{ config::ExploreConfig, nu_common::{collect_pipeline, run_command_with_value}, pager::{Frame, Transition, ViewInfo, report::Report}, }; use super::{Layout, Orientation, View, ViewConfig, record::RecordView, util::nu_style_to_tui}; use anyhow::Result; use crossterm::event::{KeyCode, KeyEvent}; use nu_protocol::{ PipelineData, Value, engine::{EngineState, Stack}, }; use ratatui::{ layout::Rect, style::{Modifier, Style}, text::{Line, Span}, widgets::{Block, BorderType, Borders, Paragraph}, }; use std::cmp::min; use unicode_width::UnicodeWidthStr; pub struct TryView { input: Value, command: String, immediate: bool, table: Option<RecordView>, view_mode: bool, border_color: Style, config: ExploreConfig, } impl TryView { pub fn new(input: Value, config: ExploreConfig) -> Self { Self { input, table: None, immediate: config.try_reactive, border_color: nu_style_to_tui(config.table.separator_style), view_mode: false, command: String::new(), config, } } pub fn init(&mut self, command: String) { self.command = command; } pub fn try_run(&mut self, engine_state: &EngineState, stack: &mut Stack) -> Result<()> { let view = run_command( &self.command, &self.input, engine_state, stack, &self.config, )?; self.table = Some(view); Ok(()) } } impl View for TryView { fn draw(&mut self, f: &mut Frame, area: Rect, cfg: ViewConfig<'_>, layout: &mut Layout) { let border_color = self.border_color; // Calculate areas with better proportions let cmd_height: u16 = 3; let margin: u16 = 1; // Command input area at the top let cmd_area = Rect::new( area.x + margin, area.y, area.width.saturating_sub(margin * 2), cmd_height, ); // Results area below let table_area = Rect::new( area.x + margin, area.y + cmd_height, area.width.saturating_sub(margin * 2), area.height.saturating_sub(cmd_height), ); // Draw command input block with rounded corners let cmd_block = if self.view_mode { Block::default() .borders(Borders::ALL) .border_type(BorderType::Rounded) .border_style(border_color) .title(Line::from(vec![ Span::styled(" ", Style::default()), Span::styled("Command", border_color), Span::styled(" ", Style::default()), ])) } else { Block::default() .borders(Borders::ALL) .border_type(BorderType::Rounded) .border_style(border_color.add_modifier(Modifier::BOLD)) .title(Line::from(vec![ Span::styled(" ", Style::default()), Span::styled("Command", border_color.add_modifier(Modifier::BOLD)), Span::styled(" ▸ ", border_color.add_modifier(Modifier::BOLD)), ])) }; f.render_widget(cmd_block, cmd_area); // Render the command input text let cmd_input_area = Rect::new( cmd_area.x + 2, cmd_area.y + 1, cmd_area.width.saturating_sub(4), 1, ); let input = self.command.as_str(); let prompt = "❯ "; let prompt_width = prompt.width() as u16; let max_cmd_len = cmd_input_area.width.saturating_sub(prompt_width); let display_input = if input.width() as u16 > max_cmd_len { // Take last max_cmd_len chars when input is too long let take_bytes = input .chars() .rev() .take(max_cmd_len as usize) .map(|c| c.len_utf8()) .sum::<usize>(); let skip = input.len() - take_bytes; &input[skip..] } else { input }; let cmd_line = Line::from(vec![ Span::styled(prompt, border_color.add_modifier(Modifier::BOLD)), Span::raw(display_input), ]); let cmd_input = Paragraph::new(cmd_line); f.render_widget(cmd_input, cmd_input_area); // Position cursor at end of input when in command mode if !self.view_mode { let cursor_x = cmd_input_area.x + prompt_width + min(display_input.width() as u16, max_cmd_len); let cursor_x_max = cmd_input_area.x + cmd_input_area.width.saturating_sub(1); if cursor_x <= cursor_x_max { f.set_cursor_position((cursor_x, cmd_input_area.y)); } } // Draw results block with rounded corners let table_block = if self.view_mode { Block::default() .borders(Borders::ALL) .border_type(BorderType::Rounded) .border_style(border_color.add_modifier(Modifier::BOLD)) .title(Line::from(vec![ Span::styled(" ", Style::default()), Span::styled("Results", border_color.add_modifier(Modifier::BOLD)), Span::styled(" ◂ ", border_color.add_modifier(Modifier::BOLD)), ])) } else { Block::default() .borders(Borders::ALL) .border_type(BorderType::Rounded) .border_style(border_color) .title(Line::from(vec![ Span::styled(" ", Style::default()), Span::styled("Results", border_color), Span::styled(" ", Style::default()), ])) }; f.render_widget(table_block, table_area); // Render the table inside the results block if let Some(table) = &mut self.table { let inner_area = Rect::new( table_area.x + 1, table_area.y + 1, table_area.width.saturating_sub(2), table_area.height.saturating_sub(2), ); if inner_area.width > 0 && inner_area.height > 0 { table.draw(f, inner_area, cfg, layout); } } else { // Show hint when no results yet let hint_area = Rect::new( table_area.x + 2, table_area.y + 1, table_area.width.saturating_sub(4), 1, ); let hint = Paragraph::new(Line::from(vec![ Span::styled( "Type a command and press ", Style::default().add_modifier(Modifier::DIM), ), Span::styled("Enter", border_color), Span::styled( " to see results", Style::default().add_modifier(Modifier::DIM), ), ])); f.render_widget(hint, hint_area); } } fn handle_input( &mut self, engine_state: &EngineState, stack: &mut Stack, layout: &Layout, info: &mut ViewInfo, key: KeyEvent, ) -> Transition { if self.view_mode { let table = self .table .as_mut() .expect("we know that we have a table cause of a flag"); let was_at_the_top = table.get_cursor_position().row == 0; if was_at_the_top && matches!(key.code, KeyCode::Up | KeyCode::PageUp) { self.view_mode = false; return Transition::Ok; } if let KeyCode::Tab = key.code { self.view_mode = false; return Transition::Ok; } let result = table.handle_input(engine_state, stack, layout, info, key); return match result { Transition::Ok | Transition::Cmd { .. } => Transition::Ok, Transition::Exit => { self.view_mode = false; Transition::Ok } Transition::None => Transition::None, }; } match &key.code { KeyCode::Esc => Transition::Exit, KeyCode::Backspace => { if !self.command.is_empty() { self.command.pop(); if self.immediate { match self.try_run(engine_state, stack) { Ok(_) => info.report = Some(Report::default()), Err(err) => info.report = Some(Report::error(format!("Error: {err}"))), } } } Transition::Ok } KeyCode::Char(c) => { self.command.push(*c); if self.immediate { match self.try_run(engine_state, stack) { Ok(_) => info.report = Some(Report::default()), Err(err) => info.report = Some(Report::error(format!("Error: {err}"))), } } Transition::Ok } KeyCode::Down | KeyCode::Tab => { if self.table.is_some() { self.view_mode = true; } Transition::Ok } KeyCode::Enter => { match self.try_run(engine_state, stack) { Ok(_) => info.report = Some(Report::default()), Err(err) => info.report = Some(Report::error(format!("Error: {err}"))), } Transition::Ok } _ => Transition::None, } } fn exit(&mut self) -> Option<Value> { self.table.as_mut().and_then(|v| v.exit()) } fn collect_data(&self) -> Vec<super::super::nu_common::NuText> { self.table .as_ref() .map_or_else(Vec::new, |v| v.collect_data()) } fn show_data(&mut self, i: usize) -> bool { self.table.as_mut().is_some_and(|v| v.show_data(i)) } } fn run_command( command: &str, input: &Value, engine_state: &EngineState, stack: &mut Stack, config: &ExploreConfig, ) -> Result<RecordView> { let pipeline = run_command_with_value(command, input, engine_state, stack)?; let is_record = matches!(pipeline, PipelineData::Value(Value::Record { .. }, ..)); let (columns, values) = collect_pipeline(pipeline)?; let mut view = RecordView::new(columns, values, config.clone()); if is_record { view.set_top_layer_orientation(Orientation::Left); } Ok(view) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/views/preview.rs
crates/nu-explore/src/explore/views/preview.rs
use super::super::{ nu_common::{NuSpan, NuText}, pager::{Frame, StatusTopOrEnd, Transition, ViewInfo, report::Report}, }; use super::{ Layout, View, ViewConfig, colored_text_widget::ColoredTextWidget, cursor::CursorMoveHandler, cursor::WindowCursor2D, }; use crossterm::event::KeyEvent; use nu_color_config::TextStyle; use nu_protocol::{ Value, engine::{EngineState, Stack}, }; use ratatui::layout::Rect; use std::cmp::max; // todo: Add wrap option #[derive(Debug)] pub struct Preview { underlying_value: Option<Value>, lines: Vec<String>, cursor: WindowCursor2D, } impl Preview { pub fn new(value: &str) -> Self { let lines: Vec<String> = value .lines() .map(|line| line.replace('\t', " ")) // tui: doesn't support TAB .collect(); // TODO: refactor so this is fallible and returns a Result instead of panicking let cursor = WindowCursor2D::new(lines.len(), usize::MAX).expect("Failed to create cursor"); Self { lines, cursor, underlying_value: None, } } } impl View for Preview { fn draw(&mut self, f: &mut Frame, area: Rect, _: ViewConfig<'_>, layout: &mut Layout) { let _ = self .cursor .set_window_size(area.height as usize, area.width as usize); let lines = &self.lines[self.cursor.window_origin().row..]; for (i, line) in lines.iter().enumerate().take(area.height as usize) { let text_widget = ColoredTextWidget::new(line, self.cursor.column()); let plain_text = text_widget.get_plain_text(area.width as usize); let area = Rect::new(area.x, area.y + i as u16, area.width, 1); f.render_widget(text_widget, area); // push the plain text to layout so it can be searched layout.push(&plain_text, area.x, area.y, area.width, area.height); } } fn handle_input( &mut self, _: &EngineState, _: &mut Stack, _: &Layout, info: &mut ViewInfo, // add this arg to draw too? key: KeyEvent, ) -> Transition { match self.handle_input_key(&key) { Ok((transition, status_top_or_end)) => { match status_top_or_end { StatusTopOrEnd::Top => set_status_top(self, info), StatusTopOrEnd::End => set_status_end(self, info), _ => {} } transition } _ => Transition::None, // currently only handle_enter() in crates/nu-explore/src/views/record/mod.rs raises an Err() } } fn collect_data(&self) -> Vec<NuText> { self.lines .iter() .map(|line| (line.to_owned(), TextStyle::default())) .collect::<Vec<_>>() } fn show_data(&mut self, row: usize) -> bool { // we can only go to the appropriate line, but we can't target column // // todo: improve somehow? self.cursor.set_window_start_position(row, 0); true } fn exit(&mut self) -> Option<Value> { match &self.underlying_value { Some(value) => Some(value.clone()), None => { let text = self.lines.join("\n"); Some(Value::string(text, NuSpan::unknown())) } } } } impl CursorMoveHandler for Preview { fn get_cursor(&mut self) -> &mut WindowCursor2D { &mut self.cursor } fn handle_left(&mut self) { self.cursor .prev_column_by(max(1, self.cursor.window_width_in_columns() / 2)); } fn handle_right(&mut self) { self.cursor .next_column_by(max(1, self.cursor.window_width_in_columns() / 2)); } } fn set_status_end(view: &Preview, info: &mut ViewInfo) { if view.cursor.row() + 1 == view.cursor.row_limit() { info.status = Some(Report::info("END")); } else { info.status = Some(Report::default()); } } fn set_status_top(view: &Preview, info: &mut ViewInfo) { if view.cursor.window_origin().row == 0 { info.status = Some(Report::info("TOP")); } else { info.status = Some(Report::default()); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/views/cursor/mod.rs
crates/nu-explore/src/explore/views/cursor/mod.rs
mod window_cursor; mod window_cursor_2d; use anyhow::{Result, bail}; pub use window_cursor::WindowCursor; pub use window_cursor_2d::{CursorMoveHandler, Position, WindowCursor2D}; /// A 1-dimensional cursor to track a position from 0 to N /// /// Say we have a cursor with size=9, at position 3: /// 0 1 2 3 4 5 6 7 8 9 /// | | | C | | | | | | /// /// After moving forward by 2 steps: /// 0 1 2 3 4 5 6 7 8 9 /// | | | | | C | | | | /// /// After moving backward by 6 steps (clamped to 0): /// 0 1 2 3 4 5 6 7 8 9 /// C | | | | | | | | | #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct Cursor { /// The current position of the cursor position: usize, /// The number of distinct positions the cursor can be at size: usize, } impl Cursor { /// Constructor to create a new Cursor pub fn new(size: usize) -> Self { // In theory we should not be able to create a cursor with size 0, but in practice // it's easier to allow that for empty lists etc. instead of propagating errors Cursor { position: 0, size } } /// The max position the cursor can be at pub fn end(&self) -> usize { self.size.saturating_sub(1) } /// Set the position to a specific value within the bounds [0, end] pub fn set_position(&mut self, pos: usize) { if pos <= self.end() { self.position = pos; } else { // Clamp the position to end if out of bounds self.position = self.end(); } } /// Set the size of the cursor. The position is clamped if it exceeds the new size pub fn set_size(&mut self, size: usize) -> Result<()> { if size == 0 { bail!("Size cannot be zero"); } self.size = size; if self.position > self.end() { self.position = self.end(); } Ok(()) } /// Move the cursor forward by a specified number of steps pub fn move_forward(&mut self, steps: usize) { if self.position + steps <= self.end() { self.position += steps; } else { self.position = self.end(); } } /// Move the cursor backward by a specified number of steps pub fn move_backward(&mut self, steps: usize) { if self.position >= steps { self.position -= steps; } else { self.position = 0; } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_cursor_set_position() { // from 0 to 9 let mut cursor = Cursor::new(10); cursor.set_position(5); assert_eq!(cursor.position, 5); cursor.set_position(15); assert_eq!(cursor.position, 9); } #[test] fn test_cursor_move_forward() { // from 0 to 9 let mut cursor = Cursor::new(10); assert_eq!(cursor.position, 0); cursor.move_forward(3); assert_eq!(cursor.position, 3); cursor.move_forward(10); assert_eq!(cursor.position, 9); } #[test] fn test_cursor_move_backward() { // from 0 to 9 let mut cursor = Cursor::new(10); cursor.move_backward(3); assert_eq!(cursor.position, 0); cursor.move_forward(5); assert_eq!(cursor.position, 5); cursor.move_backward(3); assert_eq!(cursor.position, 2); cursor.move_backward(3); assert_eq!(cursor.position, 0); } #[test] fn test_cursor_size_zero_handling() { let cursor = Cursor::new(0); assert_eq!(cursor.end(), 0); let mut cursor = Cursor::new(0); cursor.move_forward(1); assert_eq!(cursor.position, 0); cursor.move_backward(1); assert_eq!(cursor.position, 0); } #[test] fn test_cursor_size_one() { let mut cursor = Cursor::new(1); assert_eq!(cursor.end(), 0); cursor.move_forward(1); assert_eq!(cursor.position, 0); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/views/cursor/window_cursor.rs
crates/nu-explore/src/explore/views/cursor/window_cursor.rs
use std::cmp::min; use super::Cursor; use anyhow::{Ok, Result, bail}; /// WindowCursor provides a mechanism to navigate through a 1-dimensional range /// using a smaller movable window within the view. /// /// View: The larger context or total allowable range for navigation. /// Window: The smaller, focused subset of the view. /// /// Example: /// ```plaintext /// 1. Initial view of size 20 with a window of size 5. The absolute cursor position starts at 0. /// View : /// |--------------------| /// Window : /// |X====| /// /// 2. After advancing the window by 3, the absolute cursor position becomes 3. /// View : /// |--------------------| /// Window : /// |X====| /// /// 3. After advancing the cursor inside the window by 2, the absolute cursor position becomes 5. /// View : /// |--------------------| /// Window : /// |==X==| /// ``` #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct WindowCursor { pub view: Cursor, pub window: Cursor, } impl WindowCursor { pub fn new(view_size: usize, window_size: usize) -> Result<Self> { if window_size > view_size { bail!("Window size cannot be greater than view size"); } Ok(Self { view: Cursor::new(view_size), window: Cursor::new(window_size), }) } pub fn absolute_position(&self) -> usize { self.window_starts_at() + self.window.position } pub fn window_relative_position(&self) -> usize { self.window.position } pub fn window_starts_at(&self) -> usize { self.view.position } pub fn window_size(&self) -> usize { self.window.size } pub fn end(&self) -> usize { self.view.end() } pub fn set_window_start_position(&mut self, i: usize) { self.view.set_position(i) } pub fn move_window_to_end(&mut self) { self.view.set_position(self.end() - self.window_size() + 1); } pub fn set_window_size(&mut self, new_size: usize) -> Result<()> { if new_size > self.view.size { // TODO: should we return an error here or clamp? the Ok is copying existing behavior return Ok(()); } self.window.set_size(new_size)?; Ok(()) } pub fn next_n(&mut self, n: usize) { for _ in 0..n { self.next(); } } pub fn next(&mut self) { if self.absolute_position() >= self.end() { return; } if self.window_relative_position() == self.window.end() { self.view.move_forward(1); } else { self.window.move_forward(1); } } pub fn next_window(&mut self) { self.move_cursor_to_end_of_window(); // move window forward by window size, or less if that would send it off the end of the view let window_end = self.window_starts_at() + self.window_size() - 1; let distance_from_window_end_to_view_end = self.end() - window_end; self.view.move_forward(min( distance_from_window_end_to_view_end, self.window_size(), )); } pub fn prev_n(&mut self, n: usize) { for _ in 0..n { self.prev(); } } pub fn prev(&mut self) { if self.window_relative_position() == 0 { self.view.move_backward(1); } else { self.window.move_backward(1); } } pub fn prev_window(&mut self) { self.move_cursor_to_start_of_window(); // move the whole window back self.view.move_backward(self.window_size()); } pub fn move_cursor_to_start_of_window(&mut self) { self.window.move_backward(self.window_size()); } pub fn move_cursor_to_end_of_window(&mut self) { self.window.move_forward(self.window_size()); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/views/cursor/window_cursor_2d.rs
crates/nu-explore/src/explore/views/cursor/window_cursor_2d.rs
use super::super::super::pager::{StatusTopOrEnd, Transition}; use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; use super::WindowCursor; use anyhow::Result; /// `WindowCursor2D` manages a 2-dimensional "window" onto a grid of cells, with a cursor that can point to a specific cell. /// For example, consider a 3x3 grid of cells: /// /// +---+---+---+ /// | a | b | c | /// |---|---|---| /// | d | e | f | /// |---|---|---| /// | g | h | i | /// +---+---+---+ /// /// A `WindowCursor2D` can be used to track the currently visible section of this grid. /// For example, a 2x2 window onto this grid could initially show the top left 2x2 section: /// /// +---+---+ /// | a | b | /// |---|---| /// | d | e | /// +---+---+ /// /// Moving the window down 1 row: /// /// +---+---+ /// | d | e | /// |---|---| /// | g | h | /// +---+---+ /// /// Inside the window, the cursor can point to a specific cell. #[derive(Debug, Default, Clone, Copy)] pub struct WindowCursor2D { pub x: WindowCursor, pub y: WindowCursor, } pub struct Position { pub row: usize, pub column: usize, } impl WindowCursor2D { pub fn new(count_rows: usize, count_columns: usize) -> Result<Self> { Ok(Self { x: WindowCursor::new(count_columns, count_columns)?, y: WindowCursor::new(count_rows, count_rows)?, }) } pub fn set_window_size(&mut self, count_rows: usize, count_columns: usize) -> Result<()> { self.x.set_window_size(count_columns)?; self.y.set_window_size(count_rows)?; Ok(()) } pub fn set_window_start_position(&mut self, row: usize, col: usize) { self.x.set_window_start_position(col); self.y.set_window_start_position(row); } /// The absolute position of the cursor in the grid (0-indexed, row only) pub fn row(&self) -> usize { self.y.absolute_position() } /// The absolute position of the cursor in the grid (0-indexed, column only) pub fn column(&self) -> usize { self.x.absolute_position() } /// The absolute position of the cursor in the grid (0-indexed) pub fn position(&self) -> Position { Position { row: self.row(), column: self.column(), } } pub fn row_limit(&self) -> usize { self.y.end() } pub fn window_origin(&self) -> Position { Position { row: self.y.window_starts_at(), column: self.x.window_starts_at(), } } pub fn window_relative_position(&self) -> Position { Position { row: self.y.window_relative_position(), column: self.x.window_relative_position(), } } pub fn window_width_in_columns(&self) -> usize { self.x.window_size() } pub fn next_row(&mut self) { self.y.next_n(1) } pub fn next_row_page(&mut self) { self.y.next_window() } pub fn row_move_to_end(&mut self) { self.y.move_window_to_end(); self.y.move_cursor_to_end_of_window(); } pub fn row_move_to_start(&mut self) { self.y.move_cursor_to_start_of_window(); self.y.set_window_start_position(0); } pub fn prev_row(&mut self) { self.y.prev() } pub fn prev_row_page(&mut self) { self.y.prev_window() } pub fn next_column(&mut self) { self.x.next() } pub fn next_column_by(&mut self, i: usize) { self.x.next_n(i) } pub fn prev_column(&mut self) { self.x.prev() } pub fn prev_column_by(&mut self, i: usize) { self.x.prev_n(i) } pub fn next_column_i(&mut self) { self.x .set_window_start_position(self.x.window_starts_at() + 1) } pub fn prev_column_i(&mut self) { if self.x.window_starts_at() == 0 { return; } self.x .set_window_start_position(self.x.window_starts_at() - 1) } pub fn next_row_i(&mut self) { self.y .set_window_start_position(self.y.window_starts_at() + 1) } pub fn prev_row_i(&mut self) { if self.y.window_starts_at() == 0 { return; } self.y .set_window_start_position(self.y.window_starts_at() - 1) } } pub trait CursorMoveHandler { fn get_cursor(&mut self) -> &mut WindowCursor2D; // standard handle_EVENT handlers that can be overwritten fn handle_enter(&mut self) -> Result<Transition> { Ok(Transition::None) } fn handle_esc(&mut self) -> Transition { Transition::Exit } fn handle_expand(&mut self) -> Transition { Transition::None } fn handle_left(&mut self) { self.get_cursor().prev_column_i() } fn handle_right(&mut self) { self.get_cursor().next_column_i() } fn handle_up(&mut self) { self.get_cursor().prev_row_i() } fn handle_down(&mut self) { self.get_cursor().next_row_i() } fn handle_transpose(&mut self) -> Transition { Transition::None } // top-level event handler should not be overwritten fn handle_input_key(&mut self, key: &KeyEvent) -> Result<(Transition, StatusTopOrEnd)> { let key_combo_status = match key { // PageUp supports Vi (Ctrl+b) and Emacs (Alt+v) keybindings KeyEvent { modifiers: KeyModifiers::CONTROL, code: KeyCode::Char('b'), .. } | KeyEvent { modifiers: KeyModifiers::ALT, code: KeyCode::Char('v'), .. } | KeyEvent { code: KeyCode::PageUp, .. } => { self.get_cursor().prev_row_page(); StatusTopOrEnd::Top } // PageDown supports Vi (Ctrl+f) and Emacs (Ctrl+v) keybindings KeyEvent { modifiers: KeyModifiers::CONTROL, code: KeyCode::Char('f'), .. } | KeyEvent { modifiers: KeyModifiers::CONTROL, code: KeyCode::Char('v'), .. } | KeyEvent { code: KeyCode::PageDown, .. } => { self.get_cursor().next_row_page(); self.get_cursor().prev_row(); StatusTopOrEnd::End } // Up support Emacs (Ctrl+p) keybinding KeyEvent { modifiers: KeyModifiers::CONTROL, code: KeyCode::Char('p'), .. } => { self.handle_up(); StatusTopOrEnd::Top } // Down support Emacs (Ctrl+n) keybinding KeyEvent { modifiers: KeyModifiers::CONTROL, code: KeyCode::Char('n'), .. } => { self.handle_down(); StatusTopOrEnd::End } _ => StatusTopOrEnd::None, }; match key_combo_status { StatusTopOrEnd::Top | StatusTopOrEnd::End => { return Ok((Transition::Ok, key_combo_status)); } _ => {} // not page up or page down, so don't return; continue to next match block } match key.code { KeyCode::Char('q') | KeyCode::Esc => Ok((self.handle_esc(), StatusTopOrEnd::None)), KeyCode::Char('i') | KeyCode::Enter => Ok((self.handle_enter()?, StatusTopOrEnd::None)), KeyCode::Char('t') => Ok((self.handle_transpose(), StatusTopOrEnd::None)), KeyCode::Char('e') => Ok((self.handle_expand(), StatusTopOrEnd::None)), KeyCode::Up | KeyCode::Char('k') => { self.handle_up(); Ok((Transition::Ok, StatusTopOrEnd::Top)) } KeyCode::Down | KeyCode::Char('j') => { self.handle_down(); Ok((Transition::Ok, StatusTopOrEnd::End)) } KeyCode::Left | KeyCode::Char('h') => { self.handle_left(); Ok((Transition::Ok, StatusTopOrEnd::None)) } KeyCode::Right | KeyCode::Char('l') => { self.handle_right(); Ok((Transition::Ok, StatusTopOrEnd::None)) } KeyCode::Home | KeyCode::Char('g') => { self.get_cursor().row_move_to_start(); Ok((Transition::Ok, StatusTopOrEnd::Top)) } KeyCode::End | KeyCode::Char('G') => { self.get_cursor().row_move_to_end(); Ok((Transition::Ok, StatusTopOrEnd::End)) } _ => Ok((Transition::None, StatusTopOrEnd::None)), } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/views/record/table_widget.rs
crates/nu-explore/src/explore/views/record/table_widget.rs
use super::super::super::{ config::TableConfig, nu_common::{NuStyle, NuText, truncate_str}, }; use super::super::util::{nu_style_to_tui, text_style_to_tui_style}; use super::Layout; use nu_color_config::{Alignment, StyleComputer, TextStyle}; use nu_protocol::Value; use nu_table::string_width; use ratatui::{ buffer::Buffer, layout::Rect, text::Span, widgets::{Block, Borders, Paragraph, StatefulWidget, Widget}, }; use std::cmp::{Ordering, max}; #[derive(Debug, Clone)] pub struct TableWidget<'a> { columns: &'a [String], data: &'a [Vec<NuText>], index_row: usize, index_column: usize, config: TableConfig, header_position: Orientation, style_computer: &'a StyleComputer<'a>, } // Basically: where's the header of the value being displayed? Usually at the top for tables, on the left for records #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Orientation { Top, Left, } impl<'a> TableWidget<'a> { #[allow(clippy::too_many_arguments)] pub fn new( columns: &'a [String], data: &'a [Vec<NuText>], style_computer: &'a StyleComputer<'a>, index_row: usize, index_column: usize, config: TableConfig, header_position: Orientation, ) -> Self { Self { columns, data, style_computer, index_row, index_column, config, header_position, } } } #[derive(Debug, Default)] pub struct TableWidgetState { pub layout: Layout, pub count_rows: usize, pub count_columns: usize, pub data_height: u16, } impl StatefulWidget for TableWidget<'_> { type State = TableWidgetState; fn render( self, area: ratatui::layout::Rect, buf: &mut ratatui::buffer::Buffer, state: &mut Self::State, ) { if area.width < 5 { return; } let is_horizontal = matches!(self.header_position, Orientation::Top); if is_horizontal { self.render_table_horizontal(area, buf, state); } else { self.render_table_vertical(area, buf, state); } } } // todo: refactoring these to methods as they have quite a bit in common. impl TableWidget<'_> { // header at the top; header is always 1 line fn render_table_horizontal(self, area: Rect, buf: &mut Buffer, state: &mut TableWidgetState) { let padding_l = self.config.column_padding_left as u16; let padding_r = self.config.column_padding_right as u16; let show_index = self.config.show_index; let show_head = self.config.show_header; let separator_s = self.config.separator_style; let mut data_height = area.height; let mut data_y = area.y; let mut head_y = area.y; if show_head { data_y += 1; data_height -= 1; // top line data_y += 1; data_height -= 1; head_y += 1; // bottom line data_y += 1; data_height -= 1; } if area.width == 0 || area.height == 0 { return; } let mut width = area.x; let mut data = &self.data[self.index_row..]; if data.len() > data_height as usize { data = &data[..data_height as usize]; } if show_head { render_header_borders(buf, area, 1, separator_s); } if show_index { width += render_index( buf, Rect::new(width, data_y, area.width, data_height), self.style_computer, self.index_row, padding_l, padding_r, ); width += render_split_line(buf, width, area.y, area.height, show_head, separator_s); } // if there is more data than we can show, add an ellipsis to the column headers to hint at that let mut show_overflow_indicator = false; state.count_rows = data.len(); state.count_columns = 0; state.data_height = data_height; if width > area.width { return; } for col in self.index_column..self.columns.len() { let need_split_line = state.count_columns > 0 && width < area.width; if need_split_line { width += render_split_line(buf, width, area.y, area.height, show_head, separator_s); } let mut column = create_column(data, col); let column_width = calculate_column_width(&column); let mut head = String::from(&self.columns[col]); let head_width = string_width(&head); let mut use_space = column_width as u16; if show_head { use_space = max(head_width as u16, use_space); } if use_space > 0 { let is_last = col + 1 == self.columns.len(); let space = area.width - width; let pad = padding_l + padding_r; let head = show_head.then_some(&mut head); let (w, ok, overflow) = truncate_column_width(space, 1, use_space, pad, is_last, &mut column, head); if overflow { show_overflow_indicator = true; } if w == 0 && !ok { break; } use_space = w; } if show_head { let head_style = head_style(&head, self.style_computer); if head_width > use_space as usize { truncate_str(&mut head, use_space as usize) } let head_iter = [(&head, head_style)].into_iter(); // we don't change width here cause the whole column have the same width; so we add it when we print data let mut w = width; w += render_space(buf, w, head_y, 1, padding_l); w += render_column(buf, w, head_y, use_space, head_iter); w += render_space(buf, w, head_y, 1, padding_r); let x = w - padding_r - use_space; state.layout.push(&head, x, head_y, use_space, 1); } let column_rows = column.iter().map(|(t, s)| (t, *s)); width += render_space(buf, width, data_y, data_height, padding_l); width += render_column(buf, width, data_y, use_space, column_rows); width += render_space(buf, width, data_y, data_height, padding_r); for (row, (text, _)) in column.iter().enumerate() { let x = width - padding_r - use_space; let y = data_y + row as u16; state.layout.push(text, x, y, use_space, 1); } state.count_columns += 1; if show_overflow_indicator { break; } } if show_overflow_indicator && show_head { width += render_space(buf, width, data_y, data_height, padding_l); width += render_overflow_column(buf, width, head_y, 1); width += render_space(buf, width, data_y, data_height, padding_r); } if width < area.width { width += render_split_line(buf, width, area.y, area.height, show_head, separator_s); } let rest = area.width.saturating_sub(width); if rest > 0 { render_space(buf, width, data_y, data_height, rest); if show_head { render_space(buf, width, head_y, 1, rest); } } } // header at the left; header is always 1 line fn render_table_vertical(self, area: Rect, buf: &mut Buffer, state: &mut TableWidgetState) { if area.width == 0 || area.height == 0 { return; } let padding_l = self.config.column_padding_left as u16; let padding_r = self.config.column_padding_right as u16; let show_index = self.config.show_index; let show_head = self.config.show_header; let separator_s = self.config.separator_style; let mut left_w = 0; if show_index { let area = Rect::new(area.x, area.y, area.width, area.height); left_w += render_index( buf, area, self.style_computer, self.index_row, padding_l, padding_r, ); left_w += render_vertical_line_with_split( buf, area.x + left_w, area.y, area.height, false, false, separator_s, ); } let mut columns = &self.columns[self.index_row..]; if columns.len() > area.height as usize { columns = &columns[..area.height as usize]; } if show_head { let columns_width = columns.iter().map(|s| string_width(s)).max().unwrap_or(0); let will_use_space = padding_l as usize + padding_r as usize + columns_width + left_w as usize; if will_use_space > area.width as usize { return; } let columns_iter = columns .iter() .map(|s| (s.clone(), head_style(s, self.style_computer))); if !show_index { let x = area.x + left_w; left_w += render_vertical_line_with_split( buf, x, area.y, area.height, false, false, separator_s, ); } let x = area.x + left_w; left_w += render_space(buf, x, area.y, 1, padding_l); let x = area.x + left_w; left_w += render_column(buf, x, area.y, columns_width as u16, columns_iter); let x = area.x + left_w; left_w += render_space(buf, x, area.y, 1, padding_r); let layout_x = left_w - padding_r - columns_width as u16; for (i, text) in columns.iter().enumerate() { state .layout .push(text, layout_x, area.y + i as u16, columns_width as u16, 1); } left_w += render_vertical_line_with_split( buf, area.x + left_w, area.y, area.height, false, false, separator_s, ); } // if there is more data than we can show, add an ellipsis to the column headers to hint at that let mut show_overflow_indicator = false; state.count_rows = columns.len(); state.count_columns = 0; // note: is there a time where we would have more then 1 column? // seems like not really; cause it's literally KV table, or am I wrong? for col in self.index_column..self.data.len() { let mut column = self.data[col][self.index_row..self.index_row + columns.len()].to_vec(); let column_width = calculate_column_width(&column); if column_width > u16::MAX as usize { break; } // see KV comment; this block might never got used let need_split_line = state.count_columns > 0 && left_w < area.width; if need_split_line { render_vertical_line(buf, area.x + left_w, area.y, area.height, separator_s); left_w += 1; } let column_width = column_width as u16; let available = area.width - left_w; let is_last = col + 1 == self.data.len(); let pad = padding_l + padding_r; let (column_width, ok, overflow) = truncate_column_width(available, 1, column_width, pad, is_last, &mut column, None); if overflow { show_overflow_indicator = true; } if column_width == 0 && !ok { break; } let head_rows = column.iter().map(|(t, s)| (t, *s)); let x = area.x + left_w; left_w += render_space(buf, x, area.y, area.height, padding_l); let x = area.x + left_w; left_w += render_column(buf, x, area.y, column_width, head_rows); let x = area.x + left_w; left_w += render_space(buf, x, area.y, area.height, padding_r); { for (row, (text, _)) in column.iter().enumerate() { let x = left_w - padding_r - column_width; let y = area.y + row as u16; state.layout.push(text, x, y, column_width, 1); } state.count_columns += 1; } if show_overflow_indicator { break; } } if show_overflow_indicator { let x = area.x + left_w; left_w += render_space(buf, x, area.y, area.height, padding_l); let x = area.x + left_w; left_w += render_overflow_column(buf, x, area.y, area.height); let x = area.x + left_w; left_w += render_space(buf, x, area.y, area.height, padding_r); } _ = left_w; } } #[allow(clippy::too_many_arguments)] fn truncate_column_width( space: u16, min: u16, w: u16, pad: u16, is_last: bool, column: &mut [(String, TextStyle)], head: Option<&mut String>, ) -> (u16, bool, bool) { let result = check_column_width(space, min, w, pad, is_last); let (width, overflow) = match result { Some(result) => result, None => return (w, true, false), }; if width == 0 { return (0, false, overflow); } truncate_list(column, width as usize); if let Some(head) = head { truncate_str(head, width as usize); } (width, false, overflow) } fn check_column_width( space: u16, min: u16, w: u16, pad: u16, is_last: bool, ) -> Option<(u16, bool)> { if !is_space_available(space, pad) { return Some((0, false)); } if is_last { if !is_space_available(space, w + pad) { return Some((space - pad, false)); } else { return None; } } if !is_space_available(space, min + pad) { return Some((0, false)); } if !is_space_available(space, w + pad + min + pad) { let left_space = space - (min + pad); if left_space > pad { let left = left_space - pad; return Some((left, true)); } else { return Some((0, true)); } } None } struct IndexColumn<'a> { style_computer: &'a StyleComputer<'a>, start: usize, } impl<'a> IndexColumn<'a> { fn new(style_computer: &'a StyleComputer, start: usize) -> Self { Self { style_computer, start, } } fn estimate_width(&self, height: u16) -> usize { let last_row = self.start + height as usize; last_row.to_string().len() } } impl Widget for IndexColumn<'_> { fn render(self, area: Rect, buf: &mut Buffer) { for row in 0..area.height { let i = row as usize + self.start; let text = i.to_string(); let style = nu_style_to_tui(self.style_computer.compute( "row_index", &Value::string(text.as_str(), nu_protocol::Span::unknown()), )); let p = Paragraph::new(text) .style(style) .alignment(ratatui::layout::Alignment::Right); let area = Rect::new(area.x, area.y + row, area.width, 1); p.render(area, buf); } } } fn render_header_borders(buf: &mut Buffer, area: Rect, span: u16, style: NuStyle) -> (u16, u16) { let borders = Borders::TOP | Borders::BOTTOM; let block = Block::default() .borders(borders) .border_style(nu_style_to_tui(style)); let height = span + 2; let area = Rect::new(area.x, area.y, area.width, height); block.render(area, buf); // y pos of header text and next line (height.saturating_sub(2), height) } fn render_index( buf: &mut Buffer, area: Rect, style_computer: &StyleComputer, start_index: usize, padding_left: u16, padding_right: u16, ) -> u16 { let mut width = render_space(buf, area.x, area.y, area.height, padding_left); let index = IndexColumn::new(style_computer, start_index); let w = index.estimate_width(area.height) as u16; let area = Rect::new(area.x + width, area.y, w, area.height); index.render(area, buf); width += w; width += render_space(buf, area.x + width, area.y, area.height, padding_right); width } fn render_split_line( buf: &mut Buffer, x: u16, y: u16, height: u16, has_head: bool, style: NuStyle, ) -> u16 { if has_head { render_vertical_split_line(buf, x, y, height, &[y], &[y + 2], &[], style); } else { render_vertical_split_line(buf, x, y, height, &[], &[], &[], style); } 1 } #[allow(clippy::too_many_arguments)] fn render_vertical_split_line( buf: &mut Buffer, x: u16, y: u16, height: u16, top_slit: &[u16], inner_slit: &[u16], bottom_slit: &[u16], style: NuStyle, ) -> u16 { render_vertical_line(buf, x, y, height, style); for &y in top_slit { render_top_connector(buf, x, y, style); } for &y in inner_slit { render_inner_connector(buf, x, y, style); } for &y in bottom_slit { render_bottom_connector(buf, x, y, style); } 1 } fn render_vertical_line_with_split( buf: &mut Buffer, x: u16, y: u16, height: u16, top_slit: bool, bottom_slit: bool, style: NuStyle, ) -> u16 { render_vertical_line(buf, x, y, height, style); if top_slit && y > 0 { render_top_connector(buf, x, y - 1, style); } if bottom_slit { render_bottom_connector(buf, x, y + height, style); } 1 } fn render_vertical_line(buf: &mut Buffer, x: u16, y: u16, height: u16, style: NuStyle) { let style = TextStyle { alignment: Alignment::Left, color_style: Some(style), }; repeat_vertical(buf, x, y, 1, height, '│', style); } fn render_space(buf: &mut Buffer, x: u16, y: u16, height: u16, padding: u16) -> u16 { repeat_vertical(buf, x, y, padding, height, ' ', TextStyle::default()); padding } fn create_column(data: &[Vec<NuText>], col: usize) -> Vec<NuText> { let mut column = vec![NuText::default(); data.len()]; for (row, values) in data.iter().enumerate() { if values.is_empty() { debug_assert!(false, "must never happen?"); continue; } let value = &values[col]; let text = value.0.replace('\n', " "); column[row] = (text, value.1); } column } /// Starting at cell [x, y]: paint `width` characters of `c` (left to right), move 1 row down, repeat /// Repeat this `height` times fn repeat_vertical( buf: &mut ratatui::buffer::Buffer, x: u16, y: u16, width: u16, height: u16, c: char, style: TextStyle, ) { let text = String::from(c); let style = text_style_to_tui_style(style); let span = Span::styled(&text, style); for row in 0..height { for col in 0..width { buf.set_span(x + col, y + row, &span, 1); } } } fn is_space_available(available: u16, got: u16) -> bool { match available.cmp(&got) { Ordering::Less => false, Ordering::Equal | Ordering::Greater => true, } } fn truncate_list(list: &mut [NuText], width: usize) { for (text, _) in list { truncate_str(text, width); } } /// Render a column with an ellipsis in the header to indicate that there is more data than can be displayed fn render_overflow_column(buf: &mut Buffer, x: u16, y: u16, height: u16) -> u16 { let style = TextStyle { alignment: Alignment::Left, color_style: None, }; repeat_vertical(buf, x, y, 1, height, '…', style); 1 } fn render_top_connector(buf: &mut Buffer, x: u16, y: u16, style: NuStyle) { let style = nu_style_to_tui(style); let span = Span::styled("┬", style); buf.set_span(x, y, &span, 1); } fn render_bottom_connector(buf: &mut Buffer, x: u16, y: u16, style: NuStyle) { let style = nu_style_to_tui(style); let span = Span::styled("┴", style); buf.set_span(x, y, &span, 1); } fn render_inner_connector(buf: &mut Buffer, x: u16, y: u16, style: NuStyle) { let style = nu_style_to_tui(style); let span = Span::styled("┼", style); buf.set_span(x, y, &span, 1); } fn calculate_column_width(column: &[NuText]) -> usize { column .iter() .map(|(text, _)| text) .map(|text| string_width(text)) .max() .unwrap_or(0) } fn render_column<T, S>( buf: &mut ratatui::buffer::Buffer, x: u16, y: u16, available_width: u16, rows: impl Iterator<Item = (T, S)>, ) -> u16 where T: AsRef<str>, S: Into<TextStyle>, { for (row, (text, style)) in rows.enumerate() { let style = text_style_to_tui_style(style.into()); let span = Span::styled(text.as_ref(), style); buf.set_span(x, y + row as u16, &span, available_width); } available_width } fn head_style(head: &str, style_computer: &StyleComputer) -> TextStyle { let style = style_computer.compute("header", &Value::string(head, nu_protocol::Span::unknown())); TextStyle::with_style(Alignment::Center, style) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/views/record/mod.rs
crates/nu-explore/src/explore/views/record/mod.rs
mod table_widget; use self::table_widget::{TableWidget, TableWidgetState}; use super::super::{ config::ExploreConfig, nu_common::{NuSpan, NuText, collect_input, lscolorize}, pager::{ Frame, Transition, ViewInfo, report::{Report, Severity}, }, }; use super::{ ElementInfo, Layout, View, ViewConfig, cursor::{CursorMoveHandler, Position, WindowCursor2D}, util::{make_styled_string, nu_style_to_tui}, }; use anyhow::Result; use crossterm::event::{KeyCode, KeyEvent}; use nu_color_config::StyleComputer; use nu_protocol::{ Config, Value, engine::{EngineState, Stack}, }; use ratatui::{layout::Rect, widgets::Block}; pub use self::table_widget::Orientation; #[derive(Debug, Clone)] pub struct RecordView { layer_stack: Vec<RecordLayer>, mode: UIMode, orientation: Orientation, cfg: ExploreConfig, auto_tail: bool, // Track if tail mode is active for auto-scroll previous_row_count: usize, page_size: usize, } impl RecordView { pub fn new(columns: Vec<String>, records: Vec<Vec<Value>>, cfg: ExploreConfig) -> Self { let row_count = records.len(); Self { layer_stack: vec![RecordLayer::new(columns, records)], mode: UIMode::View, orientation: Orientation::Top, cfg, auto_tail: true, // Enable auto-tail by default previous_row_count: row_count, page_size: 0, } } pub fn tail(&mut self, width: u16, height: u16) { let page_size = estimate_page_size(Rect::new(0, 0, width, height), self.cfg.table.show_header); tail_data(self, page_size as usize); self.auto_tail = true; // Enable auto-tail mode } pub fn transpose(&mut self) { let layer = self.get_top_layer_mut(); transpose_table(layer); layer.reset_cursor(); } pub fn get_top_layer(&self) -> &RecordLayer { self.layer_stack .last() .expect("we guarantee that 1 entry is always in a list") } pub fn get_top_layer_mut(&mut self) -> &mut RecordLayer { self.layer_stack .last_mut() .expect("we guarantee that 1 entry is always in a list") } pub fn set_top_layer_orientation(&mut self, orientation: Orientation) { let layer = self.get_top_layer_mut(); layer.orientation = orientation; layer.reset_cursor(); } /// Get the current position of the cursor in the table as a whole pub fn get_cursor_position(&self) -> Position { let layer = self.get_top_layer(); layer.cursor.position() } /// Get the current position of the cursor in the window being shown pub fn get_cursor_position_in_window(&self) -> Position { let layer = self.get_top_layer(); layer.cursor.window_relative_position() } /// Get the origin of the window being shown. (0,0), top left corner. pub fn get_window_origin(&self) -> Position { let layer = self.get_top_layer(); layer.cursor.window_origin() } pub fn set_cursor_mode(&mut self) { self.mode = UIMode::Cursor; } pub fn set_view_mode(&mut self) { self.mode = UIMode::View; } pub fn get_current_value(&self) -> &Value { let Position { row, column } = self.get_cursor_position(); let layer = self.get_top_layer(); let (row, column) = match layer.orientation { Orientation::Top => (row, column), Orientation::Left => (column, row), }; // These should never happen as long as the cursor is working correctly assert!(row < layer.record_values.len(), "row out of bounds"); assert!(column < layer.column_names.len(), "column out of bounds"); &layer.record_values[row][column] } fn create_table_widget<'a>(&'a mut self, cfg: ViewConfig<'a>) -> TableWidget<'a> { let style = self.cfg.table; let style_computer = cfg.style_computer; let Position { row, column } = self.get_window_origin(); let layer = self.get_top_layer_mut(); if layer.record_text.is_none() { let mut data = convert_records_to_string(&layer.record_values, cfg.nu_config, cfg.style_computer); lscolorize(&layer.column_names, &mut data, cfg.cwd, cfg.lscolors); layer.record_text = Some(data); } let headers = &layer.column_names; let data = layer.record_text.as_ref().expect("always ok"); TableWidget::new( headers, data, style_computer, row, column, style, layer.orientation, ) } fn update_cursors(&mut self, rows: usize, columns: usize) { match self.get_top_layer().orientation { Orientation::Top => { let _ = self .get_top_layer_mut() .cursor .set_window_size(rows, columns); } Orientation::Left => { let _ = self .get_top_layer_mut() .cursor .set_window_size(rows, columns); } } } fn create_records_report(&self) -> Report { let layer = self.get_top_layer(); let covered_percent = report_row_position(layer.cursor); let cursor = report_cursor_position(self.mode, layer.cursor); let message = layer.name.clone().unwrap_or_default(); // note: maybe came up with a better short names? E/V/N? let mode = match self.mode { UIMode::Cursor => String::from("EDIT"), UIMode::View => String::from("VIEW"), }; Report::new(message, Severity::Info, mode, cursor, covered_percent) } } impl View for RecordView { fn draw(&mut self, f: &mut Frame, area: Rect, cfg: ViewConfig<'_>, layout: &mut Layout) { let mut table_layout = TableWidgetState::default(); let table = self.create_table_widget(cfg); f.render_stateful_widget(table, area, &mut table_layout); *layout = table_layout.layout; self.update_cursors(table_layout.count_rows, table_layout.count_columns); // Update page_size self.page_size = estimate_page_size(area, self.cfg.table.show_header) as usize; // Check for new rows and handle auto-tail let current_row_count = self.get_top_layer().record_values.len(); if current_row_count > self.previous_row_count { // Invalidate record_text to force redraw self.get_top_layer_mut().record_text = None; // If auto_tail, scroll to bottom if self.auto_tail { let page_size = self.page_size; if current_row_count > page_size { self.get_top_layer_mut() .cursor .set_window_start_position(current_row_count - page_size, 0); } } } self.previous_row_count = current_row_count; if self.mode == UIMode::Cursor { let Position { row, column } = self.get_cursor_position_in_window(); let info = get_element_info( layout, row, column, table_layout.count_rows, self.get_top_layer().orientation, self.cfg.table.show_header, ); if let Some(info) = info { highlight_selected_cell(f, info.clone(), &self.cfg); } } } fn handle_input( &mut self, _engine_state: &EngineState, _stack: &mut Stack, _layout: &Layout, info: &mut ViewInfo, key: KeyEvent, ) -> Transition { if key.code == KeyCode::PageUp { let page_size = self.page_size; let current_row = self.get_top_layer().cursor.window_origin().row; let new_row = current_row.saturating_sub(page_size); let layer = self.get_top_layer_mut(); layer .cursor .set_window_start_position(new_row, layer.cursor.window_origin().column); let report = self.create_records_report(); info.status = Some(report); return Transition::Ok; } if key.code == KeyCode::PageDown { let page_size = self.page_size; let current_row = self.get_top_layer().cursor.window_origin().row; let row_count = self.get_top_layer().record_values.len(); let max_row = row_count.saturating_sub(page_size); let new_row = (current_row + page_size).min(max_row); let layer = self.get_top_layer_mut(); layer .cursor .set_window_start_position(new_row, layer.cursor.window_origin().column); let report = self.create_records_report(); info.status = Some(report); return Transition::Ok; } match self.handle_input_key(&key) { Ok((transition, ..)) => { if matches!(&transition, Transition::Ok | Transition::Cmd { .. }) { let report = self.create_records_report(); info.status = Some(report); } transition } Err(e) => { log::error!("Error handling input in RecordView: {e}"); let report = Report::message(e.to_string(), Severity::Err); info.status = Some(report); Transition::None } } } fn update(&mut self, _info: &mut ViewInfo) -> bool { false } fn exit(&mut self) -> Option<Value> { None } } fn get_element_info( layout: &mut Layout, row: usize, column: usize, count_rows: usize, orientation: Orientation, with_head: bool, ) -> Option<&ElementInfo> { let with_head = with_head as usize; let index = match orientation { Orientation::Top => column * (count_rows + with_head) + row + 1, Orientation::Left => (column + with_head) * count_rows + row, }; layout.data.get(index) } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] enum UIMode { Cursor, View, } #[derive(Debug, Clone)] pub struct RecordLayer { pub column_names: Vec<String>, // These are the raw records in the current layer. The sole reason we keep this around is so we can return the original value // if it's being peeked. Otherwise we could accept an iterator over it. // or if it could be Cloneable we could do that anyway; // cause it would keep memory footprint lower while keep everything working // (yee would make return O(n); we would need to traverse iterator once again; but maybe worth it) pub record_values: Vec<Vec<Value>>, // This is the text representation of the record values (the actual text that will be displayed to users). // It's an Option because we need configuration to set it and we (currently) don't have access to configuration when things are created. pub record_text: Option<Vec<Vec<NuText>>>, orientation: Orientation, name: Option<String>, was_transposed: bool, pub cursor: WindowCursor2D, } impl RecordLayer { fn new(columns: Vec<String>, records: Vec<Vec<Value>>) -> Self { // TODO: refactor so this is fallible and returns a Result instead of panicking let cursor = WindowCursor2D::new(records.len(), columns.len()).expect("Failed to create cursor"); let column_names = columns.iter().map(|s| strip_string(s)).collect(); Self { column_names, record_values: records, record_text: None, cursor, orientation: Orientation::Top, name: None, was_transposed: false, } } fn set_name(&mut self, name: impl Into<String>) { self.name = Some(name.into()); } fn count_rows(&self) -> usize { match self.orientation { Orientation::Top => self.record_values.len(), Orientation::Left => self.column_names.len(), } } fn count_columns(&self) -> usize { match self.orientation { Orientation::Top => self.column_names.len(), Orientation::Left => self.record_values.len(), } } fn get_column_header(&self) -> Option<String> { let col = self.cursor.column(); self.column_names.get(col).map(|header| header.to_string()) } fn reset_cursor(&mut self) { // TODO: refactor so this is fallible and returns a Result instead of panicking self.cursor = WindowCursor2D::new(self.count_rows(), self.count_columns()) .expect("Failed to create cursor"); } } impl CursorMoveHandler for RecordView { fn get_cursor(&mut self) -> &mut WindowCursor2D { &mut self.get_top_layer_mut().cursor } fn handle_enter(&mut self) -> Result<Transition> { match self.mode { UIMode::View => self.set_cursor_mode(), UIMode::Cursor => { let value = self.get_current_value(); // ...but it only makes sense to drill down into a few types of values if !matches!( value, Value::Record { .. } | Value::List { .. } | Value::Custom { .. } ) { return Ok(Transition::None); } let is_record = matches!(value, Value::Record { .. }); let next_layer = create_layer(value.clone())?; push_layer(self, next_layer); if is_record { self.set_top_layer_orientation(Orientation::Left); } else { self.set_top_layer_orientation(self.orientation); } } } Ok(Transition::Ok) } fn handle_esc(&mut self) -> Transition { match self.mode { UIMode::View => { if self.layer_stack.len() > 1 { self.layer_stack.pop(); self.mode = UIMode::Cursor; } else { return Transition::Exit; } } UIMode::Cursor => self.set_view_mode(), } Transition::Ok } fn handle_expand(&mut self) -> Transition { Transition::Cmd(String::from("expand")) } fn handle_transpose(&mut self) -> Transition { match self.mode { UIMode::View => { self.transpose(); Transition::Ok } _ => Transition::None, } } // for these, copy standard CursorMoveHandler for UIMode::View, but use special handling for UIMode::Cursor // NOTE: https://stackoverflow.com/a/31462293/2016290 says there's plans for Rust to allow calling super functions, // but not yet, and since they're all one line, it seems simpler to copy than make a lot of helper functions fn handle_left(&mut self) { match self.mode { UIMode::View => self.get_top_layer_mut().cursor.prev_column_i(), _ => self.get_top_layer_mut().cursor.prev_column(), } } fn handle_right(&mut self) { match self.mode { UIMode::View => self.get_top_layer_mut().cursor.next_column_i(), _ => self.get_top_layer_mut().cursor.next_column(), } } fn handle_up(&mut self) { match self.mode { UIMode::View => self.get_top_layer_mut().cursor.prev_row_i(), _ => self.get_top_layer_mut().cursor.prev_row(), } } fn handle_down(&mut self) { match self.mode { UIMode::View => self.get_top_layer_mut().cursor.next_row_i(), _ => self.get_top_layer_mut().cursor.next_row(), } } } fn create_layer(value: Value) -> Result<RecordLayer> { let (columns, values) = collect_input(value)?; if columns.is_empty() { return Err(anyhow::anyhow!("Nothing to explore in empty collections!")); } Ok(RecordLayer::new(columns, values)) } fn push_layer(view: &mut RecordView, mut next_layer: RecordLayer) { let layer = view.get_top_layer(); let header = layer.get_column_header(); if let Some(header) = header { next_layer.set_name(header); } view.layer_stack.push(next_layer); } fn estimate_page_size(area: Rect, show_head: bool) -> u16 { let mut available_height = area.height; available_height -= 3; // status_bar if show_head { available_height -= 3; // head } available_height } /// scroll to the end of the data fn tail_data(state: &mut RecordView, page_size: usize) { let layer = state.get_top_layer_mut(); let count_rows = layer.record_values.len(); if count_rows > page_size { layer .cursor .set_window_start_position(count_rows - page_size, 0); } } fn convert_records_to_string( records: &[Vec<Value>], cfg: &Config, style_computer: &StyleComputer, ) -> Vec<Vec<NuText>> { records .iter() .map(|row| { row.iter() .map(|value| { let text = value.clone().to_abbreviated_string(cfg); let text = strip_string(&text); let float_precision = cfg.float_precision as usize; make_styled_string(style_computer, text, Some(value), float_precision) }) .collect::<Vec<_>>() }) .collect::<Vec<_>>() } fn highlight_selected_cell(f: &mut Frame, info: ElementInfo, cfg: &ExploreConfig) { let cell_style = cfg.selected_cell; let highlight_block = Block::default().style(nu_style_to_tui(cell_style)); let area = Rect::new(info.area.x, info.area.y, info.area.width, 1); f.render_widget(highlight_block.clone(), area) } fn report_cursor_position(mode: UIMode, cursor: WindowCursor2D) -> String { if mode == UIMode::Cursor { let Position { row, column } = cursor.position(); format!("{row},{column}") } else { let Position { row, column } = cursor.window_origin(); format!("{row},{column}") } } fn report_row_position(cursor: WindowCursor2D) -> String { if cursor.window_origin().row == 0 { String::from("Top") } else { let percent_rows = get_percentage(cursor.row(), cursor.row_limit()); match percent_rows { 100 => String::from("All"), value => format!("{value}%"), } } } fn get_percentage(value: usize, max: usize) -> usize { debug_assert!(value <= max, "{value:?} {max:?}"); ((value as f32 / max as f32) * 100.0).floor() as usize } fn transpose_table(layer: &mut RecordLayer) { if layer.was_transposed { transpose_from(layer); } else { transpose_to(layer); } layer.was_transposed = !layer.was_transposed; } fn transpose_from(layer: &mut RecordLayer) { let count_rows = layer.record_values.len(); let count_columns = layer.column_names.len(); if let Some(data) = &mut layer.record_text { pop_first_column(data); *data = _transpose_table(data, count_rows, count_columns - 1); } let headers = pop_first_column(&mut layer.record_values); let headers = headers .into_iter() .map(|value| match value { Value::String { val, .. } => val, _ => unreachable!("must never happen"), }) .collect(); let data = _transpose_table(&layer.record_values, count_rows, count_columns - 1); layer.record_values = data; layer.column_names = headers; } fn transpose_to(layer: &mut RecordLayer) { let count_rows = layer.record_values.len(); let count_columns = layer.column_names.len(); if let Some(data) = &mut layer.record_text { *data = _transpose_table(data, count_rows, count_columns); for (column, column_name) in layer.column_names.iter().enumerate() { let value = (column_name.to_owned(), Default::default()); data[column].insert(0, value); } } let mut data = _transpose_table(&layer.record_values, count_rows, count_columns); for (column, column_name) in layer.column_names.iter().enumerate() { let value = Value::string(column_name, NuSpan::unknown()); data[column].insert(0, value); } layer.record_values = data; layer.column_names = (1..count_rows + 1 + 1).map(|i| i.to_string()).collect(); } fn pop_first_column<T>(values: &mut [Vec<T>]) -> Vec<T> where T: Default + Clone, { let mut data = vec![T::default(); values.len()]; for (row, values) in values.iter_mut().enumerate() { data[row] = values.remove(0); } data } fn _transpose_table<T>(values: &[Vec<T>], count_rows: usize, count_columns: usize) -> Vec<Vec<T>> where T: Clone + Default, { let mut data = vec![vec![T::default(); count_rows]; count_columns]; for (row, values) in values.iter().enumerate() { for (column, value) in values.iter().enumerate() { data[column][row].clone_from(value); } } data } fn strip_string(text: &str) -> String { String::from_utf8(strip_ansi_escapes::strip(text)) .map_err(|_| ()) .unwrap_or_else(|_| text.to_owned()) } #[cfg(test)] mod tests { use super::*; use nu_protocol::{Value, span::Span}; // Helper to create a simple test Value::Record fn create_test_record() -> Value { let mut record = nu_protocol::Record::new(); record.insert( "name".to_string(), Value::string("sample", Span::test_data()), ); record.insert("value".to_string(), Value::int(42, Span::test_data())); Value::record(record, Span::test_data()) } // Helper to create a simple test Value::List fn create_test_list() -> Value { let items = vec![ Value::string("item1", Span::test_data()), Value::string("item2", Span::test_data()), ]; Value::list(items, Span::test_data()) } #[test] fn test_create_layer_empty_collection() { // Test with empty record let empty_record = Value::record(nu_protocol::Record::new(), Span::test_data()); let result = create_layer(empty_record); assert!(result.is_err()); assert_eq!( result.unwrap_err().to_string(), "Nothing to explore in empty collections!" ); // Test with empty list let empty_list = Value::list(vec![], Span::test_data()); let result = create_layer(empty_list); assert!(result.is_err()); assert_eq!( result.unwrap_err().to_string(), "Nothing to explore in empty collections!" ); } #[test] fn test_create_layer_valid_record() { let record = create_test_record(); let result = create_layer(record); assert!(result.is_ok()); let layer = result.unwrap(); assert_eq!(layer.column_names, vec!["name", "value"]); assert_eq!(layer.record_values.len(), 1); assert_eq!(layer.record_values[0].len(), 2); } #[test] fn test_create_layer_valid_list() { let list = create_test_list(); let result = create_layer(list); assert!(result.is_ok()); let layer = result.unwrap(); assert_eq!(layer.column_names, vec![""]); assert_eq!(layer.record_values.len(), 2); assert_eq!(layer.record_values[0].len(), 1); } #[test] fn test_transpose_table() { // Create a simple 2x3 table let mut layer = RecordLayer::new( vec!["col1".to_string(), "col2".to_string(), "col3".to_string()], vec![ vec![ Value::string("r1c1", Span::test_data()), Value::string("r1c2", Span::test_data()), Value::string("r1c3", Span::test_data()), ], vec![ Value::string("r2c1", Span::test_data()), Value::string("r2c2", Span::test_data()), Value::string("r2c3", Span::test_data()), ], ], ); // Before transpose assert_eq!(layer.count_rows(), 2); assert_eq!(layer.count_columns(), 3); assert!(!layer.was_transposed); // After transpose transpose_table(&mut layer); assert_eq!(layer.count_rows(), 3); assert_eq!(layer.count_columns(), 3); // Now includes header row assert!(layer.was_transposed); // After transpose back transpose_table(&mut layer); assert_eq!(layer.count_rows(), 2); assert_eq!(layer.count_columns(), 3); assert!(!layer.was_transposed); } #[test] fn test_estimate_page_size() { // Test with header let area = Rect::new(0, 0, 80, 24); assert_eq!(estimate_page_size(area, true), 18); // 24 - 3 (status bar) - 3 (header) = 18 // Test without header assert_eq!(estimate_page_size(area, false), 21); // 24 - 3 (status bar) = 21 } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/views/binary/binary_widget.rs
crates/nu-explore/src/explore/views/binary/binary_widget.rs
use nu_color_config::TextStyle; use nu_pretty_hex::categorize_byte; use ratatui::{ buffer::Buffer, layout::Rect, text::Span, widgets::{Paragraph, Widget}, }; use super::super::super::nu_common::NuStyle; use super::super::util::{nu_style_to_tui, text_style_to_tui_style}; /// Padding between segments in the hex view const SEGMENT_PADDING: u16 = 1; #[derive(Debug, Clone)] pub struct BinaryWidget<'a> { data: &'a [u8], opts: BinarySettings, style: BinaryStyle, row_offset: usize, } impl<'a> BinaryWidget<'a> { pub fn new(data: &'a [u8], opts: BinarySettings, style: BinaryStyle) -> Self { Self { data, opts, style, row_offset: 0, } } pub fn count_lines(&self) -> usize { self.data.len() / self.count_elements() } pub fn count_elements(&self) -> usize { self.opts.count_segments * self.opts.segment_size } pub fn set_row_offset(&mut self, offset: usize) { self.row_offset = offset; } } #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] pub struct BinarySettings { segment_size: usize, count_segments: usize, } impl BinarySettings { pub fn new(segment_size: usize, count_segments: usize) -> Self { Self { segment_size, count_segments, } } } #[derive(Debug, Default, Clone)] pub struct BinaryStyle { color_index: Option<NuStyle>, column_padding_left: u16, column_padding_right: u16, } impl BinaryStyle { pub fn new( color_index: Option<NuStyle>, column_padding_left: u16, column_padding_right: u16, ) -> Self { Self { color_index, column_padding_left, column_padding_right, } } } impl Widget for BinaryWidget<'_> { fn render(self, area: Rect, buf: &mut Buffer) { let min_width = get_widget_width(&self); if (area.width as usize) < min_width { return; } render_hexdump(area, buf, self); } } // todo: indent color fn render_hexdump(area: Rect, buf: &mut Buffer, w: BinaryWidget) { const MIN_INDEX_SIZE: usize = 8; let index_width = get_max_index_size(&w).max(MIN_INDEX_SIZE) as u16; // safe as it's checked before hand that we have enough space let mut last_line = None; for line in 0..area.height { let data_line_length = w.opts.count_segments * w.opts.segment_size; let start_index = line as usize * data_line_length; let address = w.row_offset + start_index; if start_index > w.data.len() { last_line = Some(line); break; } let mut x = 0; let y = line; let line = &w.data[start_index..]; // index column x += render_space(buf, x, y, 1, w.style.column_padding_left); x += render_hex_usize(buf, x, y, address, index_width, get_index_style(&w)); x += render_space(buf, x, y, 1, w.style.column_padding_right); x += render_vertical_split(buf, x, y); // data/hex column x += render_space(buf, x, y, 1, w.style.column_padding_left); x += render_data_line(buf, x, y, line, &w); x += render_space(buf, x, y, 1, w.style.column_padding_right); x += render_vertical_split(buf, x, y); // ASCII column x += render_space(buf, x, y, 1, w.style.column_padding_left); x += render_ascii_line(buf, x, y, line, &w); render_space(buf, x, y, 1, w.style.column_padding_right); } let data_line_size = (w.opts.count_segments * (w.opts.segment_size * 2) + w.opts.count_segments.saturating_sub(1)) as u16; let ascii_line_size = (w.opts.count_segments * w.opts.segment_size) as u16; if let Some(last_line) = last_line { for line in last_line..area.height { let data_line_length = w.opts.count_segments * w.opts.segment_size; let start_index = line as usize * data_line_length; let address = w.row_offset + start_index; let mut x = 0; let y = line; // index column x += render_space(buf, x, y, 1, w.style.column_padding_left); x += render_hex_usize(buf, x, y, address, index_width, get_index_style(&w)); x += render_space(buf, x, y, 1, w.style.column_padding_right); x += render_vertical_split(buf, x, y); // data/hex column x += render_space(buf, x, y, 1, w.style.column_padding_left); x += render_space(buf, x, y, 1, data_line_size); x += render_space(buf, x, y, 1, w.style.column_padding_right); x += render_vertical_split(buf, x, y); // ASCII column x += render_space(buf, x, y, 1, w.style.column_padding_left); x += render_space(buf, x, y, 1, ascii_line_size); render_space(buf, x, y, 1, w.style.column_padding_right); } } } fn render_data_line(buf: &mut Buffer, x: u16, y: u16, line: &[u8], w: &BinaryWidget) -> u16 { let mut size = 0; let mut count = 0; let count_max = w.opts.count_segments; let segment_size = w.opts.segment_size; size += render_segment(buf, x, y, line, w); count += 1; while count != count_max && count * segment_size < line.len() { let data = &line[count * segment_size..]; size += render_space(buf, x + size, y, 1, SEGMENT_PADDING); size += render_segment(buf, x + size, y, data, w); count += 1; } while count != count_max { size += render_space(buf, x + size, y, 1, SEGMENT_PADDING); size += render_space(buf, x + size, y, 1, w.opts.segment_size as u16 * 2); count += 1; } size } fn render_segment(buf: &mut Buffer, x: u16, y: u16, line: &[u8], w: &BinaryWidget) -> u16 { let mut count = w.opts.segment_size; let mut size = 0; for &n in line { if count == 0 { break; } let (_, style) = get_segment_char(w, n); size += render_hex_u8(buf, x + size, y, n, style); count -= 1; } if count > 0 { size += render_space(buf, x + size, y, 1, (count * 2) as u16); } size } fn render_ascii_line(buf: &mut Buffer, x: u16, y: u16, line: &[u8], w: &BinaryWidget) -> u16 { let mut size = 0; let mut count = 0; let length = w.count_elements(); for &n in line { if count == length { break; } let (c, style) = get_ascii_char(w, n); size += render_ascii_char(buf, x + size, y, c, style); count += 1; } if count < length { size += render_space(buf, x + size, y, 1, (length - count) as u16); } size } fn render_ascii_char(buf: &mut Buffer, x: u16, y: u16, n: char, style: Option<NuStyle>) -> u16 { let text = n.to_string(); let mut p = Paragraph::new(text); if let Some(style) = style { let style = nu_style_to_tui(style); p = p.style(style); } let area = Rect::new(x, y, 1, 1); p.render(area, buf); 1 } fn render_hex_u8(buf: &mut Buffer, x: u16, y: u16, n: u8, style: Option<NuStyle>) -> u16 { render_hex_usize(buf, x, y, n as usize, 2, style) } fn render_hex_usize( buf: &mut Buffer, x: u16, y: u16, n: usize, width: u16, style: Option<NuStyle>, ) -> u16 { let text = usize_to_hex(n, width as usize); let mut p = Paragraph::new(text); if let Some(style) = style { let style = nu_style_to_tui(style); p = p.style(style); } let area = Rect::new(x, y, width, 1); p.render(area, buf); width } fn get_ascii_char(_w: &BinaryWidget, n: u8) -> (char, Option<NuStyle>) { let (style, c) = categorize_byte(&n); let c = c.unwrap_or(n as char); let style = if style.is_plain() { None } else { Some(style) }; (c, style) } fn get_segment_char(_w: &BinaryWidget, n: u8) -> (char, Option<NuStyle>) { let (style, c) = categorize_byte(&n); let c = c.unwrap_or(n as char); let style = if style.is_plain() { None } else { Some(style) }; (c, style) } fn get_index_style(w: &BinaryWidget) -> Option<NuStyle> { w.style.color_index } /// Render blank characters starting at the given position, going right `width` characters and down `height` characters. /// Returns `width` for convenience. fn render_space(buf: &mut Buffer, x: u16, y: u16, height: u16, width: u16) -> u16 { repeat_vertical(buf, x, y, width, height, ' ', TextStyle::default()); width } /// Render a vertical split (│) at the given position. Returns the width of the split (always 1) for convenience. fn render_vertical_split(buf: &mut Buffer, x: u16, y: u16) -> u16 { repeat_vertical(buf, x, y, 1, 1, '│', TextStyle::default()); 1 } fn repeat_vertical( buf: &mut Buffer, x_offset: u16, y_offset: u16, width: u16, height: u16, c: char, style: TextStyle, ) { let text = std::iter::repeat_n(c, width as usize).collect::<String>(); let style = text_style_to_tui_style(style); let span = Span::styled(text, style); for row in 0..height { buf.set_span(x_offset, y_offset + row, &span, width); } } fn get_max_index_size(w: &BinaryWidget) -> usize { let line_size = w.opts.count_segments * (w.opts.segment_size * 2); let count_lines = w.data.len() / line_size; let max_index = w.row_offset + count_lines * line_size; usize_to_hex(max_index, 0).len() } fn get_widget_width(w: &BinaryWidget) -> usize { const MIN_INDEX_SIZE: usize = 8; let line_size = w.opts.count_segments * (w.opts.segment_size * 2); let count_lines = w.data.len() / line_size; let max_index = w.row_offset + count_lines * line_size; let index_size = usize_to_hex(max_index, 0).len(); let index_size = index_size.max(MIN_INDEX_SIZE); let data_split_size = w.opts.count_segments.saturating_sub(1) * (SEGMENT_PADDING as usize); let data_size = line_size + data_split_size; let ascii_size = w.opts.count_segments * w.opts.segment_size; #[allow(clippy::identity_op)] let min_width = 0 + w.style.column_padding_left as usize + index_size + w.style.column_padding_right as usize + 1 // split + w.style.column_padding_left as usize + data_size + w.style.column_padding_right as usize + 1 //split + w.style.column_padding_left as usize + ascii_size + w.style.column_padding_right as usize; min_width } fn usize_to_hex(n: usize, width: usize) -> String { if width == 0 { format!("{n:x}") } else { format!("{n:0>width$x}") } } #[cfg(test)] mod tests { use super::usize_to_hex; #[test] fn test_to_hex() { assert_eq!(usize_to_hex(1, 2), "01"); assert_eq!(usize_to_hex(16, 2), "10"); assert_eq!(usize_to_hex(29, 2), "1d"); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/views/binary/mod.rs
crates/nu-explore/src/explore/views/binary/mod.rs
// todo: 3 cursor modes one for section mod binary_widget; use crossterm::event::KeyEvent; use nu_protocol::{ Value, engine::{EngineState, Stack}, }; use ratatui::layout::Rect; use super::super::{ config::ExploreConfig, nu_common::NuText, pager::{ Frame, Transition, ViewInfo, report::{Report, Severity}, }, }; use super::cursor::Position; use self::binary_widget::{BinarySettings, BinaryStyle, BinaryWidget}; use super::{Layout, View, ViewConfig, cursor::CursorMoveHandler, cursor::WindowCursor2D}; /// An interactive view that displays binary data in a hex dump format. /// Not finished; many aspects are still WIP. #[derive(Debug, Clone)] pub struct BinaryView { data: Vec<u8>, // HACK: we are only using the vertical dimension of the cursor, should we use a plain old WindowCursor? cursor: WindowCursor2D, settings: Settings, } #[derive(Debug, Default, Clone)] struct Settings { opts: BinarySettings, style: BinaryStyle, } impl BinaryView { pub fn new(data: Vec<u8>, cfg: &ExploreConfig) -> Self { let settings = settings_from_config(cfg); // There's gotta be a nicer way of doing this than creating a widget just to count lines let count_rows = BinaryWidget::new(&data, settings.opts, Default::default()).count_lines(); Self { data, cursor: WindowCursor2D::new(count_rows, 1).expect("Failed to create XYCursor"), settings, } } } impl View for BinaryView { fn draw(&mut self, f: &mut Frame, area: Rect, _cfg: ViewConfig<'_>, _layout: &mut Layout) { let widget = create_binary_widget(self); f.render_widget(widget, area); } fn handle_input( &mut self, _: &EngineState, _: &mut Stack, _: &Layout, info: &mut ViewInfo, key: KeyEvent, ) -> Transition { // currently only handle_enter() in crates/nu-explore/src/views/record/mod.rs raises an Err() if let Ok((Transition::Ok, ..)) = self.handle_input_key(&key) { let report = create_report(self.cursor); info.status = Some(report); } Transition::None } fn collect_data(&self) -> Vec<NuText> { // todo: impl to allow search vec![] } fn show_data(&mut self, _pos: usize) -> bool { // todo: impl to allow search false } fn exit(&mut self) -> Option<Value> { // todo: impl Cursor + peek of a value None } } impl CursorMoveHandler for BinaryView { fn get_cursor(&mut self) -> &mut WindowCursor2D { &mut self.cursor } } fn create_binary_widget(v: &BinaryView) -> BinaryWidget<'_> { let start_line = v.cursor.window_origin().row; let count_elements = BinaryWidget::new(&[], v.settings.opts, Default::default()).count_elements(); let index = start_line * count_elements; let data = &v.data[index..]; let mut w = BinaryWidget::new(data, v.settings.opts, v.settings.style.clone()); w.set_row_offset(index); w } fn settings_from_config(config: &ExploreConfig) -> Settings { // Most of this is hardcoded for now, add it to the config later if needed Settings { opts: BinarySettings::new(2, 8), style: BinaryStyle::new( None, config.table.column_padding_left as u16, config.table.column_padding_right as u16, ), } } fn create_report(cursor: WindowCursor2D) -> Report { let covered_percent = report_row_position(cursor); let cursor = report_cursor_position(cursor); let mode = report_mode_name(); let msg = String::new(); Report::new(msg, Severity::Info, mode, cursor, covered_percent) } fn report_mode_name() -> String { String::from("VIEW") } fn report_row_position(cursor: WindowCursor2D) -> String { if cursor.window_origin().row == 0 { return String::from("Top"); } // todo: there's some bug in XYCursor; when we hit PgDOWN/UP and general move it exceeds the limit // not sure when it was introduced and if present in original view. // but it just requires a refactoring as these method names are just ..... not perfect. let row = cursor.row().min(cursor.row_limit()); let count_rows = cursor.row_limit(); let percent_rows = get_percentage(row, count_rows); match percent_rows { 100 => String::from("All"), value => format!("{value}%"), } } fn report_cursor_position(cursor: WindowCursor2D) -> String { let Position { row, column } = cursor.window_origin(); format!("{row},{column}") } fn get_percentage(value: usize, max: usize) -> usize { debug_assert!(value <= max, "{value:?} {max:?}"); ((value as f32 / max as f32) * 100.0).floor() as usize }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/pager/report.rs
crates/nu-explore/src/explore/pager/report.rs
#[derive(Debug, Clone)] pub struct Report { pub message: String, pub level: Severity, pub context1: String, pub context2: String, pub context3: String, } impl Report { pub fn new(message: String, level: Severity, ctx1: String, ctx2: String, ctx3: String) -> Self { Self { message, level, context1: ctx1, context2: ctx2, context3: ctx3, } } pub fn message(message: impl Into<String>, level: Severity) -> Self { Self::new( message.into(), level, String::new(), String::new(), String::new(), ) } pub fn info(message: impl Into<String>) -> Self { Self::message(message.into(), Severity::Info) } pub fn success(message: impl Into<String>) -> Self { Self::message(message.into(), Severity::Success) } pub fn error(message: impl Into<String>) -> Self { Self::message(message.into(), Severity::Err) } } impl Default for Report { fn default() -> Self { Self::new( String::new(), Severity::Info, String::new(), String::new(), String::new(), ) } } #[derive(Debug, Clone, Copy)] pub enum Severity { Info, Success, Warn, Err, }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/pager/status_bar.rs
crates/nu-explore/src/explore/pager/status_bar.rs
use ratatui::{ buffer::Buffer, layout::Rect, style::{Modifier, Style}, widgets::{Block, Widget}, }; use super::super::{ nu_common::{NuStyle, string_width}, views::util::{nu_style_to_tui, set_span}, }; pub struct StatusBar { text: (String, Style), ctx1: (String, Style), ctx2: (String, Style), ctx3: (String, Style), back_s: Style, } impl StatusBar { pub fn new(text: String, ctx1: String, ctx2: String, ctx3: String) -> Self { Self { text: (text, Style::default()), ctx1: (ctx1, Style::default()), ctx2: (ctx2, Style::default()), ctx3: (ctx3, Style::default()), back_s: Style::default(), } } pub fn set_message_style(&mut self, style: NuStyle) { self.text.1 = nu_style_to_tui(style).add_modifier(Modifier::BOLD); } pub fn set_ctx1_style(&mut self, style: NuStyle) { self.ctx1.1 = nu_style_to_tui(style); } pub fn set_ctx2_style(&mut self, style: NuStyle) { self.ctx2.1 = nu_style_to_tui(style); } pub fn set_ctx3_style(&mut self, style: NuStyle) { self.ctx3.1 = nu_style_to_tui(style); } pub fn set_background_style(&mut self, style: NuStyle) { self.back_s = nu_style_to_tui(style); } } impl Widget for StatusBar { fn render(self, area: Rect, buf: &mut Buffer) { const MAX_CTX_WIDTH: u16 = 14; const SEPARATOR: &str = "│"; const PADDING: u16 = 1; // Fill background let block = Block::default().style(self.back_s); block.render(area, buf); if area.width < 10 { return; } let mut used_width: u16 = 0; // Collect non-empty context items let contexts: Vec<(&String, Style)> = [ (&self.ctx3.0, self.ctx3.1), (&self.ctx2.0, self.ctx2.1), (&self.ctx1.0, self.ctx1.1), ] .into_iter() .filter(|(text, _)| !text.is_empty()) .collect(); // Render context items from right to left for (i, (text, style)) in contexts.iter().enumerate() { let text_width = (string_width(text) as u16).min(MAX_CTX_WIDTH); // Calculate space needed let separator_space = if i > 0 { 2 } else { 0 }; // " │" before item let needed = text_width + PADDING + separator_space; if area.width <= used_width + needed + 5 { // Reserve space for message break; } // Add right padding for first item if i == 0 { used_width += PADDING; } // Render the text let x = area.right().saturating_sub(used_width + text_width); set_span(buf, (x, area.y), text, *style, text_width); used_width += text_width; // Render separator before next item (visually after current, since RTL) if i < contexts.len() - 1 { let sep_x = area.right().saturating_sub(used_width + 2); let dim_style = self.back_s.add_modifier(Modifier::DIM); set_span(buf, (sep_x, area.y), SEPARATOR, dim_style, 1); used_width += 2; // separator + space } } // Add spacing before message if !contexts.is_empty() { used_width += PADDING; } // Render the main message on the left let (text, style) = self.text; if !text.is_empty() && area.width > used_width + PADDING * 2 { let available_width = area.width.saturating_sub(used_width + PADDING * 2); let text_to_render = if string_width(&text) as u16 > available_width { let mut truncated = text.clone(); while string_width(&truncated) as u16 > available_width.saturating_sub(1) && !truncated.is_empty() { truncated.pop(); } if !truncated.is_empty() { truncated.push('…'); } truncated } else { text }; set_span( buf, (area.x + PADDING, area.y), &text_to_render, style, available_width, ); } } } #[cfg(test)] mod tests { use super::*; fn buffer_to_string(buf: &Buffer) -> String { let mut result = String::new(); for y in 0..buf.area.height { for x in 0..buf.area.width { if let Some(cell) = buf.cell((x, y)) { result.push_str(cell.symbol()); } } if y < buf.area.height - 1 { result.push('\n'); } } result } fn render_status_bar(status_bar: StatusBar, width: u16, height: u16) -> Buffer { let area = Rect::new(0, 0, width, height); let mut buf = Buffer::empty(area); status_bar.render(area, &mut buf); buf } #[test] fn test_status_bar_basic_message() { let status_bar = StatusBar::new( "Test Message".to_string(), String::new(), String::new(), String::new(), ); let buf = render_status_bar(status_bar, 40, 1); let content = buffer_to_string(&buf); assert!(content.contains("Test Message")); } #[test] fn test_status_bar_with_context() { let status_bar = StatusBar::new( "Message".to_string(), "Ctx1".to_string(), "Ctx2".to_string(), "Ctx3".to_string(), ); let buf = render_status_bar(status_bar, 60, 1); let content = buffer_to_string(&buf); assert!(content.contains("Message")); assert!(content.contains("Ctx1")); assert!(content.contains("Ctx2")); assert!(content.contains("Ctx3")); } #[test] fn test_status_bar_context_order() { let status_bar = StatusBar::new( "Msg".to_string(), "First".to_string(), "Second".to_string(), "Third".to_string(), ); let buf = render_status_bar(status_bar, 60, 1); let content = buffer_to_string(&buf); // Message should be on the left, contexts on the right let msg_pos = content.find("Msg").unwrap(); let first_pos = content.find("First").unwrap(); assert!(msg_pos < first_pos); } #[test] fn test_status_bar_narrow_width_no_render() { // Width < 10 should not render context items let status_bar = StatusBar::new( "Message".to_string(), "Ctx1".to_string(), String::new(), String::new(), ); let buf = render_status_bar(status_bar, 9, 1); let content = buffer_to_string(&buf); // Should not contain context when too narrow assert!(!content.contains("Ctx1")); } #[test] fn test_status_bar_empty_contexts_filtered() { let status_bar = StatusBar::new( "Message".to_string(), "OnlyOne".to_string(), String::new(), String::new(), ); let buf = render_status_bar(status_bar, 40, 1); let content = buffer_to_string(&buf); assert!(content.contains("Message")); assert!(content.contains("OnlyOne")); // Should not have separators for empty contexts } #[test] fn test_status_bar_long_message_truncation() { let long_message = "A".repeat(100); let status_bar = StatusBar::new( long_message, "Ctx".to_string(), String::new(), String::new(), ); let buf = render_status_bar(status_bar, 30, 1); let content = buffer_to_string(&buf); // Message should be truncated with ellipsis assert!(content.contains('…') || content.len() <= 30); } #[test] fn test_status_bar_unicode_text() { let status_bar = StatusBar::new( "日本語メッセージ".to_string(), "状態".to_string(), String::new(), String::new(), ); let buf = render_status_bar(status_bar, 50, 1); // Should handle Unicode without panicking assert_eq!(buf.area.width, 50); } #[test] fn test_status_bar_all_empty() { let status_bar = StatusBar::new(String::new(), String::new(), String::new(), String::new()); let buf = render_status_bar(status_bar, 40, 1); // Should not panic with all empty strings assert_eq!(buf.area.width, 40); } #[test] fn test_status_bar_context_max_width() { // Context items should be limited to MAX_CTX_WIDTH (14) let long_ctx = "A".repeat(30); let status_bar = StatusBar::new("Msg".to_string(), long_ctx, String::new(), String::new()); let buf = render_status_bar(status_bar, 60, 1); // Should not panic and should render assert_eq!(buf.area.width, 60); } #[test] fn test_status_bar_separator_between_contexts() { let status_bar = StatusBar::new( String::new(), "A".to_string(), "B".to_string(), String::new(), ); let buf = render_status_bar(status_bar, 40, 1); let content = buffer_to_string(&buf); // Should have separator between contexts assert!(content.contains('│')); } #[test] fn test_status_bar_zero_height() { // Zero height buffer - just verify we can create the area let area = Rect::new(0, 0, 40, 0); assert_eq!(area.height, 0); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/pager/command_bar.rs
crates/nu-explore/src/explore/pager/command_bar.rs
use ratatui::{ buffer::Buffer, layout::Rect, style::{Modifier, Style}, widgets::{Block, Widget}, }; use super::super::{ nu_common::{NuStyle, string_width}, views::util::{nu_style_to_tui, set_span}, }; #[derive(Debug)] pub struct CommandBar<'a> { text: &'a str, information: &'a str, text_s: Style, back_s: Style, } impl<'a> CommandBar<'a> { pub fn new(text: &'a str, information: &'a str, text_s: NuStyle, back_s: NuStyle) -> Self { let text_s = nu_style_to_tui(text_s).add_modifier(Modifier::BOLD); let back_s = nu_style_to_tui(back_s); Self { text, information, text_s, back_s, } } } impl Widget for CommandBar<'_> { fn render(self, area: Rect, buf: &mut Buffer) { const INFO_PADDING_RIGHT: u16 = 2; const TEXT_PADDING_LEFT: u16 = 1; // colorize the entire line background let block = Block::default().style(self.back_s); block.render(area, buf); // Render the command/search text on the left with padding let text_x = area.x + TEXT_PADDING_LEFT; let info_width = string_width(self.information) as u16; let max_text_width = area .width .saturating_sub(TEXT_PADDING_LEFT + info_width + INFO_PADDING_RIGHT + 2); let text_width = set_span( buf, (text_x, area.y), self.text, self.text_s, max_text_width, ); // Calculate available space for info let available_width = area.width.saturating_sub(text_x - area.x + text_width); if available_width <= INFO_PADDING_RIGHT + 2 || self.information.is_empty() { return; } // Render info on the right with padding let info_x = area.right().saturating_sub(info_width + INFO_PADDING_RIGHT); if info_x > text_x + text_width + 1 { set_span( buf, (info_x, area.y), self.information, self.text_s, info_width, ); } } } #[cfg(test)] mod tests { use super::*; fn buffer_to_string(buf: &Buffer) -> String { let mut result = String::new(); for y in 0..buf.area.height { for x in 0..buf.area.width { if let Some(cell) = buf.cell((x, y)) { result.push_str(cell.symbol()); } } if y < buf.area.height - 1 { result.push('\n'); } } result } fn render_command_bar(text: &str, information: &str, width: u16, height: u16) -> Buffer { let area = Rect::new(0, 0, width, height); let mut buf = Buffer::empty(area); let cmd_bar = CommandBar::new(text, information, NuStyle::default(), NuStyle::default()); cmd_bar.render(area, &mut buf); buf } #[test] fn test_command_bar_basic_text() { let buf = render_command_bar(":help", "", 40, 1); let content = buffer_to_string(&buf); assert!(content.contains(":help")); } #[test] fn test_command_bar_with_information() { let buf = render_command_bar(":search", "[1/5]", 40, 1); let content = buffer_to_string(&buf); assert!(content.contains(":search")); assert!(content.contains("[1/5]")); } #[test] fn test_command_bar_text_on_left_info_on_right() { let buf = render_command_bar("/pattern", "[3/10]", 50, 1); let content = buffer_to_string(&buf); let text_pos = content.find("/pattern").unwrap(); let info_pos = content.find("[3/10]").unwrap(); // Text should be on the left, info on the right assert!(text_pos < info_pos); } #[test] fn test_command_bar_empty_text() { let buf = render_command_bar("", "[info]", 40, 1); let content = buffer_to_string(&buf); // Should not panic with empty text assert!(content.contains("[info]")); } #[test] fn test_command_bar_empty_information() { let buf = render_command_bar(":quit", "", 40, 1); let content = buffer_to_string(&buf); assert!(content.contains(":quit")); } #[test] fn test_command_bar_both_empty() { let buf = render_command_bar("", "", 40, 1); // Should not panic with both empty assert_eq!(buf.area.width, 40); } #[test] fn test_command_bar_narrow_width() { // Very narrow width - info might not fit let buf = render_command_bar(":x", "[info]", 10, 1); // Should not panic assert_eq!(buf.area.width, 10); } #[test] fn test_command_bar_unicode_text() { let buf = render_command_bar("/日本語", "[結果]", 50, 1); let content = buffer_to_string(&buf); // Should handle Unicode without panicking assert!(content.contains("日本語") || !content.is_empty()); } #[test] fn test_command_bar_left_padding() { let buf = render_command_bar(":a", "", 20, 1); let content = buffer_to_string(&buf); // Text should not start at position 0 (there's padding) let first_char = content.chars().next().unwrap(); assert_eq!(first_char, ' '); } #[test] fn test_command_bar_zero_height() { // Zero height buffer - just verify we can create the area let area = Rect::new(0, 0, 40, 0); assert_eq!(area.height, 0); } #[test] fn test_command_bar_zero_width() { let buf = render_command_bar(":test", "[info]", 0, 1); assert_eq!(buf.area.width, 0); } #[test] fn test_command_bar_long_text_and_info() { let long_text = ":".to_string() + &"a".repeat(50); let long_info = "b".repeat(20); let buf = render_command_bar(&long_text, &long_info, 40, 1); // Should not panic with long text assert_eq!(buf.area.width, 40); } #[test] fn test_command_bar_search_pattern() { let buf = render_command_bar("/search_pattern", "[0/0]", 40, 1); let content = buffer_to_string(&buf); assert!(content.contains("/search_pattern")); assert!(content.contains("[0/0]")); } #[test] fn test_command_bar_reverse_search() { let buf = render_command_bar("?reverse", "[2/5]", 40, 1); let content = buffer_to_string(&buf); assert!(content.contains("?reverse")); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/pager/title_bar.rs
crates/nu-explore/src/explore/pager/title_bar.rs
use ratatui::{ buffer::Buffer, layout::Rect, style::{Modifier, Style}, widgets::{Block, Widget}, }; use super::super::{ nu_common::{NuStyle, string_width}, views::util::{nu_style_to_tui, set_span}, }; /// A title bar widget displayed at the top of the explore view pub struct TitleBar { title: String, title_style: Style, info_left: String, info_right: String, info_style: Style, background_style: Style, } impl TitleBar { pub fn new(title: impl Into<String>) -> Self { Self { title: title.into(), title_style: Style::default().add_modifier(Modifier::BOLD), info_left: String::new(), info_right: String::new(), info_style: Style::default().add_modifier(Modifier::DIM), background_style: Style::default(), } } pub fn with_info_left(mut self, info: impl Into<String>) -> Self { self.info_left = info.into(); self } pub fn with_info_right(mut self, info: impl Into<String>) -> Self { self.info_right = info.into(); self } pub fn set_background_style(&mut self, style: NuStyle) { self.background_style = nu_style_to_tui(style); } pub fn set_title_style(&mut self, style: NuStyle) { self.title_style = nu_style_to_tui(style).add_modifier(Modifier::BOLD); } pub fn set_info_style(&mut self, style: NuStyle) { self.info_style = nu_style_to_tui(style).add_modifier(Modifier::DIM); } } impl Widget for TitleBar { fn render(self, area: Rect, buf: &mut Buffer) { if area.height == 0 || area.width < 10 { return; } // Fill background let block = Block::default().style(self.background_style); block.render(area, buf); const PADDING: u16 = 1; const SEPARATOR_WIDTH: u16 = 3; let mut left_offset = PADDING; let mut right_offset = PADDING; // Render left info if present (with dimmed style for hints) if !self.info_left.is_empty() { let info_width = string_width(&self.info_left) as u16; let max_left_width = area.width / 3; if left_offset + info_width < max_left_width { set_span( buf, (area.x + left_offset, area.y), &self.info_left, self.info_style, info_width, ); left_offset += info_width + SEPARATOR_WIDTH; } } // Render right info if present (with dimmed style for hints) if !self.info_right.is_empty() { let info_width = string_width(&self.info_right) as u16; let max_right_width = area.width / 3; if right_offset + info_width < max_right_width { let x = area.right().saturating_sub(right_offset + info_width); set_span( buf, (x, area.y), &self.info_right, self.info_style, info_width, ); right_offset += info_width + SEPARATOR_WIDTH; } } // Calculate available space for title (centered) let title_width = string_width(&self.title) as u16; let available_center = area.width.saturating_sub(left_offset + right_offset); if title_width > 0 && available_center > 3 { // Try to center the title let ideal_x = area.x + (area.width.saturating_sub(title_width)) / 2; // Make sure title doesn't overlap with left/right info let min_x = area.x + left_offset; let max_x = area.right().saturating_sub(right_offset + title_width); let title_x = ideal_x.clamp(min_x, max_x.max(min_x)); let actual_width = (area.right().saturating_sub(right_offset)) .saturating_sub(title_x) .min(title_width); if actual_width > 0 { let title_to_render = if title_width > actual_width { let mut truncated = self.title.clone(); while string_width(&truncated) as u16 > actual_width.saturating_sub(1) && !truncated.is_empty() { truncated.pop(); } if !truncated.is_empty() { truncated.push('…'); } truncated } else { self.title }; set_span( buf, (title_x, area.y), &title_to_render, self.title_style, actual_width, ); } } } } #[cfg(test)] mod tests { use super::*; fn buffer_to_string(buf: &Buffer) -> String { let mut result = String::new(); for y in 0..buf.area.height { for x in 0..buf.area.width { if let Some(cell) = buf.cell((x, y)) { result.push_str(cell.symbol()); } } if y < buf.area.height - 1 { result.push('\n'); } } result } fn render_title_bar(title_bar: TitleBar, width: u16, height: u16) -> Buffer { let area = Rect::new(0, 0, width, height); let mut buf = Buffer::empty(area); title_bar.render(area, &mut buf); buf } #[test] fn test_title_bar_basic_render() { let title_bar = TitleBar::new("Test Title"); let buf = render_title_bar(title_bar, 40, 1); let content = buffer_to_string(&buf); assert!(content.contains("Test Title")); } #[test] fn test_title_bar_with_left_info() { let title_bar = TitleBar::new("Title").with_info_left("Left Info"); let buf = render_title_bar(title_bar, 50, 1); let content = buffer_to_string(&buf); assert!(content.contains("Left Info")); assert!(content.contains("Title")); } #[test] fn test_title_bar_with_right_info() { let title_bar = TitleBar::new("Title").with_info_right("Right Info"); let buf = render_title_bar(title_bar, 50, 1); let content = buffer_to_string(&buf); assert!(content.contains("Right Info")); assert!(content.contains("Title")); } #[test] fn test_title_bar_with_both_infos() { let title_bar = TitleBar::new("Center") .with_info_left("Left") .with_info_right("Right"); let buf = render_title_bar(title_bar, 60, 1); let content = buffer_to_string(&buf); assert!(content.contains("Left")); assert!(content.contains("Center")); assert!(content.contains("Right")); // Verify order: left info should come before center, center before right let left_pos = content.find("Left").unwrap(); let center_pos = content.find("Center").unwrap(); let right_pos = content.find("Right").unwrap(); assert!(left_pos < center_pos); assert!(center_pos < right_pos); } #[test] fn test_title_bar_narrow_width_no_render() { // Width < 10 should not render anything let title_bar = TitleBar::new("Title"); let buf = render_title_bar(title_bar, 9, 1); let content = buffer_to_string(&buf); // Should be empty (just spaces) assert!(!content.contains("Title")); } #[test] fn test_title_bar_zero_height_no_render() { // Zero height buffer - just verify we can create the area let area = Rect::new(0, 0, 40, 0); assert_eq!(area.height, 0); } #[test] fn test_title_bar_title_centered() { let title_bar = TitleBar::new("XX"); let buf = render_title_bar(title_bar, 20, 1); let content = buffer_to_string(&buf); // Find position of title - should be roughly centered let title_pos = content.find("XX").unwrap(); // With width 20 and title "XX" (2 chars), ideal center is around position 9 assert!((8..=10).contains(&title_pos)); } #[test] fn test_title_bar_unicode_width() { // Test with Unicode characters that have different display widths let title_bar = TitleBar::new("日本語"); // Japanese characters (wider) let buf = render_title_bar(title_bar, 40, 1); // Should not panic when handling wide Unicode characters assert_eq!(buf.area.width, 40); } #[test] fn test_title_bar_empty_title() { let title_bar = TitleBar::new(""); let buf = render_title_bar(title_bar, 40, 1); // Should not panic, just render empty assert_eq!(buf.area.width, 40); } #[test] fn test_title_bar_builder_pattern() { // Verify builder pattern works correctly let title_bar = TitleBar::new("Title") .with_info_left("L") .with_info_right("R"); assert_eq!(title_bar.title, "Title"); assert_eq!(title_bar.info_left, "L"); assert_eq!(title_bar.info_right, "R"); } #[test] fn test_title_bar_very_long_title_truncation() { let long_title = "A".repeat(100); let title_bar = TitleBar::new(long_title); let buf = render_title_bar(title_bar, 30, 1); let content = buffer_to_string(&buf); // Title should be truncated with ellipsis assert!(content.contains('…') || content.len() <= 30); } #[test] fn test_title_bar_info_respects_width_limit() { // Info should not take more than 1/3 of width let title_bar = TitleBar::new("T") .with_info_left("A".repeat(50).as_str()) .with_info_right("B".repeat(50).as_str()); let buf = render_title_bar(title_bar, 30, 1); // Should not panic, and title should still be visible if possible assert_eq!(buf.area.width, 30); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/pager/mod.rs
crates/nu-explore/src/explore/pager/mod.rs
mod command_bar; mod events; pub mod report; mod status_bar; mod title_bar; use self::{ command_bar::CommandBar, report::{Report, Severity}, status_bar::StatusBar, title_bar::TitleBar, }; use super::{ config::ExploreConfig, nu_common::{NuColor, NuConfig, NuStyle}, registry::{Command, CommandRegistry}, views::{Layout, View, ViewConfig, util::nu_style_to_tui}, }; use anyhow::Result; use crossterm::{ event::{KeyCode, KeyEvent, KeyModifiers}, execute, terminal::{ Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode, }, }; use events::UIEvents; use lscolors::LsColors; use nu_color_config::StyleComputer; use nu_protocol::{ Value, engine::{EngineState, Stack}, }; use ratatui::{backend::CrosstermBackend, layout::Rect, widgets::Block}; use std::{ cmp::min, io::{self, Stdout}, result, }; use unicode_width::{UnicodeWidthChar, UnicodeWidthStr}; pub type Frame<'a> = ratatui::Frame<'a>; pub type Terminal = ratatui::Terminal<CrosstermBackend<Stdout>>; #[derive(Debug, Clone)] pub struct Pager<'a> { config: PagerConfig<'a>, message: Option<String>, cmd_buf: CommandBuf, search_buf: SearchBuf, } #[derive(Debug, Clone, Default)] struct SearchBuf { buf_cmd: String, buf_cmd_input: String, search_results: Vec<usize>, search_index: usize, is_reversed: bool, is_search_input: bool, } #[derive(Debug, Clone, Default)] struct CommandBuf { is_cmd_input: bool, run_cmd: bool, buf_cmd2: String, cursor_pos: usize, cmd_history: Vec<String>, cmd_history_allow: bool, cmd_history_pos: usize, cmd_exec_info: Option<String>, } impl<'a> Pager<'a> { pub fn new(config: PagerConfig<'a>) -> Self { Self { config, cmd_buf: CommandBuf::default(), search_buf: SearchBuf::default(), message: None, } } pub fn show_message(&mut self, text: impl Into<String>) { self.message = Some(text.into()); } pub fn run( &mut self, engine_state: &EngineState, stack: &mut Stack, view: Option<Page>, commands: CommandRegistry, ) -> Result<Option<Value>> { // setup terminal enable_raw_mode()?; let mut stdout = io::stdout(); execute!(stdout, EnterAlternateScreen, Clear(ClearType::All))?; let backend = CrosstermBackend::new(stdout); let mut terminal = Terminal::new(backend)?; let mut info = ViewInfo { status: Some(Report::default()), ..Default::default() }; if let Some(text) = self.message.take() { info.status = Some(Report::message(text, Severity::Info)); } let result = render_ui( &mut terminal, engine_state, stack, self, &mut info, view, commands, )?; // restore terminal disable_raw_mode()?; execute!(io::stdout(), LeaveAlternateScreen)?; Ok(result) } } #[derive(Debug, Clone)] pub enum Transition { Ok, Exit, Cmd(String), None, } #[derive(Debug, Clone)] pub enum StatusTopOrEnd { Top, End, None, } #[derive(Debug, Clone)] pub struct PagerConfig<'a> { pub nu_config: &'a NuConfig, pub explore_config: &'a ExploreConfig, pub style_computer: &'a StyleComputer<'a>, pub lscolors: &'a LsColors, // If true, when quitting output the value of the cell the cursor was on pub peek_value: bool, pub tail: bool, // Just a cached dir we are working in used for color manipulations pub cwd: String, } impl<'a> PagerConfig<'a> { pub fn new( nu_config: &'a NuConfig, explore_config: &'a ExploreConfig, style_computer: &'a StyleComputer, lscolors: &'a LsColors, peek_value: bool, tail: bool, cwd: &str, ) -> Self { Self { nu_config, explore_config, style_computer, lscolors, peek_value, tail, cwd: cwd.to_string(), } } } #[allow(clippy::too_many_arguments)] fn render_ui( term: &mut Terminal, engine_state: &EngineState, stack: &mut Stack, pager: &mut Pager<'_>, info: &mut ViewInfo, view: Option<Page>, commands: CommandRegistry, ) -> Result<Option<Value>> { let events = UIEvents::new(); let mut view_stack = ViewStack::new(view, Vec::new()); loop { if engine_state.signals().interrupted() { break Ok(None); } // Give the view a chance to update its internal state (e.g., receive streaming data) // and update the status bar before drawing. if let Some(page) = view_stack.curr_view.as_mut() { page.view.update(info); } let mut layout = Layout::default(); { let info = info.clone(); term.draw(|f| { draw_frame(f, &mut view_stack.curr_view, pager, &mut layout, info); })?; } // Note that this will return within the configured tick_rate of events. In particular this // means this loop keeps redrawing the UI about 4 times a second, whether it needs to or // not. That's OK-ish because ratatui will detect real changes and not send unnecessary // output to the terminal (something that may especially be important with ssh). While not // needed at the moment, the idea is that this behavior allows for some degree of // animation (so that the UI can update over time, even without user input). let transition = handle_events( engine_state, stack, &events, &layout, info, &mut pager.search_buf, &mut pager.cmd_buf, view_stack.curr_view.as_mut().map(|p| &mut p.view), ); let (exit, cmd_name) = react_to_event_result( transition, engine_state, &commands, pager, &mut view_stack, stack, info, ); if let Some(value) = exit { break Ok(value); } if !cmd_name.is_empty() { if let Some(r) = info.report.as_mut() { r.message = cmd_name; r.level = Severity::Success; } else { info.report = Some(Report::success(cmd_name)); } let info = info.clone(); term.draw(|f| { draw_info(f, pager, info); })?; } if pager.cmd_buf.run_cmd { let args = pager.cmd_buf.buf_cmd2.clone(); pager.cmd_buf.run_cmd = false; pager.cmd_buf.buf_cmd2.clear(); let out = pager_run_command(engine_state, stack, pager, &mut view_stack, &commands, args); match out { Ok(result) => { if result.exit { break Ok(peek_value_from_view(&mut view_stack.curr_view, pager)); } if result.view_change && !result.cmd_name.is_empty() { if let Some(r) = info.report.as_mut() { r.message = result.cmd_name; r.level = Severity::Success; } else { info.report = Some(Report::success(result.cmd_name)); } let info = info.clone(); term.draw(|f| { draw_info(f, pager, info); })?; } } Err(err) => info.report = Some(Report::error(err)), } } } } fn react_to_event_result( status: Transition, engine_state: &EngineState, commands: &CommandRegistry, pager: &mut Pager<'_>, view_stack: &mut ViewStack, stack: &mut Stack, info: &mut ViewInfo, ) -> (Option<Option<Value>>, String) { match status { Transition::Exit => ( Some(peek_value_from_view(&mut view_stack.curr_view, pager)), String::default(), ), Transition::Ok => { let exit = view_stack.stack.is_empty(); if exit { return ( Some(peek_value_from_view(&mut view_stack.curr_view, pager)), String::default(), ); } // try to pop the view stack if let Some(v) = view_stack.stack.pop() { view_stack.curr_view = Some(v); } (None, String::default()) } Transition::Cmd(cmd) => { let out = pager_run_command(engine_state, stack, pager, view_stack, commands, cmd); match out { Ok(result) if result.exit => ( Some(peek_value_from_view(&mut view_stack.curr_view, pager)), String::default(), ), Ok(result) => (None, result.cmd_name), Err(err) => { info.report = Some(Report::error(err)); (None, String::default()) } } } Transition::None => (None, String::default()), } } fn peek_value_from_view(view: &mut Option<Page>, pager: &mut Pager<'_>) -> Option<Value> { if pager.config.peek_value { let view = view.as_mut().map(|p| &mut p.view); view.and_then(|v| v.exit()) } else { None } } fn draw_frame( f: &mut Frame, view: &mut Option<Page>, pager: &mut Pager<'_>, layout: &mut Layout, info: ViewInfo, ) { let area = f.area(); // Reserve space: 1 line for title bar at top, 2 lines for status/cmd bars at bottom let title_area = Rect::new(area.x, area.y, area.width, 1); let content_area = Rect::new( area.x, area.y + 1, area.width, area.height.saturating_sub(3), ); // Render title bar render_title_bar(f, title_area, pager.config.explore_config); if let Some(page) = view { let cfg = create_view_config(pager); page.view.draw(f, content_area, cfg, layout); } draw_info(f, pager, info); highlight_search_results(f, pager, layout, pager.config.explore_config.highlight); set_cursor_cmd_bar(f, area, pager); } fn render_title_bar(f: &mut Frame, area: Rect, theme: &ExploreConfig) { let mut title_bar = TitleBar::new("Explore") .with_info_left("Navigate: ←↑↓→") .with_info_right(":help for help"); title_bar.set_background_style(theme.title_bar_background); title_bar.set_title_style(theme.title_bar_text); title_bar.set_info_style(theme.title_bar_text); f.render_widget(title_bar, area); } fn draw_info(f: &mut Frame, pager: &mut Pager<'_>, info: ViewInfo) { let area = f.area(); if let Some(report) = info.status { let last_2nd_line = area.bottom().saturating_sub(2); let area = Rect::new(area.left(), last_2nd_line, area.width, 1); render_status_bar(f, area, report, pager.config.explore_config); } { let last_line = area.bottom().saturating_sub(1); let area = Rect::new(area.left(), last_line, area.width, 1); render_cmd_bar(f, area, pager, info.report, pager.config.explore_config); } } fn create_view_config<'a>(pager: &'a Pager<'_>) -> ViewConfig<'a> { let cfg = &pager.config; ViewConfig::new( cfg.nu_config, cfg.explore_config, cfg.style_computer, cfg.lscolors, &pager.config.cwd, ) } fn pager_run_command( engine_state: &EngineState, stack: &mut Stack, pager: &mut Pager, view_stack: &mut ViewStack, commands: &CommandRegistry, args: String, ) -> result::Result<CmdResult, String> { let command = commands.find(&args); match command { Some(Ok(command)) => { let result = run_command(engine_state, stack, pager, view_stack, command); match result { Ok(value) => Ok(value), Err(err) => Err(format!("Error: command {args:?} failed: {err}")), } } Some(Err(err)) => Err(format!( "Error: command {args:?} was not provided with correct arguments: {err}" )), None => Err(format!("Error: command {args:?} was not recognized")), } } fn run_command( engine_state: &EngineState, stack: &mut Stack, pager: &mut Pager, view_stack: &mut ViewStack, command: Command, ) -> Result<CmdResult> { match command { Command::Reactive(mut command) => { // what we do we just replace the view. let value = view_stack.curr_view.as_mut().and_then(|p| p.view.exit()); let transition = command.react(engine_state, stack, pager, value)?; match transition { Transition::Ok => Ok(CmdResult::new(false, false, String::new())), Transition::Exit => Ok(CmdResult::new(true, false, String::new())), Transition::Cmd { .. } => todo!("not used so far"), Transition::None => panic!("Transition::None not expected from command.react()"), } } Command::View { mut cmd, stackable } => { // what we do we just replace the view. let value = view_stack.curr_view.as_mut().and_then(|p| p.view.exit()); let view_cfg = create_view_config(pager); let new_view = cmd.spawn(engine_state, stack, value, &view_cfg)?; if let Some(view) = view_stack.curr_view.take() && view.stackable { view_stack.stack.push(view); } view_stack.curr_view = Some(Page::raw(new_view, stackable)); Ok(CmdResult::new(false, true, cmd.name().to_owned())) } } } fn set_cursor_cmd_bar(f: &mut Frame, area: Rect, pager: &Pager) { // Account for left padding (1) + prefix char like ':' or '/' (1) const LEFT_OFFSET: u16 = 2; if pager.search_buf.is_search_input { // todo: deal with a situation where we exceed the bar width let next_pos = pager.search_buf.buf_cmd_input.width() as u16 + LEFT_OFFSET; if next_pos < area.width { f.set_cursor_position((next_pos, area.height - 1)); } } } fn render_status_bar(f: &mut Frame, area: Rect, report: Report, theme: &ExploreConfig) { let msg_style = report_msg_style(&report, theme, theme.status_bar_text); let mut status_bar = create_status_bar(report); status_bar.set_background_style(theme.status_bar_background); status_bar.set_message_style(msg_style); status_bar.set_ctx1_style(theme.status_bar_text); status_bar.set_ctx2_style(theme.status_bar_text); status_bar.set_ctx3_style(theme.status_bar_text); f.render_widget(status_bar, area); } fn create_status_bar(report: Report) -> StatusBar { StatusBar::new( report.message, report.context1, report.context2, report.context3, ) } fn report_msg_style(report: &Report, config: &ExploreConfig, style: NuStyle) -> NuStyle { match report.level { Severity::Info => style, _ => report_level_style(report.level, config), } } fn render_cmd_bar( f: &mut Frame, area: Rect, pager: &Pager, report: Option<Report>, config: &ExploreConfig, ) { if let Some(report) = report { let style = report_msg_style(&report, config, config.cmd_bar_text); let bar = CommandBar::new( &report.message, &report.context1, style, config.cmd_bar_background, ); f.render_widget(bar, area); return; } if pager.cmd_buf.is_cmd_input { render_cmd_bar_cmd(f, area, pager, config); return; } if pager.search_buf.is_search_input || !pager.search_buf.buf_cmd_input.is_empty() { render_cmd_bar_search(f, area, pager, config); } } fn render_cmd_bar_search(f: &mut Frame, area: Rect, pager: &Pager<'_>, config: &ExploreConfig) { if pager.search_buf.search_results.is_empty() && !pager.search_buf.is_search_input { let message = format!("Pattern not found: {}", pager.search_buf.buf_cmd_input); let style = NuStyle { background: Some(NuColor::Red), foreground: Some(NuColor::White), ..Default::default() }; let bar = CommandBar::new(&message, "", style, config.cmd_bar_background); f.render_widget(bar, area); return; } let prefix = if pager.search_buf.is_reversed { '?' } else { '/' }; let text = format!("{}{}", prefix, pager.search_buf.buf_cmd_input); let info = if pager.search_buf.search_results.is_empty() { String::from("[0/0]") } else { let index = pager.search_buf.search_index + 1; let total = pager.search_buf.search_results.len(); format!("[{index}/{total}]") }; let bar = CommandBar::new(&text, &info, config.cmd_bar_text, config.cmd_bar_background); f.render_widget(bar, area); } fn render_cmd_bar_cmd(f: &mut Frame, area: Rect, pager: &Pager, config: &ExploreConfig) { let input = pager.cmd_buf.buf_cmd2.as_str(); let cursor_pos = pager.cmd_buf.cursor_pos; let input_width = input.width(); let max_len = area.width as usize - 1; // -1 for : let mut display_input = input; let mut skipped_chars = 0; if input_width > max_len { // Truncate from left to fit max_len let mut current_width = 0; let mut start_byte = 0; for (i, c) in input.char_indices() { let c_width = c.width().unwrap_or(1); if current_width + c_width > input_width - max_len { start_byte = i; break; } current_width += c_width; skipped_chars += 1; } display_input = &input[start_byte..]; } // Further truncate to match CommandBar's max_text_width let max_text_width = area.width.saturating_sub(1) as usize; // TEXT_PADDING_LEFT=1, no info padding let max_for_display = max_text_width.saturating_sub(1); let mut truncated_display = display_input; if truncated_display.width() > max_for_display { let mut current_width = 0; let mut end = 0; for (i, c) in truncated_display.char_indices() { let c_width = c.width().unwrap_or(1); if current_width + c_width > max_for_display { break; } current_width += c_width; end = i + c.len_utf8(); } truncated_display = &truncated_display[..end]; } let prefix = ':'; let text = format!("{prefix}{truncated_display}"); let bar = CommandBar::new(&text, "", config.cmd_bar_text, config.cmd_bar_background); f.render_widget(bar, area); // Set the terminal cursor position if pager.cmd_buf.is_cmd_input { let cursor_in_input = cursor_pos; // char index of cursor in buf let cursor_col = if cursor_in_input >= skipped_chars { let mut cursor_in_display = cursor_in_input - skipped_chars; // Clamp to truncated_display length let truncated_char_count = truncated_display.chars().count(); cursor_in_display = cursor_in_display.min(truncated_char_count); // Get the substring before the cursor let before_display: String = truncated_display.chars().take(cursor_in_display).collect(); 2 + before_display.width() as u16 // 2 for :, then visual width } else { 2 // cursor is in truncated part, place at start after : }; f.set_cursor_position((area.x + cursor_col, area.y)); } } fn highlight_search_results(f: &mut Frame, pager: &Pager, layout: &Layout, style: NuStyle) { if pager.search_buf.search_results.is_empty() { return; } let highlight_block = Block::default().style(nu_style_to_tui(style)); for e in &layout.data { let text = ansi_str::AnsiStr::ansi_strip(&e.text); if let Some(p) = text.find(&pager.search_buf.buf_cmd_input) { let p = covert_bytes_to_chars(&text, p); // this width is a best guess let w = pager.search_buf.buf_cmd_input.width() as u16; let area = Rect::new(e.area.x + p as u16, e.area.y, w, 1); f.render_widget(highlight_block.clone(), area); } } } fn covert_bytes_to_chars(text: &str, p: usize) -> usize { let mut b = 0; let mut i = 0; for c in text.chars() { b += c.len_utf8(); if b > p { break; } i += 1; } i } #[allow(clippy::too_many_arguments)] fn handle_events<V: View>( engine_state: &EngineState, stack: &mut Stack, events: &UIEvents, layout: &Layout, info: &mut ViewInfo, search: &mut SearchBuf, command: &mut CommandBuf, mut view: Option<&mut V>, ) -> Transition { // We are only interested in Pressed events; // It's crucial because there are cases where terminal MIGHT produce false events; // 2 events 1 for release 1 for press. // Want to react only on 1 of them so we do. let mut key = match events.next_key_press() { Ok(Some(key)) => key, Ok(None) => return Transition::None, Err(e) => { log::error!("Failed to read key event: {e}"); return Transition::None; } }; // Sometimes we get a BIG list of events; // for example when someone scrolls via a mouse either UP or DOWN. // This MIGHT cause freezes as we have a 400 delay for a next command read. // // To eliminate that we are trying to read all possible commands which we should act upon. loop { let result = handle_event( engine_state, stack, layout, info, search, command, view.as_deref_mut(), key, ); if !matches!(result, Transition::None) { return result; } match events.try_next_key_press() { Ok(Some(next_key)) => key = next_key, Ok(None) => return Transition::None, Err(e) => { log::error!("Failed to peek key event: {e}"); return Transition::None; } } } } #[allow(clippy::too_many_arguments)] fn handle_event<V: View>( engine_state: &EngineState, stack: &mut Stack, layout: &Layout, info: &mut ViewInfo, search: &mut SearchBuf, command: &mut CommandBuf, mut view: Option<&mut V>, key: KeyEvent, ) -> Transition { if handle_exit_key_event(&key) { return Transition::Exit; } if handle_general_key_events1(&key, search, command, view.as_deref_mut()) { return Transition::None; } if let Some(view) = &mut view { let t = view.handle_input(engine_state, stack, layout, info, key); match t { Transition::Exit => return Transition::Ok, Transition::Cmd(cmd) => return Transition::Cmd(cmd), Transition::Ok => return Transition::None, Transition::None => {} } } // was not handled so we must check our default controls handle_general_key_events2(&key, search, command, view, info); Transition::None } fn handle_exit_key_event(key: &KeyEvent) -> bool { if key.modifiers == KeyModifiers::CONTROL { // these are all common things people might try, might as well handle them all if let KeyCode::Char('c') | KeyCode::Char('d') | KeyCode::Char('q') = key.code { return true; } } false } fn handle_general_key_events1<V>( key: &KeyEvent, search: &mut SearchBuf, command: &mut CommandBuf, view: Option<&mut V>, ) -> bool where V: View, { if search.is_search_input { return search_input_key_event(search, view, key); } if command.is_cmd_input { return cmd_input_key_event(command, key); } false } fn handle_general_key_events2<V>( key: &KeyEvent, search: &mut SearchBuf, command: &mut CommandBuf, view: Option<&mut V>, info: &mut ViewInfo, ) where V: View, { match key.code { KeyCode::Char('?') => { search.buf_cmd_input.clear(); search.is_search_input = true; search.is_reversed = true; info.report = None; } KeyCode::Char('/') => { search.buf_cmd_input.clear(); search.is_search_input = true; search.is_reversed = false; info.report = None; } KeyCode::Char(':') => { command.buf_cmd2.clear(); command.is_cmd_input = true; command.cmd_exec_info = None; info.report = None; } KeyCode::Char('n') => { if !search.search_results.is_empty() { if search.buf_cmd_input.is_empty() { search.buf_cmd_input.clone_from(&search.buf_cmd); } if search.search_index + 1 == search.search_results.len() { search.search_index = 0 } else { search.search_index += 1; } let pos = search.search_results[search.search_index]; if let Some(view) = view { view.show_data(pos); } } } _ => {} } } fn search_input_key_event( buf: &mut SearchBuf, view: Option<&mut impl View>, key: &KeyEvent, ) -> bool { match &key.code { KeyCode::Esc => { buf.buf_cmd_input.clear(); if let Some(view) = view && !buf.buf_cmd.is_empty() { let data = view.collect_data().into_iter().map(|(text, _)| text); buf.search_results = search_pattern(data, &buf.buf_cmd, buf.is_reversed); buf.search_index = 0; } buf.is_search_input = false; true } KeyCode::Enter => { buf.buf_cmd.clone_from(&buf.buf_cmd_input); buf.is_search_input = false; true } KeyCode::Backspace => { if buf.buf_cmd_input.is_empty() { buf.is_search_input = false; buf.is_reversed = false; } else { buf.buf_cmd_input.pop(); if let Some(view) = view && !buf.buf_cmd_input.is_empty() { let data = view.collect_data().into_iter().map(|(text, _)| text); buf.search_results = search_pattern(data, &buf.buf_cmd_input, buf.is_reversed); buf.search_index = 0; if !buf.search_results.is_empty() { let pos = buf.search_results[buf.search_index]; view.show_data(pos); } } } true } KeyCode::Char(c) => { buf.buf_cmd_input.push(*c); if let Some(view) = view && !buf.buf_cmd_input.is_empty() { let data = view.collect_data().into_iter().map(|(text, _)| text); buf.search_results = search_pattern(data, &buf.buf_cmd_input, buf.is_reversed); buf.search_index = 0; if !buf.search_results.is_empty() { let pos = buf.search_results[buf.search_index]; view.show_data(pos); } } true } _ => false, } } fn search_pattern(data: impl Iterator<Item = String>, pat: &str, rev: bool) -> Vec<usize> { let mut matches = Vec::new(); for (row, text) in data.enumerate() { if text.contains(pat) { matches.push(row); } } if rev { matches.reverse(); } matches } fn cmd_input_key_event(buf: &mut CommandBuf, key: &KeyEvent) -> bool { match &key.code { KeyCode::Esc => { buf.is_cmd_input = false; buf.buf_cmd2 = String::new(); buf.cursor_pos = 0; true } KeyCode::Enter => { buf.is_cmd_input = false; buf.run_cmd = true; buf.cmd_history.push(buf.buf_cmd2.clone()); buf.cmd_history_pos = buf.cmd_history.len(); buf.cursor_pos = 0; true } KeyCode::Backspace => { if buf.cursor_pos > 0 { buf.cursor_pos -= 1; buf.buf_cmd2.remove(buf.cursor_pos); buf.cmd_history_allow = false; } else if buf.buf_cmd2.is_empty() { buf.is_cmd_input = false; } true } KeyCode::Delete => { if buf.cursor_pos < buf.buf_cmd2.len() { buf.buf_cmd2.remove(buf.cursor_pos); buf.cmd_history_allow = false; } true } KeyCode::Left => { if buf.cursor_pos > 0 { buf.cursor_pos -= 1; } true } KeyCode::Right => { if buf.cursor_pos < buf.buf_cmd2.len() { buf.cursor_pos += 1; } true } KeyCode::Char(c) => { buf.buf_cmd2.insert(buf.cursor_pos, *c); buf.cursor_pos += 1; buf.cmd_history_allow = false; true } KeyCode::Down if buf.buf_cmd2.is_empty() || buf.cmd_history_allow => { if !buf.cmd_history.is_empty() { buf.cmd_history_allow = true; buf.cmd_history_pos = min( buf.cmd_history_pos + 1, buf.cmd_history.len().saturating_sub(1), ); buf.buf_cmd2 .clone_from(&buf.cmd_history[buf.cmd_history_pos]); buf.cursor_pos = buf.buf_cmd2.len(); } true } KeyCode::Up if buf.buf_cmd2.is_empty() || buf.cmd_history_allow => { if !buf.cmd_history.is_empty() { buf.cmd_history_allow = true; buf.cmd_history_pos = buf.cmd_history_pos.saturating_sub(1); buf.buf_cmd2 .clone_from(&buf.cmd_history[buf.cmd_history_pos]); buf.cursor_pos = buf.buf_cmd2.len(); } true } _ => true, } } fn report_level_style(level: Severity, config: &ExploreConfig) -> NuStyle { match level { Severity::Info => config.status_info, Severity::Success => config.status_success, Severity::Warn => config.status_warn, Severity::Err => config.status_error, } } #[derive(Debug, Default, Clone)] pub struct ViewInfo { pub cursor: Option<Position>, pub status: Option<Report>, pub report: Option<Report>, } #[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct Position { pub x: u16, pub y: u16, } impl Position { pub fn new(x: u16, y: u16) -> Self { Self { x, y } } } pub struct Page { pub view: Box<dyn View>, /// Controls what happens when this view is the current view and a new view is created. /// If true, view will be pushed to the stack, otherwise, it will be deleted. pub stackable: bool, } impl Page { pub fn raw(view: Box<dyn View>, stackable: bool) -> Self { Self { view, stackable } } pub fn new<V>(view: V, stackable: bool) -> Self where V: View + 'static, { Self::raw(Box::new(view), stackable) } } struct ViewStack { curr_view: Option<Page>, stack: Vec<Page>, } impl ViewStack { fn new(view: Option<Page>, stack: Vec<Page>) -> Self { Self { curr_view: view, stack, } } } struct CmdResult { exit: bool, view_change: bool, cmd_name: String, } impl CmdResult { fn new(exit: bool, view_change: bool, cmd_name: String) -> Self { Self { exit, view_change, cmd_name, } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/pager/events.rs
crates/nu-explore/src/explore/pager/events.rs
use std::{ io::Result, time::{Duration, Instant}, }; use crossterm::event::{Event, KeyEvent, KeyEventKind, poll, read}; pub struct UIEvents { tick_rate: Duration, } pub struct Cfg { pub tick_rate: Duration, } impl Default for Cfg { fn default() -> Cfg { Cfg { tick_rate: Duration::from_millis(250), } } } impl UIEvents { pub fn new() -> UIEvents { UIEvents::with_config(Cfg::default()) } pub fn with_config(config: Cfg) -> UIEvents { UIEvents { tick_rate: config.tick_rate, } } /// Read the next key press event, dropping any other preceding events. Returns None if no /// relevant event is found within the configured tick_rate. pub fn next_key_press(&self) -> Result<Option<KeyEvent>> { let deadline = Instant::now() + self.tick_rate; loop { let timeout = deadline.saturating_duration_since(Instant::now()); if !poll(timeout)? { return Ok(None); } if let Event::Key(event) = read()? && event.kind == KeyEventKind::Press { return Ok(Some(event)); } } } /// Read the next key press event, dropping any other preceding events. If no key event is /// available, returns immediately. pub fn try_next_key_press(&self) -> Result<Option<KeyEvent>> { loop { if !poll(Duration::ZERO)? { return Ok(None); } if let Event::Key(event) = read()? && event.kind == KeyEventKind::Press { return Ok(Some(event)); } } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/nu_common/command.rs
crates/nu-explore/src/explore/nu_common/command.rs
use nu_engine::eval_block; use nu_parser::parse; use nu_protocol::{ OutDest, PipelineData, ShellError, Value, debugger::WithoutDebug, engine::{EngineState, Redirection, Stack, StateWorkingSet}, }; use std::sync::Arc; pub fn run_command_with_value( command: &str, input: &Value, engine_state: &EngineState, stack: &mut Stack, ) -> Result<PipelineData, ShellError> { if is_ignored_command(command) { return Err(ShellError::GenericError { error: "Command ignored".to_string(), msg: "the command is ignored".to_string(), span: None, help: None, inner: vec![], }); } let pipeline = PipelineData::value(input.clone(), None); let pipeline = run_nu_command(engine_state, stack, command, pipeline)?; if let PipelineData::Value(Value::Error { error, .. }, ..) = pipeline { Err(ShellError::GenericError { error: "Error from pipeline".to_string(), msg: error.to_string(), span: None, help: None, inner: vec![*error], }) } else { Ok(pipeline) } } pub fn run_nu_command( engine_state: &EngineState, stack: &mut Stack, cmd: &str, current: PipelineData, ) -> std::result::Result<PipelineData, ShellError> { let mut engine_state = engine_state.clone(); eval_source2(&mut engine_state, stack, cmd.as_bytes(), "", current) } pub fn is_ignored_command(command: &str) -> bool { let ignore_list = ["clear", "explore", "exit"]; for cmd in ignore_list { if command.starts_with(cmd) { return true; } } false } fn eval_source2( engine_state: &mut EngineState, stack: &mut Stack, source: &[u8], fname: &str, input: PipelineData, ) -> Result<PipelineData, ShellError> { let (mut block, delta) = { let mut working_set = StateWorkingSet::new(engine_state); let output = parse( &mut working_set, Some(fname), // format!("entry #{}", entry_num) source, false, ); if let Some(err) = working_set.parse_errors.first() { return Err(ShellError::GenericError { error: "Parse error".to_string(), msg: err.to_string(), span: None, help: None, inner: vec![], }); } (output, working_set.render()) }; // We need to merge different info other wise things like PIPEs etc will not work. if let Err(err) = engine_state.merge_delta(delta) { return Err(ShellError::GenericError { error: "Merge error".to_string(), msg: err.to_string(), span: None, help: None, inner: vec![err], }); } // eval_block outputs all expressions except the last to STDOUT; // we don't won't that. // // So we LITERALLY ignore all expressions except the LAST. if block.len() > 1 { let range = ..block.pipelines.len() - 1; // Note: `make_mut` will mutate `&mut block: &mut Arc<Block>` // for the outer fn scope `eval_block` Arc::make_mut(&mut block).pipelines.drain(range); } let stack = &mut stack.push_redirection( Some(Redirection::Pipe(OutDest::PipeSeparate)), Some(Redirection::Pipe(OutDest::PipeSeparate)), ); eval_block::<WithoutDebug>(engine_state, stack, &block, input).map(|p| p.body) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/nu_common/string.rs
crates/nu-explore/src/explore/nu_common/string.rs
use nu_table::string_truncate; pub use nu_table::string_width; pub fn truncate_str(text: &mut String, width: usize) { if width == 0 { text.clear(); } else { if string_width(text) < width { return; } *text = string_truncate(text, width - 1); text.push('…'); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/nu_common/value.rs
crates/nu-explore/src/explore/nu_common/value.rs
use super::NuSpan; use anyhow::Result; use nu_engine::get_columns; use nu_protocol::{ByteStream, ListStream, PipelineData, PipelineMetadata, Value, record}; use std::collections::HashMap; pub fn collect_pipeline(input: PipelineData) -> Result<(Vec<String>, Vec<Vec<Value>>)> { match input { PipelineData::Empty => Ok((vec![], vec![])), PipelineData::Value(value, ..) => collect_input(value), PipelineData::ListStream(stream, ..) => Ok(collect_list_stream(stream)), PipelineData::ByteStream(stream, metadata) => Ok(collect_byte_stream(stream, metadata)), } } fn collect_list_stream(stream: ListStream) -> (Vec<String>, Vec<Vec<Value>>) { let mut records = vec![]; for item in stream { records.push(item); } let mut cols = get_columns(&records); let data = convert_records_to_dataset(&cols, records); // trying to deal with 'non-standard input' if cols.is_empty() && !data.is_empty() { let min_column_length = data.iter().map(|row| row.len()).min().unwrap_or(0); if min_column_length > 0 { cols = (0..min_column_length).map(|i| i.to_string()).collect(); } } (cols, data) } fn collect_byte_stream( stream: ByteStream, metadata: Option<PipelineMetadata>, ) -> (Vec<String>, Vec<Vec<Value>>) { let span = stream.span(); let mut columns = vec![]; let mut data = vec![]; match stream.into_child() { Ok(child) => match child.wait_with_output() { Ok(output) => { let exit_code = output.exit_status.code(); if let Some(stdout) = output.stdout { columns.push(String::from("stdout")); data.push(string_or_binary(stdout, span)); } if let Some(stderr) = output.stderr { columns.push(String::from("stderr")); data.push(string_or_binary(stderr, span)); } columns.push(String::from("exit_code")); data.push(Value::int(exit_code.into(), span)); } Err(err) => { columns.push("".into()); data.push(Value::error(err, span)); } }, Err(stream) => { let value = stream .into_value() .unwrap_or_else(|err| Value::error(err, span)); columns.push("".into()); data.push(value); } } if metadata.is_some() { let val = Value::record(record! { "data_source" => Value::string("ls", span) }, span); columns.push(String::from("metadata")); data.push(val); } (columns, vec![data]) } fn string_or_binary(bytes: Vec<u8>, span: NuSpan) -> Value { match String::from_utf8(bytes) { Ok(str) => Value::string(str, span), Err(err) => Value::binary(err.into_bytes(), span), } } /// Try to build column names and a table grid. pub fn collect_input(value: Value) -> Result<(Vec<String>, Vec<Vec<Value>>)> { let span = value.span(); match value { Value::Record { val: record, .. } => { let (key, val): (_, Vec<Value>) = record.into_owned().into_iter().unzip(); Ok(( key, match val.is_empty() { true => vec![], false => vec![val], }, )) } Value::List { vals, .. } => { let mut columns = get_columns(&vals); let data = convert_records_to_dataset(&columns, vals); if columns.is_empty() && !data.is_empty() { columns = vec![String::from("")]; } Ok((columns, data)) } Value::String { val, .. } => { let lines = val .lines() .map(|line| Value::string(line, span)) .map(|val| vec![val]) .collect(); Ok((vec![String::from("")], lines)) } Value::Nothing { .. } => Ok((vec![], vec![])), Value::Custom { val, .. } => { let materialized = val.to_base_value(span)?; collect_input(materialized) } value => Ok((vec![String::from("")], vec![vec![value]])), } } fn convert_records_to_dataset(cols: &[String], records: Vec<Value>) -> Vec<Vec<Value>> { if !cols.is_empty() { create_table_for_record(cols, &records) } else if cols.is_empty() && records.is_empty() { vec![] } else if cols.len() == records.len() { vec![records] } else { // I am not sure whether it's good to return records as its length LIKELY // will not match columns, which makes no sense...... // // BUT... // we can represent it as a list; which we do records.into_iter().map(|record| vec![record]).collect() } } fn create_table_for_record(headers: &[String], items: &[Value]) -> Vec<Vec<Value>> { let mut data = vec![Vec::new(); items.len()]; for (i, item) in items.iter().enumerate() { let row = record_create_row(headers, item); data[i] = row; } data } fn record_create_row(headers: &[String], item: &Value) -> Vec<Value> { if let Value::Record { val, .. } = item { headers .iter() .map(|col| val.get(col).cloned().unwrap_or_else(unknown_error_value)) .collect() } else { // should never reach here due to `get_columns` above which will return // empty columns if any value in the list is not a record vec![Value::default(); headers.len()] } } pub fn create_map(value: &Value) -> Option<HashMap<String, Value>> { Some( value .as_record() .ok()? .iter() .map(|(k, v)| (k.clone(), v.clone())) .collect(), ) } fn unknown_error_value() -> Value { Value::string(String::from("❎"), NuSpan::unknown()) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/nu_common/table.rs
crates/nu-explore/src/explore/nu_common/table.rs
use super::NuConfig; use nu_color_config::StyleComputer; use nu_protocol::{Record, Signals, Value}; use nu_table::{ ExpandedTable, TableOpts, common::{nu_value_to_string, nu_value_to_string_clean}, }; pub fn try_build_table( value: Value, signals: &Signals, config: &NuConfig, style_computer: StyleComputer, ) -> String { let span = value.span(); let opts = TableOpts::new( config, style_computer, signals, span, usize::MAX, config.table.mode, 0, false, ); match value { Value::List { vals, .. } => try_build_list(vals, opts), Value::Record { val, .. } => try_build_map(&val, opts), val @ Value::String { .. } => { nu_value_to_string_clean(&val, config, &opts.style_computer).0 } val => nu_value_to_string(&val, config, &opts.style_computer).0, } } fn try_build_map(record: &Record, opts: TableOpts<'_>) -> String { let result = ExpandedTable::new(None, false, String::new()).build_map(record, opts.clone()); match result { Ok(Some(result)) => result, _ => { let value = Value::record(record.clone(), opts.span); nu_value_to_string(&value, opts.config, &opts.style_computer).0 } } } fn try_build_list(vals: Vec<Value>, opts: TableOpts<'_>) -> String { let result = ExpandedTable::new(None, false, String::new()).build_list(&vals, opts.clone()); match result { Ok(Some(out)) => out, _ => { // it means that the list is empty let value = Value::list(vals, opts.span); nu_value_to_string(&value, opts.config, &opts.style_computer).0 } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/nu_common/lscolor.rs
crates/nu-explore/src/explore/nu_common/lscolor.rs
use std::path::Path; use super::NuText; use lscolors::LsColors; use nu_ansi_term::{Color, Style}; use nu_engine::env_to_string; use nu_path::{expand_path_with, expand_to_real_path}; use nu_protocol::engine::{EngineState, Stack}; use nu_utils::get_ls_colors; pub fn create_lscolors(engine_state: &EngineState, stack: &Stack) -> LsColors { let colors = stack .get_env_var(engine_state, "LS_COLORS") .and_then(|v| env_to_string("LS_COLORS", v, engine_state, stack).ok()); get_ls_colors(colors) } /// Colorizes any columns named "name" in the table using LS_COLORS pub fn lscolorize(header: &[String], data: &mut [Vec<NuText>], cwd: &str, lscolors: &LsColors) { for (col, col_name) in header.iter().enumerate() { if col_name != "name" { continue; } for row in data.iter_mut() { let (path, text_style) = &mut row[col]; let style = get_path_style(path, cwd, lscolors); if let Some(style) = style { *text_style = text_style.style(style); } } } } fn get_path_style(path: &str, cwd: &str, ls_colors: &LsColors) -> Option<Style> { let stripped_path = nu_utils::strip_ansi_unlikely(path); let mut style = ls_colors.style_for_str(stripped_path.as_ref()); let is_likely_dir = style.is_none(); if is_likely_dir { let mut meta = std::fs::symlink_metadata(path).ok(); if meta.is_none() { let mut expanded_path = expand_to_real_path(path); let try_cwd = expanded_path.as_path() == Path::new(path); if try_cwd { let cwd_path = format!("./{path}"); expanded_path = expand_path_with(cwd_path, cwd, false); } meta = std::fs::symlink_metadata(expanded_path.as_path()).ok(); style = ls_colors.style_for_path_with_metadata(expanded_path.as_path(), meta.as_ref()); } else { style = ls_colors.style_for_path_with_metadata(path, meta.as_ref()); } } style.map(lsstyle_to_nu_style) } fn lsstyle_to_nu_style(s: &lscolors::Style) -> Style { let mut out = Style::default(); if let Some(clr) = &s.background { out.background = lscolor_to_nu_color(clr); } if let Some(clr) = &s.foreground { out.foreground = lscolor_to_nu_color(clr); } if s.font_style.slow_blink | s.font_style.rapid_blink { out.is_blink = true; } if s.font_style.bold { out.is_bold = true; } if s.font_style.dimmed { out.is_dimmed = true; } if s.font_style.hidden { out.is_hidden = true; } if s.font_style.reverse { out.is_reverse = true; } if s.font_style.italic { out.is_italic = true; } if s.font_style.underline { out.is_underline = true; } out } fn lscolor_to_nu_color(clr: &lscolors::Color) -> Option<Color> { use lscolors::Color::*; let clr = match clr { Black => Color::Black, BrightBlack => Color::DarkGray, Red => Color::Red, BrightRed => Color::LightRed, Green => Color::Green, BrightGreen => Color::LightGreen, Yellow => Color::Yellow, BrightYellow => Color::LightYellow, Blue => Color::Blue, BrightBlue => Color::LightBlue, Magenta => Color::Magenta, BrightMagenta => Color::LightMagenta, Cyan => Color::Cyan, BrightCyan => Color::LightCyan, White => Color::White, BrightWhite => Color::LightGray, &Fixed(i) => Color::Fixed(i), &RGB(r, g, b) => Color::Rgb(r, g, b), }; Some(clr) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/nu_common/mod.rs
crates/nu-explore/src/explore/nu_common/mod.rs
mod command; mod lscolor; mod string; mod table; mod value; use nu_color_config::TextStyle; use nu_protocol::Value; pub use nu_ansi_term::{Color as NuColor, Style as NuStyle}; pub use nu_protocol::{Config as NuConfig, Span as NuSpan}; pub type NuText = (String, TextStyle); pub use command::run_command_with_value; pub use lscolor::{create_lscolors, lscolorize}; pub use string::{string_width, truncate_str}; pub use table::try_build_table; pub use value::{collect_input, collect_pipeline, create_map}; pub fn has_simple_value(data: &[Vec<Value>]) -> Option<&Value> { if data.len() == 1 && data[0].len() == 1 && !matches!(&data[0][0], Value::List { .. } | Value::Record { .. }) { Some(&data[0][0]) } else { None } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/registry/command.rs
crates/nu-explore/src/explore/registry/command.rs
use super::super::{ commands::{SimpleCommand, ViewCommand}, views::{View, ViewConfig}, }; use anyhow::Result; #[derive(Clone)] pub enum Command { Reactive(Box<dyn SCommand>), View { cmd: Box<dyn VCommand>, stackable: bool, }, } impl Command { pub fn view<C>(command: C, stackable: bool) -> Self where C: ViewCommand + Clone + 'static, C::View: View, { let cmd = Box::new(ViewCmd(command)) as Box<dyn VCommand>; Self::View { cmd, stackable } } pub fn reactive<C>(command: C) -> Self where C: SimpleCommand + Clone + 'static, { let cmd = Box::new(command) as Box<dyn SCommand>; Self::Reactive(cmd) } } impl Command { pub fn name(&self) -> &str { match self { Command::Reactive(cmd) => cmd.name(), Command::View { cmd, .. } => cmd.name(), } } pub fn parse(&mut self, args: &str) -> Result<()> { match self { Command::Reactive(cmd) => cmd.parse(args), Command::View { cmd, .. } => cmd.parse(args), } } } // type helper to deal with `Box`es #[derive(Clone)] struct ViewCmd<C>(C); impl<C> ViewCommand for ViewCmd<C> where C: ViewCommand, C::View: View + 'static, { type View = Box<dyn View>; fn name(&self) -> &'static str { self.0.name() } fn description(&self) -> &'static str { self.0.description() } fn parse(&mut self, args: &str) -> Result<()> { self.0.parse(args) } fn spawn( &mut self, engine_state: &nu_protocol::engine::EngineState, stack: &mut nu_protocol::engine::Stack, value: Option<nu_protocol::Value>, cfg: &ViewConfig, ) -> Result<Self::View> { let view = self.0.spawn(engine_state, stack, value, cfg)?; Ok(Box::new(view) as Box<dyn View>) } } pub trait SCommand: SimpleCommand + SCommandClone {} impl<T> SCommand for T where T: 'static + SimpleCommand + Clone {} pub trait SCommandClone { fn clone_box(&self) -> Box<dyn SCommand>; } impl<T> SCommandClone for T where T: 'static + SCommand + Clone, { fn clone_box(&self) -> Box<dyn SCommand> { Box::new(self.clone()) } } impl Clone for Box<dyn SCommand> { fn clone(&self) -> Box<dyn SCommand> { self.clone_box() } } pub trait VCommand: ViewCommand<View = Box<dyn View>> + VCommandClone {} impl<T> VCommand for T where T: 'static + ViewCommand<View = Box<dyn View>> + Clone {} pub trait VCommandClone { fn clone_box(&self) -> Box<dyn VCommand>; } impl<T> VCommandClone for T where T: 'static + VCommand + Clone, { fn clone_box(&self) -> Box<dyn VCommand> { Box::new(self.clone()) } } impl Clone for Box<dyn VCommand> { fn clone(&self) -> Box<dyn VCommand> { self.clone_box() } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore/registry/mod.rs
crates/nu-explore/src/explore/registry/mod.rs
mod command; use super::{ commands::{SimpleCommand, ViewCommand}, views::View, }; use anyhow::Result; use std::borrow::Cow; use std::collections::HashMap; pub use command::Command; #[derive(Default, Clone)] pub struct CommandRegistry { commands: HashMap<Cow<'static, str>, Command>, aliases: HashMap<Cow<'static, str>, Cow<'static, str>>, } impl CommandRegistry { pub fn new() -> Self { Self::default() } pub fn register(&mut self, command: Command) { self.commands .insert(Cow::Owned(command.name().to_owned()), command); } pub fn register_command_view<C>(&mut self, command: C, stackable: bool) where C: ViewCommand + Clone + 'static, C::View: View, { self.commands.insert( Cow::Owned(command.name().to_owned()), Command::view(command, stackable), ); } pub fn register_command_reactive<C>(&mut self, command: C) where C: SimpleCommand + Clone + 'static, { self.commands.insert( Cow::Owned(command.name().to_owned()), Command::reactive(command), ); } pub fn create_aliases(&mut self, aliases: &str, command: &str) { self.aliases.insert( Cow::Owned(aliases.to_owned()), Cow::Owned(command.to_owned()), ); } pub fn find(&self, args: &str) -> Option<Result<Command>> { let cmd = args.split_once(' ').map_or(args, |(cmd, _)| cmd); let args = &args[cmd.len()..]; let mut command = self.find_command(cmd)?; if let Err(err) = command.parse(args) { return Some(Err(err)); } Some(Ok(command)) } pub fn get_commands(&self) -> impl Iterator<Item = &Command> { self.commands.values() } pub fn get_aliases(&self) -> impl Iterator<Item = (&str, &str)> { self.aliases .iter() .map(|(key, value)| (key.as_ref(), value.as_ref())) } fn find_command(&self, cmd: &str) -> Option<Command> { match self.commands.get(cmd).cloned() { None => self .aliases .get(cmd) .and_then(|cmd| self.commands.get(cmd).cloned()), cmd => cmd, } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore_regex/app.rs
crates/nu-explore/src/explore_regex/app.rs
//! Application state and logic for the regex explorer. use crate::explore_regex::colors; use crate::explore_regex::quick_ref::{QuickRefEntry, get_flattened_entries}; use fancy_regex::Regex; use ratatui::{ style::Style, text::{Line, Span, Text}, }; use tui_textarea::{CursorMove, TextArea}; /// Which pane currently has input focus. #[derive(Default, Clone, Copy, PartialEq, Eq)] pub enum InputFocus { #[default] Regex, Sample, QuickRef, } /// Main application state for the regex explorer. pub struct App<'a> { pub input_focus: InputFocus, pub regex_textarea: TextArea<'a>, pub sample_textarea: TextArea<'a>, pub compiled_regex: Option<Regex>, pub regex_error: Option<String>, pub sample_scroll_v: u16, pub sample_scroll_h: u16, pub sample_view_height: u16, pub match_count: usize, // Quick reference panel state pub show_quick_ref: bool, pub quick_ref_selected: usize, pub quick_ref_scroll: usize, pub quick_ref_scroll_h: u16, pub quick_ref_view_height: usize, pub quick_ref_view_width: u16, pub quick_ref_entries: Vec<QuickRefEntry>, } impl<'a> App<'a> { pub fn new(input_string: String) -> Self { let mut regex_textarea = TextArea::default(); regex_textarea.set_cursor_line_style(Style::new()); let mut sample_textarea = TextArea::default(); sample_textarea.insert_str(&input_string); sample_textarea.set_cursor_line_style(Style::new()); sample_textarea.move_cursor(CursorMove::Top); let entries = get_flattened_entries(); let initial_selected = Self::find_next_item(&entries, 0).unwrap_or(0); Self { input_focus: InputFocus::default(), regex_textarea, sample_textarea, compiled_regex: None, regex_error: None, sample_scroll_v: 0, sample_scroll_h: 0, sample_view_height: 0, match_count: 0, show_quick_ref: false, quick_ref_selected: initial_selected, quick_ref_scroll: 0, quick_ref_scroll_h: 0, quick_ref_view_height: 0, quick_ref_view_width: 0, quick_ref_entries: entries, } } pub fn get_sample_text(&self) -> String { self.sample_textarea.lines().join("\n") } pub fn get_regex_input(&self) -> String { self.regex_textarea .lines() .first() .cloned() .unwrap_or_default() } pub fn compile_regex(&mut self) { self.compiled_regex = None; self.regex_error = None; self.match_count = 0; let Some(regex_input) = self.regex_textarea.lines().first() else { return; }; if regex_input.is_empty() { return; } match Regex::new(regex_input) { Ok(regex) => { self.compiled_regex = Some(regex); self.update_match_count(); } Err(e) => { self.regex_error = Some(e.to_string()); } } } /// Update match count using the already-compiled regex. /// This is more efficient than `compile_regex()` when only the sample text changes. pub fn update_match_count(&mut self) { if let Some(ref regex) = self.compiled_regex { let sample_text = self.get_sample_text(); self.match_count = regex.captures_iter(&sample_text).flatten().count(); } } /// Generate highlighted text with regex matches styled. pub fn get_highlighted_text(&self) -> Text<'static> { let sample_text = self.get_sample_text(); let Some(regex) = &self.compiled_regex else { return Text::from(sample_text); }; // Collect all match highlights: (start, end, style) let mut highlights: Vec<(usize, usize, Style)> = regex .captures_iter(&sample_text) .flatten() .flat_map(|capture| { capture .iter() .enumerate() .filter_map(|(group, submatch)| { submatch.map(|m| (m.start(), m.end(), colors::highlight_style(group))) }) .collect::<Vec<_>>() }) .collect(); // Add fallback style for unhighlighted text (must be last after sort) highlights.push((0, sample_text.len(), Style::new())); // Sort by span size (smallest first) so inner groups take precedence highlights.sort_by_key(|(start, end, _)| (*end - *start, *start)); // Collect all boundary points and deduplicate let mut boundaries: Vec<usize> = highlights.iter().flat_map(|(s, e, _)| [*s, *e]).collect(); boundaries.sort(); boundaries.dedup(); // Build styled lines, handling newlines properly let mut lines: Vec<Line> = Vec::new(); let mut current_line = Line::from(""); for window in boundaries.windows(2) { let [start, end] = [window[0], window[1]]; // Find the first (smallest) highlight that contains this range let Some((_, _, style)) = highlights.iter().find(|(s, e, _)| *s <= start && *e >= end) else { continue; }; let fragment = &sample_text[start..end]; for (idx, part) in fragment.split('\n').enumerate() { if idx > 0 { lines.push(current_line); current_line = Line::from(""); } if !part.is_empty() { current_line.push_span(Span::styled(part.to_string(), *style)); } } } lines.push(current_line); Text::from(lines) } // ─── Quick Reference Panel ─────────────────────────────────────────── /// Toggle the quick reference panel visibility. pub fn toggle_quick_ref(&mut self) { self.show_quick_ref = !self.show_quick_ref; self.input_focus = if self.show_quick_ref { InputFocus::QuickRef } else { InputFocus::Regex }; } /// Close quick ref panel and return focus to regex input. pub fn close_quick_ref(&mut self) { self.show_quick_ref = false; self.input_focus = InputFocus::Regex; } /// Move selection up in the quick reference list. pub fn quick_ref_up(&mut self) { if let Some(prev) = Self::find_prev_item(&self.quick_ref_entries, self.quick_ref_selected) { self.quick_ref_selected = prev; } } /// Move selection down in the quick reference list. pub fn quick_ref_down(&mut self) { if let Some(next) = Self::find_next_item(&self.quick_ref_entries, self.quick_ref_selected) { self.quick_ref_selected = next; } } /// Move selection up by one page. pub fn quick_ref_page_up(&mut self) { let target = self .quick_ref_selected .saturating_sub(self.quick_ref_view_height.max(1)); // Find the nearest selectable item at or after target self.quick_ref_selected = Self::find_nearest_item(&self.quick_ref_entries, target) .unwrap_or(self.quick_ref_selected); } /// Move selection down by one page. pub fn quick_ref_page_down(&mut self) { let target = (self.quick_ref_selected + self.quick_ref_view_height.max(1)) .min(self.quick_ref_entries.len().saturating_sub(1)); // Find the nearest selectable item at or before target self.quick_ref_selected = Self::find_nearest_item_reverse(&self.quick_ref_entries, target) .unwrap_or(self.quick_ref_selected); } /// Insert the selected quick reference item into the regex input. pub fn insert_selected_quick_ref(&mut self) { if let Some(QuickRefEntry::Item(item)) = self.quick_ref_entries.get(self.quick_ref_selected) { self.regex_textarea.insert_str(item.insert); self.compile_regex(); } } /// Scroll quick reference panel left. pub fn quick_ref_scroll_left(&mut self) { self.quick_ref_scroll_h = self.quick_ref_scroll_h.saturating_sub(4); } /// Scroll quick reference panel right. pub fn quick_ref_scroll_right(&mut self) { self.quick_ref_scroll_h = self.quick_ref_scroll_h.saturating_add(4); } /// Scroll quick reference panel to home (beginning of line). pub fn quick_ref_scroll_home(&mut self) { self.quick_ref_scroll_h = 0; } /// Check if an entry at the given index is selectable (i.e., an Item, not a Category). fn is_selectable(entries: &[QuickRefEntry], idx: usize) -> bool { matches!(entries.get(idx), Some(QuickRefEntry::Item(_))) } /// Find the next selectable item after (not including) the given index. fn find_next_item(entries: &[QuickRefEntry], from: usize) -> Option<usize> { ((from + 1)..entries.len()).find(|&i| Self::is_selectable(entries, i)) } /// Find the previous selectable item before (not including) the given index. fn find_prev_item(entries: &[QuickRefEntry], from: usize) -> Option<usize> { (0..from).rev().find(|&i| Self::is_selectable(entries, i)) } /// Find the nearest selectable item at or after the given index. fn find_nearest_item(entries: &[QuickRefEntry], from: usize) -> Option<usize> { (from..entries.len()).find(|&i| Self::is_selectable(entries, i)) } /// Find the nearest selectable item at or before the given index. fn find_nearest_item_reverse(entries: &[QuickRefEntry], from: usize) -> Option<usize> { (0..=from).rev().find(|&i| Self::is_selectable(entries, i)) } } #[cfg(test)] mod tests { use super::*; use crate::explore_regex::quick_ref::QuickRefItem; /// Create a test entry list with known structure: /// [Category, Item, Item, Category, Item, Category, Item, Item] fn test_entries() -> Vec<QuickRefEntry> { vec![ QuickRefEntry::Category("Cat1"), QuickRefEntry::Item(QuickRefItem { syntax: "a", description: "desc a", insert: "a", }), QuickRefEntry::Item(QuickRefItem { syntax: "b", description: "desc b", insert: "b", }), QuickRefEntry::Category("Cat2"), QuickRefEntry::Item(QuickRefItem { syntax: "c", description: "desc c", insert: "c", }), QuickRefEntry::Category("Cat3"), QuickRefEntry::Item(QuickRefItem { syntax: "d", description: "desc d", insert: "d", }), QuickRefEntry::Item(QuickRefItem { syntax: "e", description: "desc e", insert: "e", }), ] } // ─── is_selectable tests ───────────────────────────────────────────────── #[test] fn test_is_selectable_item() { let entries = test_entries(); assert!(App::is_selectable(&entries, 1)); // Item "a" assert!(App::is_selectable(&entries, 2)); // Item "b" assert!(App::is_selectable(&entries, 4)); // Item "c" } #[test] fn test_is_selectable_category() { let entries = test_entries(); assert!(!App::is_selectable(&entries, 0)); // Category "Cat1" assert!(!App::is_selectable(&entries, 3)); // Category "Cat2" assert!(!App::is_selectable(&entries, 5)); // Category "Cat3" } #[test] fn test_is_selectable_out_of_bounds() { let entries = test_entries(); assert!(!App::is_selectable(&entries, 100)); } #[test] fn test_is_selectable_empty_list() { let entries: Vec<QuickRefEntry> = vec![]; assert!(!App::is_selectable(&entries, 0)); } // ─── find_next_item tests ──────────────────────────────────────────────── #[test] fn test_find_next_item_basic() { let entries = test_entries(); // From item 1, next item is 2 assert_eq!(App::find_next_item(&entries, 1), Some(2)); } #[test] fn test_find_next_item_skips_category() { let entries = test_entries(); // From item 2, next is item 4 (skips category at 3) assert_eq!(App::find_next_item(&entries, 2), Some(4)); } #[test] fn test_find_next_item_from_category() { let entries = test_entries(); // From category 0, next item is 1 assert_eq!(App::find_next_item(&entries, 0), Some(1)); // From category 3, next item is 4 assert_eq!(App::find_next_item(&entries, 3), Some(4)); } #[test] fn test_find_next_item_at_end() { let entries = test_entries(); // From last item (7), no next item assert_eq!(App::find_next_item(&entries, 7), None); } #[test] fn test_find_next_item_empty_list() { let entries: Vec<QuickRefEntry> = vec![]; assert_eq!(App::find_next_item(&entries, 0), None); } // ─── find_prev_item tests ──────────────────────────────────────────────── #[test] fn test_find_prev_item_basic() { let entries = test_entries(); // From item 2, prev item is 1 assert_eq!(App::find_prev_item(&entries, 2), Some(1)); } #[test] fn test_find_prev_item_skips_category() { let entries = test_entries(); // From item 4, prev is item 2 (skips category at 3) assert_eq!(App::find_prev_item(&entries, 4), Some(2)); } #[test] fn test_find_prev_item_from_category() { let entries = test_entries(); // From category 3, prev item is 2 assert_eq!(App::find_prev_item(&entries, 3), Some(2)); // From category 5, prev item is 4 assert_eq!(App::find_prev_item(&entries, 5), Some(4)); } #[test] fn test_find_prev_item_at_start() { let entries = test_entries(); // From first item (1), no prev item (0 is a category) assert_eq!(App::find_prev_item(&entries, 1), None); // From index 0, no prev item assert_eq!(App::find_prev_item(&entries, 0), None); } #[test] fn test_find_prev_item_empty_list() { let entries: Vec<QuickRefEntry> = vec![]; assert_eq!(App::find_prev_item(&entries, 0), None); } // ─── find_nearest_item tests ───────────────────────────────────────────── #[test] fn test_find_nearest_item_on_item() { let entries = test_entries(); // On item 1, nearest is itself assert_eq!(App::find_nearest_item(&entries, 1), Some(1)); } #[test] fn test_find_nearest_item_on_category() { let entries = test_entries(); // On category 0, nearest forward is item 1 assert_eq!(App::find_nearest_item(&entries, 0), Some(1)); // On category 3, nearest forward is item 4 assert_eq!(App::find_nearest_item(&entries, 3), Some(4)); } #[test] fn test_find_nearest_item_past_end() { let entries = test_entries(); assert_eq!(App::find_nearest_item(&entries, 100), None); } #[test] fn test_find_nearest_item_empty_list() { let entries: Vec<QuickRefEntry> = vec![]; assert_eq!(App::find_nearest_item(&entries, 0), None); } // ─── find_nearest_item_reverse tests ───────────────────────────────────── #[test] fn test_find_nearest_item_reverse_on_item() { let entries = test_entries(); // On item 4, nearest reverse is itself assert_eq!(App::find_nearest_item_reverse(&entries, 4), Some(4)); } #[test] fn test_find_nearest_item_reverse_on_category() { let entries = test_entries(); // On category 3, nearest reverse is item 2 assert_eq!(App::find_nearest_item_reverse(&entries, 3), Some(2)); // On category 5, nearest reverse is item 4 assert_eq!(App::find_nearest_item_reverse(&entries, 5), Some(4)); } #[test] fn test_find_nearest_item_reverse_at_start_category() { let entries = test_entries(); // On category 0, no item before or at assert_eq!(App::find_nearest_item_reverse(&entries, 0), None); } #[test] fn test_find_nearest_item_reverse_empty_list() { let entries: Vec<QuickRefEntry> = vec![]; assert_eq!(App::find_nearest_item_reverse(&entries, 0), None); } // ─── Navigation method tests (quick_ref_up/down) ───────────────────────── #[test] fn test_quick_ref_down_moves_to_next_item() { let mut app = create_test_app(); app.quick_ref_selected = 1; // Start at item "a" app.quick_ref_down(); assert_eq!(app.quick_ref_selected, 2); // Moved to item "b" } #[test] fn test_quick_ref_down_skips_category() { let mut app = create_test_app(); app.quick_ref_selected = 2; // Start at item "b" app.quick_ref_down(); assert_eq!(app.quick_ref_selected, 4); // Skipped category, moved to item "c" } #[test] fn test_quick_ref_down_stays_at_last_item() { let mut app = create_test_app(); app.quick_ref_selected = 7; // Start at last item "e" app.quick_ref_down(); assert_eq!(app.quick_ref_selected, 7); // Stayed at last item } #[test] fn test_quick_ref_up_moves_to_prev_item() { let mut app = create_test_app(); app.quick_ref_selected = 2; // Start at item "b" app.quick_ref_up(); assert_eq!(app.quick_ref_selected, 1); // Moved to item "a" } #[test] fn test_quick_ref_up_skips_category() { let mut app = create_test_app(); app.quick_ref_selected = 4; // Start at item "c" app.quick_ref_up(); assert_eq!(app.quick_ref_selected, 2); // Skipped category, moved to item "b" } #[test] fn test_quick_ref_up_stays_at_first_item() { let mut app = create_test_app(); app.quick_ref_selected = 1; // Start at first item "a" app.quick_ref_up(); assert_eq!(app.quick_ref_selected, 1); // Stayed at first item } // ─── Page navigation tests ─────────────────────────────────────────────── #[test] fn test_quick_ref_page_down() { let mut app = create_test_app(); app.quick_ref_selected = 1; // Start at item "a" app.quick_ref_view_height = 3; // Page size of 3 app.quick_ref_page_down(); // Target would be index 4, which is item "c" assert_eq!(app.quick_ref_selected, 4); } #[test] fn test_quick_ref_page_down_lands_on_category() { let mut app = create_test_app(); app.quick_ref_selected = 1; // Start at item "a" app.quick_ref_view_height = 2; // Page size of 2 app.quick_ref_page_down(); // Target would be index 3 (category), should find nearest item at or before: 2 assert_eq!(app.quick_ref_selected, 2); } #[test] fn test_quick_ref_page_down_at_end() { let mut app = create_test_app(); app.quick_ref_selected = 7; // Start at last item "e" app.quick_ref_view_height = 3; app.quick_ref_page_down(); // Should stay at last item assert_eq!(app.quick_ref_selected, 7); } #[test] fn test_quick_ref_page_up() { let mut app = create_test_app(); app.quick_ref_selected = 7; // Start at item "e" app.quick_ref_view_height = 3; // Page size of 3 app.quick_ref_page_up(); // Target would be index 4, which is item "c" assert_eq!(app.quick_ref_selected, 4); } #[test] fn test_quick_ref_page_up_lands_on_category() { let mut app = create_test_app(); app.quick_ref_selected = 6; // Start at item "d" app.quick_ref_view_height = 3; // Page size of 3 app.quick_ref_page_up(); // Target would be index 3 (category), should find nearest item at or after: 4 assert_eq!(app.quick_ref_selected, 4); } #[test] fn test_quick_ref_page_up_at_start() { let mut app = create_test_app(); app.quick_ref_selected = 1; // Start at first item "a" app.quick_ref_view_height = 3; app.quick_ref_page_up(); // Should stay at first item assert_eq!(app.quick_ref_selected, 1); } #[test] fn test_quick_ref_page_navigation_with_zero_height() { let mut app = create_test_app(); app.quick_ref_selected = 2; app.quick_ref_view_height = 0; // Edge case: zero height app.quick_ref_page_down(); // Should use height of 1, so move by 1 // From 2, target is 3 (category), nearest at or before is 2 assert_eq!(app.quick_ref_selected, 2); } // ─── Horizontal scroll tests ───────────────────────────────────────────── #[test] fn test_quick_ref_scroll_right() { let mut app = create_test_app(); assert_eq!(app.quick_ref_scroll_h, 0); app.quick_ref_scroll_right(); assert_eq!(app.quick_ref_scroll_h, 4); app.quick_ref_scroll_right(); assert_eq!(app.quick_ref_scroll_h, 8); } #[test] fn test_quick_ref_scroll_left() { let mut app = create_test_app(); app.quick_ref_scroll_h = 8; app.quick_ref_scroll_left(); assert_eq!(app.quick_ref_scroll_h, 4); app.quick_ref_scroll_left(); assert_eq!(app.quick_ref_scroll_h, 0); } #[test] fn test_quick_ref_scroll_left_at_zero() { let mut app = create_test_app(); assert_eq!(app.quick_ref_scroll_h, 0); app.quick_ref_scroll_left(); assert_eq!(app.quick_ref_scroll_h, 0); // Should not underflow } #[test] fn test_quick_ref_scroll_home() { let mut app = create_test_app(); app.quick_ref_scroll_h = 20; app.quick_ref_scroll_home(); assert_eq!(app.quick_ref_scroll_h, 0); } #[test] fn test_quick_ref_scroll_home_already_at_zero() { let mut app = create_test_app(); assert_eq!(app.quick_ref_scroll_h, 0); app.quick_ref_scroll_home(); assert_eq!(app.quick_ref_scroll_h, 0); } // ─── Unicode handling tests ─────────────────────────────────────────────── #[test] fn test_compile_regex_with_unicode_pattern() { let mut app = App::new(String::new()); app.regex_textarea = TextArea::new(vec!["\\p{L}+".to_string()]); app.compile_regex(); assert!(app.compiled_regex.is_some()); assert!(app.regex_error.is_none()); } #[test] fn test_get_highlighted_text_with_unicode_sample() { let mut app = App::new("12345abcde項目".to_string()); app.regex_textarea = TextArea::new(vec!["\\w+".to_string()]); app.compile_regex(); let highlighted = app.get_highlighted_text(); // Should not panic and should produce some text assert!(!highlighted.lines.is_empty()); } // ─── Helper ────────────────────────────────────────────────────────────── fn create_test_app() -> App<'static> { let mut app = App::new(String::new()); app.quick_ref_entries = test_entries(); app.quick_ref_selected = 1; // Default to first item app.quick_ref_view_height = 5; app } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore_regex/command.rs
crates/nu-explore/src/explore_regex/command.rs
//! The explore regex command implementation. // Borrowed from the ut project and tweaked. Thanks! // https://github.com/ksdme/ut // Below is the ut license: // MIT License // // Copyright (c) 2025 Kilari Teja // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. use crate::explore_regex::app::App; use crate::explore_regex::ui::run_app_loop; use nu_engine::command_prelude::*; use ratatui::{ Terminal, backend::CrosstermBackend, crossterm::{ event::{DisableMouseCapture, EnableMouseCapture}, execute, terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode}, }, }; use std::io; /// A `regular expression explorer` program. #[derive(Clone)] pub struct ExploreRegex; impl Command for ExploreRegex { fn name(&self) -> &str { "explore regex" } fn description(&self) -> &str { "Launch a TUI to create and explore regular expressions interactively." } fn signature(&self) -> nu_protocol::Signature { Signature::build("explore regex") .input_output_types(vec![ (Type::Nothing, Type::String), (Type::String, Type::String), ]) .category(Category::Viewers) } fn extra_description(&self) -> &str { r#"Press `Ctrl-Q` to quit and provide constructed regular expression as the output."# } fn run( &self, _engine_state: &EngineState, _stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let input_span = input.span().unwrap_or(call.head); let (string_input, _span, _metadata) = input.collect_string_strict(input_span)?; let regex = execute_regex_app(call.head, string_input)?; Ok(PipelineData::Value( nu_protocol::Value::string(regex, call.head), None, )) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Explore a regular expression interactively", example: r#"explore regex"#, result: None, }, Example { description: "Explore a regular expression interactively with sample text", example: r#"open -r Cargo.toml | explore regex"#, result: None, }, ] } } /// Converts a terminal/IO error into a ShellError with consistent formatting. fn terminal_error(error: &str, cause: impl std::fmt::Display, span: Span) -> ShellError { ShellError::GenericError { error: error.into(), msg: format!("terminal error: {cause}"), span: Some(span), help: None, inner: vec![], } } fn execute_regex_app(span: Span, string_input: String) -> Result<String, ShellError> { let mut terminal = setup_terminal(span)?; let mut app = App::new(string_input); let result = run_app_loop(&mut terminal, &mut app); // Always attempt to restore terminal, even if app loop failed let restore_result = restore_terminal(&mut terminal, span); // Propagate app loop error first, then restore error result.map_err(|e| terminal_error("Application error", e, span))?; restore_result?; Ok(app.get_regex_input()) } fn setup_terminal(span: Span) -> Result<Terminal<CrosstermBackend<io::Stdout>>, ShellError> { enable_raw_mode().map_err(|e| terminal_error("Could not enable raw mode", e, span))?; let mut stdout = io::stdout(); execute!(stdout, EnterAlternateScreen, EnableMouseCapture) .map_err(|e| terminal_error("Could not enter alternate screen", e, span))?; Terminal::new(CrosstermBackend::new(stdout)) .map_err(|e| terminal_error("Could not initialize terminal", e, span)) } fn restore_terminal( terminal: &mut Terminal<CrosstermBackend<io::Stdout>>, span: Span, ) -> Result<(), ShellError> { disable_raw_mode().map_err(|e| terminal_error("Could not disable raw mode", e, span))?; execute!( terminal.backend_mut(), LeaveAlternateScreen, DisableMouseCapture ) .map_err(|e| terminal_error("Could not leave alternate screen", e, span))?; terminal .show_cursor() .map_err(|e| terminal_error("Could not show terminal cursor", e, span)) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore_regex/mod.rs
crates/nu-explore/src/explore_regex/mod.rs
//! Explore regex TUI - an interactive regular expression explorer. //! //! This module provides the `explore regex` command which launches a TUI //! for creating and testing regular expressions interactively. mod app; mod colors; mod command; pub mod quick_ref; mod ui; pub use command::ExploreRegex;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore_regex/ui.rs
crates/nu-explore/src/explore_regex/ui.rs
//! UI drawing functions and application loop for the regex explorer. use crate::explore_regex::app::{App, InputFocus}; use crate::explore_regex::colors::styles; use crate::explore_regex::quick_ref::QuickRefEntry; use ratatui::{ Terminal, backend::CrosstermBackend, crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers}, layout::{Alignment, Constraint, Direction, Layout, Rect}, style::{Modifier, Style}, text::{Line, Span}, widgets::{ Block, BorderType, Borders, Padding, Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState, }, }; use std::io::{self, Stdout}; use tui_textarea::{CursorMove, Input}; use unicode_segmentation::UnicodeSegmentation; use unicode_width::UnicodeWidthStr; // ─── Key Action Handling ───────────────────────────────────────────────────── /// Actions that can be triggered by keyboard input. enum KeyAction { Quit, ToggleQuickRef, SwitchFocus, FocusRegex, QuickRefUp, QuickRefDown, QuickRefPageUp, QuickRefPageDown, QuickRefLeft, QuickRefRight, QuickRefHome, QuickRefInsert, SamplePageUp, SamplePageDown, TextInput(Input), None, } /// Determine the action for a key event based on current app state. fn determine_action(app: &App, key: &event::KeyEvent) -> KeyAction { // Global shortcuts if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('q') { return KeyAction::Quit; } if key.code == KeyCode::F(1) { return KeyAction::ToggleQuickRef; } // Quick reference panel navigation if app.show_quick_ref && app.input_focus == InputFocus::QuickRef { return match key.code { KeyCode::Up | KeyCode::Char('k') => KeyAction::QuickRefUp, KeyCode::Down | KeyCode::Char('j') => KeyAction::QuickRefDown, KeyCode::PageUp => KeyAction::QuickRefPageUp, KeyCode::PageDown => KeyAction::QuickRefPageDown, KeyCode::Left | KeyCode::Char('h') => KeyAction::QuickRefLeft, KeyCode::Right | KeyCode::Char('l') => KeyAction::QuickRefRight, KeyCode::Home => KeyAction::QuickRefHome, KeyCode::Enter => KeyAction::QuickRefInsert, KeyCode::Esc | KeyCode::Tab | KeyCode::BackTab => KeyAction::FocusRegex, _ => KeyAction::None, }; } // Focus switching if matches!(key.code, KeyCode::Tab | KeyCode::BackTab) { return KeyAction::SwitchFocus; } if key.code == KeyCode::Esc { return KeyAction::FocusRegex; } // Sample pane page navigation if app.input_focus == InputFocus::Sample { match key.code { KeyCode::PageUp => return KeyAction::SamplePageUp, KeyCode::PageDown => return KeyAction::SamplePageDown, _ => {} } } // Default: pass to text input KeyAction::TextInput(Input::from(Event::Key(*key))) } /// Execute a key action, modifying app state. fn execute_action(app: &mut App, action: KeyAction) -> bool { match action { KeyAction::Quit => return true, KeyAction::ToggleQuickRef => app.toggle_quick_ref(), KeyAction::SwitchFocus => { app.input_focus = match app.input_focus { InputFocus::Regex => InputFocus::Sample, InputFocus::Sample | InputFocus::QuickRef => InputFocus::Regex, }; } KeyAction::FocusRegex => { if app.show_quick_ref && app.input_focus == InputFocus::QuickRef { app.close_quick_ref(); } else { app.input_focus = InputFocus::Regex; } } KeyAction::QuickRefUp => app.quick_ref_up(), KeyAction::QuickRefDown => app.quick_ref_down(), KeyAction::QuickRefPageUp => app.quick_ref_page_up(), KeyAction::QuickRefPageDown => app.quick_ref_page_down(), KeyAction::QuickRefLeft => app.quick_ref_scroll_left(), KeyAction::QuickRefRight => app.quick_ref_scroll_right(), KeyAction::QuickRefHome => app.quick_ref_scroll_home(), KeyAction::QuickRefInsert => app.insert_selected_quick_ref(), KeyAction::SamplePageUp | KeyAction::SamplePageDown => { handle_sample_page_navigation(app, matches!(action, KeyAction::SamplePageDown)); } KeyAction::TextInput(input) => handle_text_input(app, input), KeyAction::None => {} } false } fn handle_sample_page_navigation(app: &mut App, page_down: bool) { let page = app.sample_view_height.max(1); let (row, col) = app.sample_textarea.cursor(); let max_row = app.sample_textarea.lines().len().saturating_sub(1) as u16; let target_row = if page_down { (row as u16).saturating_add(page).min(max_row) } else { (row as u16).saturating_sub(page) }; app.sample_textarea .move_cursor(CursorMove::Jump(target_row, col as u16)); } fn handle_text_input(app: &mut App, input: Input) { match app.input_focus { InputFocus::Regex => { app.regex_textarea.input(input); app.compile_regex(); } InputFocus::Sample => { let old_text = app.get_sample_text(); app.sample_textarea.input(input); if app.get_sample_text() != old_text { app.update_match_count(); } } InputFocus::QuickRef => {} } } // ─── Main Loop ─────────────────────────────────────────────────────────────── pub fn run_app_loop( terminal: &mut Terminal<CrosstermBackend<Stdout>>, app: &mut App, ) -> io::Result<()> { loop { terminal.draw(|f| draw_ui(f, app))?; let Event::Key(key) = event::read()? else { continue; }; if key.kind != KeyEventKind::Press { continue; } let action = determine_action(app, &key); if execute_action(app, action) { return Ok(()); } } } // ─── UI Drawing ────────────────────────────────────────────────────────────── fn draw_ui(f: &mut ratatui::Frame, app: &mut App) { let outer_block = Block::default() .borders(Borders::ALL) .border_type(BorderType::Rounded) .border_style(styles::border_unfocused()) .title(Line::from(vec![Span::styled( " Regex Explorer ", styles::focused(), )])) .title_alignment(Alignment::Left); let inner_area = outer_block.inner(f.area()); f.render_widget(outer_block, f.area()); if app.show_quick_ref { let chunks = Layout::default() .direction(Direction::Horizontal) .constraints([Constraint::Min(40), Constraint::Length(40)]) .split(inner_area); draw_main_content(f, app, chunks[0]); draw_quick_ref_panel(f, app, chunks[1]); } else { draw_main_content(f, app, inner_area); } } fn draw_main_content(f: &mut ratatui::Frame, app: &mut App, area: Rect) { let chunks = Layout::default() .direction(Direction::Vertical) .constraints([ Constraint::Length(1), // Spacer Constraint::Length(1), // Regex label Constraint::Length(3), // Regex input Constraint::Length(1), // Spacer Constraint::Length(1), // Sample label Constraint::Min(6), // Sample Constraint::Length(1), // Spacer Constraint::Length(1), // Help ]) .horizontal_margin(2) .split(area); draw_regex_section(f, app, chunks[1], chunks[2]); draw_sample_section(f, app, chunks[4], chunks[5]); draw_help(f, app, chunks[7]); } // ─── Section Drawing Helpers ───────────────────────────────────────────────── fn draw_regex_section(f: &mut ratatui::Frame, app: &mut App, label_area: Rect, input_area: Rect) { let focused = app.input_focus == InputFocus::Regex; // Label with status let status = match (&app.regex_error, &app.compiled_regex) { (Some(_), _) => Some(("invalid", styles::status_error())), (None, Some(_)) => Some(("valid", styles::status_success())), _ => None, }; let label = build_label( "Regex Pattern", focused, status.map(|(t, s)| (t.to_string(), s)), ); f.render_widget(Paragraph::new(label), label_area); // Input block let border_style = if focused { if app.regex_error.is_some() { styles::border_error() } else { styles::border_focused() } } else { styles::border_unfocused() }; let block = Block::default() .borders(Borders::ALL) .border_type(BorderType::Rounded) .border_style(border_style) .padding(Padding::horizontal(1)); app.regex_textarea.set_block(block); app.regex_textarea.set_cursor_style(if focused { styles::cursor_active() } else { styles::cursor_hidden() }); f.render_widget(&app.regex_textarea, input_area); } fn draw_sample_section( f: &mut ratatui::Frame, app: &mut App, label_area: Rect, content_area: Rect, ) { let focused = app.input_focus == InputFocus::Sample; // Label with match count let status: Option<(String, Style)> = if app.match_count > 0 { let text = if app.match_count == 1 { "1 match".to_string() } else { format!("{} matches", app.match_count) }; Some((text, styles::separator())) } else if app.compiled_regex.is_some() { Some(("no matches".to_string(), styles::status_warning())) } else { None }; let label = build_label("Test String", focused, status); f.render_widget(Paragraph::new(label), label_area); // Sample block let block = Block::default() .borders(Borders::ALL) .border_type(BorderType::Rounded) .border_style(if focused { styles::border_focused() } else { styles::border_unfocused() }) .padding(Padding::horizontal(1)); let content = block.inner(content_area); app.sample_view_height = content.height; // Handle scrolling if focused { update_sample_scroll(app, content); } let text = app.get_highlighted_text(); let paragraph = Paragraph::new(text) .scroll((app.sample_scroll_v, app.sample_scroll_h)) .block(block); f.render_widget(paragraph, content_area); // Draw cursor if focused { draw_sample_cursor(f, app, content); } } fn update_sample_scroll(app: &mut App, content: Rect) { let (cursor_row, cursor_col) = app.sample_textarea.cursor(); let line = &app.sample_textarea.lines()[cursor_row]; let cursor_display_col = line .graphemes(true) .take(cursor_col) .map(|g| g.width()) .sum::<usize>() as u16; let cursor_row_u16 = cursor_row as u16; // Vertical scrolling if cursor_row_u16 < app.sample_scroll_v { app.sample_scroll_v = cursor_row_u16; } else if cursor_row_u16 >= app.sample_scroll_v + content.height { app.sample_scroll_v = cursor_row_u16 - content.height + 1; } // Horizontal scrolling if cursor_display_col < app.sample_scroll_h { app.sample_scroll_h = cursor_display_col; } else if cursor_display_col >= app.sample_scroll_h + content.width { app.sample_scroll_h = cursor_display_col - content.width + 1; } } fn draw_sample_cursor(f: &mut ratatui::Frame, app: &App, content: Rect) { let buf = f.buffer_mut(); let (cursor_row, cursor_col) = app.sample_textarea.cursor(); let line = &app.sample_textarea.lines()[cursor_row]; let prefix_width = line .graphemes(true) .take(cursor_col) .map(|g| g.width()) .sum::<usize>() as u16; let cursor_x = content.x + prefix_width - app.sample_scroll_h; let cursor_y = content.y + (cursor_row as u16) - app.sample_scroll_v; let grapheme_count = line.graphemes(true).count(); let is_eol = cursor_col == grapheme_count; let grapheme_width = if is_eol { 1 } else { line.graphemes(true) .nth(cursor_col) .map(|g| g.width()) .unwrap_or(1) }; for i in 0..grapheme_width { if let Some(cell) = buf.cell_mut((cursor_x + i as u16, cursor_y)) { if is_eol { cell.set_symbol(" "); } cell.set_style(cell.style().add_modifier(Modifier::REVERSED)); } } } // ─── Label Building Helpers ────────────────────────────────────────────────── /// Build a label line with optional status badge. fn build_label( title: &str, focused: bool, status: Option<(impl Into<String>, Style)>, ) -> Line<'static> { let mut spans = if focused { vec![ Span::styled("> ", styles::focus_indicator()), Span::styled(title.to_string(), styles::focused()), ] } else { vec![ Span::styled(" ", styles::unfocused()), Span::styled(title.to_string(), styles::unfocused()), ] }; if let Some((text, style)) = status { spans.push(Span::styled(" [", styles::status_bracket())); spans.push(Span::styled(text.into(), style)); spans.push(Span::styled("]", styles::status_bracket())); } Line::from(spans) } // ─── Help Bar ──────────────────────────────────────────────────────────────── fn draw_help(f: &mut ratatui::Frame, app: &App, area: Rect) { let sep = Span::styled(" • ", styles::separator()); let mut spans = vec![ help_key("Tab"), help_desc(" Switch Focus"), sep.clone(), help_key("Esc"), help_desc(" Focus Regex"), sep.clone(), help_key("F1"), help_desc(if app.show_quick_ref { " Hide Quick Ref" } else { " Quick Ref" }), sep.clone(), help_key("Ctrl+Q"), help_desc(" Exit"), ]; if app.show_quick_ref && app.input_focus == InputFocus::QuickRef { spans.push(sep); spans.push(help_key("↑↓")); spans.push(help_desc(" Navigate")); spans.push(Span::styled(" ", styles::separator())); spans.push(help_key("←→")); spans.push(help_desc(" Scroll")); spans.push(Span::styled(" ", styles::separator())); spans.push(help_key("Enter")); spans.push(help_desc(" Insert")); } f.render_widget(Paragraph::new(Line::from(spans)), area); } fn help_key(text: &str) -> Span<'static> { Span::styled(text.to_string(), styles::focused()) } fn help_desc(text: &str) -> Span<'static> { Span::styled(text.to_string(), styles::separator()) } // ─── Quick Reference Panel ─────────────────────────────────────────────────── fn draw_quick_ref_panel(f: &mut ratatui::Frame, app: &mut App, area: Rect) { let focused = app.input_focus == InputFocus::QuickRef; let block = Block::default() .borders(Borders::ALL) .border_type(BorderType::Rounded) .border_style(if focused { styles::border_focused() } else { styles::border_unfocused() }) .title(Line::from(vec![Span::styled( " Quick Reference ", styles::focused(), )])) .title_alignment(Alignment::Center) .padding(Padding::horizontal(1)); let inner = block.inner(area); f.render_widget(block, area); let visible_height = inner.height as usize; let visible_width = inner.width; app.quick_ref_view_height = visible_height; app.quick_ref_view_width = visible_width; // Adjust scroll to keep selected visible if app.quick_ref_selected < app.quick_ref_scroll { app.quick_ref_scroll = app.quick_ref_selected; } else if app.quick_ref_selected >= app.quick_ref_scroll + visible_height { app.quick_ref_scroll = app.quick_ref_selected - visible_height + 1; } // Build content lines let lines: Vec<Line> = app .quick_ref_entries .iter() .enumerate() .skip(app.quick_ref_scroll) .take(visible_height) .map(|(idx, entry)| build_quick_ref_line(entry, idx, app.quick_ref_selected, focused)) .collect(); let paragraph = Paragraph::new(lines).scroll((0, app.quick_ref_scroll_h)); f.render_widget(paragraph, inner); // Scrollbar if app.quick_ref_entries.len() > visible_height { draw_scrollbar(f, area, app.quick_ref_entries.len(), app.quick_ref_scroll); } } fn build_quick_ref_line( entry: &QuickRefEntry, idx: usize, selected: usize, focused: bool, ) -> Line<'static> { const SYNTAX_WIDTH: usize = 14; match entry { QuickRefEntry::Category(name) => Line::from(vec![Span::styled( format!("─ {} ─────────────────────────────────────", name), styles::category_header(), )]), QuickRefEntry::Item(item) => { let is_selected = idx == selected && focused; let syntax = format!("{:<width$}", item.syntax, width = SYNTAX_WIDTH); if is_selected { Line::from(vec![ Span::styled(syntax, styles::selected_bold()), Span::styled(" ", styles::selected()), Span::styled(item.description.to_string(), styles::selected()), // Extra padding for smooth horizontal scrolling Span::styled(" ", styles::selected()), ]) } else { Line::from(vec![ Span::styled(syntax, styles::focused()), Span::styled(" ", styles::unfocused()), Span::styled(item.description.to_string(), styles::unfocused()), ]) } } } } fn draw_scrollbar(f: &mut ratatui::Frame, area: Rect, total: usize, position: usize) { let scrollbar = Scrollbar::new(ScrollbarOrientation::VerticalRight) .begin_symbol(Some("↑")) .end_symbol(Some("↓")); let mut state = ScrollbarState::new(total).position(position); let scrollbar_area = Rect { x: area.x + area.width - 2, y: area.y + 1, width: 1, height: area.height.saturating_sub(2), }; f.render_stateful_widget(scrollbar, scrollbar_area, &mut state); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore_regex/quick_ref.rs
crates/nu-explore/src/explore_regex/quick_ref.rs
//! Quick reference data for the regex explorer. //! //! This module provides categorized regex patterns compatible with the //! fancy-regex crate, similar to regex101.com's quick reference panel. /// A single quick reference item #[derive(Clone)] pub struct QuickRefItem { /// The pattern syntax to display (e.g., "\\d") pub syntax: &'static str, /// Description of what the pattern matches pub description: &'static str, /// The actual pattern to insert (may differ from syntax for display purposes) pub insert: &'static str, } /// A category of quick reference items pub struct QuickRefCategory { pub name: &'static str, pub items: &'static [QuickRefItem], } /// All quick reference categories - patterns are compatible with fancy-regex pub static QUICK_REF_CATEGORIES: &[QuickRefCategory] = &[ QuickRefCategory { name: "Anchors", items: &[ QuickRefItem { syntax: "^", description: "Start of string/line", insert: "^", }, QuickRefItem { syntax: "$", description: "End of string/line", insert: "$", }, QuickRefItem { syntax: "\\b", description: "Word boundary", insert: "\\b", }, QuickRefItem { syntax: "\\B", description: "Not a word boundary", insert: "\\B", }, QuickRefItem { syntax: "\\A", description: "Start of string only", insert: "\\A", }, QuickRefItem { syntax: "\\z", description: "End of string only", insert: "\\z", }, QuickRefItem { syntax: "\\Z", description: "End before trailing newlines", insert: "\\Z", }, QuickRefItem { syntax: "\\G", description: "Where previous match ended", insert: "\\G", }, ], }, QuickRefCategory { name: "Character Classes", items: &[ QuickRefItem { syntax: ".", description: "Any character except newline", insert: ".", }, QuickRefItem { syntax: "\\O", description: "Any character including newline", insert: "\\O", }, QuickRefItem { syntax: "\\d", description: "Digit [0-9]", insert: "\\d", }, QuickRefItem { syntax: "\\D", description: "Not a digit [^0-9]", insert: "\\D", }, QuickRefItem { syntax: "\\w", description: "Word character [a-zA-Z0-9_]", insert: "\\w", }, QuickRefItem { syntax: "\\W", description: "Not a word character", insert: "\\W", }, QuickRefItem { syntax: "\\s", description: "Whitespace character", insert: "\\s", }, QuickRefItem { syntax: "\\S", description: "Not a whitespace character", insert: "\\S", }, QuickRefItem { syntax: "\\h", description: "Hex digit [0-9A-Fa-f]", insert: "\\h", }, QuickRefItem { syntax: "\\H", description: "Not a hex digit", insert: "\\H", }, QuickRefItem { syntax: "[abc]", description: "Any of a, b, or c", insert: "[abc]", }, QuickRefItem { syntax: "[^abc]", description: "Not a, b, or c", insert: "[^abc]", }, QuickRefItem { syntax: "[a-z]", description: "Character range a-z", insert: "[a-z]", }, QuickRefItem { syntax: "[A-Z]", description: "Character range A-Z", insert: "[A-Z]", }, QuickRefItem { syntax: "[0-9]", description: "Character range 0-9", insert: "[0-9]", }, ], }, QuickRefCategory { name: "Quantifiers", items: &[ QuickRefItem { syntax: "*", description: "0 or more (greedy)", insert: "*", }, QuickRefItem { syntax: "+", description: "1 or more (greedy)", insert: "+", }, QuickRefItem { syntax: "?", description: "0 or 1 (greedy)", insert: "?", }, QuickRefItem { syntax: "{n}", description: "Exactly n times", insert: "{1}", }, QuickRefItem { syntax: "{n,}", description: "n or more times", insert: "{1,}", }, QuickRefItem { syntax: "{n,m}", description: "Between n and m times", insert: "{1,3}", }, QuickRefItem { syntax: "*?", description: "0 or more (lazy)", insert: "*?", }, QuickRefItem { syntax: "+?", description: "1 or more (lazy)", insert: "+?", }, QuickRefItem { syntax: "??", description: "0 or 1 (lazy)", insert: "??", }, QuickRefItem { syntax: "{n,m}?", description: "Between n and m (lazy)", insert: "{1,3}?", }, ], }, QuickRefCategory { name: "Groups & Capturing", items: &[ QuickRefItem { syntax: "(...)", description: "Capturing group", insert: "()", }, QuickRefItem { syntax: "(?:...)", description: "Non-capturing group", insert: "(?:)", }, QuickRefItem { syntax: "(?<name>...)", description: "Named capturing group", insert: "(?<name>)", }, QuickRefItem { syntax: "(?P<name>...)", description: "Named group (Python style)", insert: "(?P<name>)", }, QuickRefItem { syntax: "(?>...)", description: "Atomic group (no backtrack)", insert: "(?>)", }, QuickRefItem { syntax: "\\1", description: "Backreference to group 1", insert: "\\1", }, QuickRefItem { syntax: "\\k<name>", description: "Backreference to named group", insert: "\\k<name>", }, QuickRefItem { syntax: "(?P=name)", description: "Named backref (Python style)", insert: "(?P=name)", }, QuickRefItem { syntax: "a|b", description: "Match a or b (alternation)", insert: "|", }, ], }, QuickRefCategory { name: "Lookaround", items: &[ QuickRefItem { syntax: "(?=...)", description: "Positive lookahead", insert: "(?=)", }, QuickRefItem { syntax: "(?!...)", description: "Negative lookahead", insert: "(?!)", }, QuickRefItem { syntax: "(?<=...)", description: "Positive lookbehind", insert: "(?<=)", }, QuickRefItem { syntax: "(?<!...)", description: "Negative lookbehind", insert: "(?<!)", }, ], }, QuickRefCategory { name: "Conditionals", items: &[ QuickRefItem { syntax: "(?(1)yes|no)", description: "If group 1 matched", insert: "(?(1)|)", }, QuickRefItem { syntax: "(?(<n>)yes|no)", description: "If named group matched", insert: "(?(<name>)|)", }, ], }, QuickRefCategory { name: "Special", items: &[ QuickRefItem { syntax: "\\K", description: "Reset match start", insert: "\\K", }, QuickRefItem { syntax: "\\e", description: "Escape character (\\x1B)", insert: "\\e", }, ], }, QuickRefCategory { name: "Escape Sequences", items: &[ QuickRefItem { syntax: "\\n", description: "Newline", insert: "\\n", }, QuickRefItem { syntax: "\\r", description: "Carriage return", insert: "\\r", }, QuickRefItem { syntax: "\\t", description: "Tab", insert: "\\t", }, QuickRefItem { syntax: "\\xHH", description: "Hex character code", insert: "\\x00", }, QuickRefItem { syntax: "\\u{HHHH}", description: "Unicode code point", insert: "\\u{0000}", }, QuickRefItem { syntax: "\\\\", description: "Literal backslash", insert: "\\\\", }, QuickRefItem { syntax: "\\.", description: "Literal dot", insert: "\\.", }, QuickRefItem { syntax: "\\*", description: "Literal asterisk", insert: "\\*", }, QuickRefItem { syntax: "\\+", description: "Literal plus", insert: "\\+", }, QuickRefItem { syntax: "\\?", description: "Literal question mark", insert: "\\?", }, QuickRefItem { syntax: "\\^", description: "Literal caret", insert: "\\^", }, QuickRefItem { syntax: "\\$", description: "Literal dollar", insert: "\\$", }, QuickRefItem { syntax: "\\[", description: "Literal bracket", insert: "\\[", }, QuickRefItem { syntax: "\\(", description: "Literal parenthesis", insert: "\\(", }, QuickRefItem { syntax: "\\{", description: "Literal brace", insert: "\\{", }, QuickRefItem { syntax: "\\|", description: "Literal pipe", insert: "\\|", }, ], }, QuickRefCategory { name: "Flags/Modifiers", items: &[ QuickRefItem { syntax: "(?i)", description: "Case insensitive", insert: "(?i)", }, QuickRefItem { syntax: "(?m)", description: "Multiline (^ $ match lines)", insert: "(?m)", }, QuickRefItem { syntax: "(?s)", description: "Dotall (. matches newlines)", insert: "(?s)", }, QuickRefItem { syntax: "(?x)", description: "Extended (ignore whitespace)", insert: "(?x)", }, QuickRefItem { syntax: "(?-i)", description: "Disable case insensitive", insert: "(?-i)", }, QuickRefItem { syntax: "(?im)", description: "Multiple flags", insert: "(?im)", }, QuickRefItem { syntax: "(?i:...)", description: "Flags for group only", insert: "(?i:)", }, ], }, QuickRefCategory { name: "Common Patterns", items: &[ QuickRefItem { syntax: "\\d+", description: "One or more digits", insert: "\\d+", }, QuickRefItem { syntax: "\\w+", description: "One or more word chars", insert: "\\w+", }, QuickRefItem { syntax: "\\S+", description: "One or more non-whitespace", insert: "\\S+", }, QuickRefItem { syntax: ".*", description: "Any characters (greedy)", insert: ".*", }, QuickRefItem { syntax: ".*?", description: "Any characters (lazy)", insert: ".*?", }, QuickRefItem { syntax: "^.*$", description: "Entire line", insert: "^.*$", }, QuickRefItem { syntax: "(\\w+) \\1", description: "Repeated word", insert: "(\\w+) \\1", }, QuickRefItem { syntax: "(?<!\\S)", description: "Start of word (lookbehind)", insert: "(?<!\\S)", }, QuickRefItem { syntax: "(?!\\S)", description: "End of word (lookahead)", insert: "(?!\\S)", }, ], }, ]; /// Represents a flattened entry (either a category header or an item) #[derive(Clone)] pub enum QuickRefEntry { Category(&'static str), Item(QuickRefItem), } /// Get a flattened list of all entries (headers and items) pub fn get_flattened_entries() -> Vec<QuickRefEntry> { let mut entries = Vec::new(); for category in QUICK_REF_CATEGORIES { entries.push(QuickRefEntry::Category(category.name)); for item in category.items { entries.push(QuickRefEntry::Item(item.clone())); } } entries } #[cfg(test)] mod tests { use super::*; use fancy_regex::Regex; #[test] fn test_all_quick_ref_patterns_are_valid() { // Patterns that are meant to be combined with other patterns // (they are partial/templates and won't compile on their own) let partial_patterns = [ "*", // quantifier, needs something before it "+", // quantifier, needs something before it "?", // quantifier, needs something before it "{1}", // quantifier, needs something before it "{1,}", // quantifier, needs something before it "{1,3}", // quantifier, needs something before it "*?", // lazy quantifier, needs something before it "+?", // lazy quantifier, needs something before it "??", // lazy quantifier, needs something before it "{1,3}?", // lazy quantifier, needs something before it "|", // alternation, needs something around it "\\1", // backreference, needs a capturing group "\\k<name>", // named backreference, needs a named group "(?P=name)", // named backreference (Python), needs a named group "(?(1)|)", // conditional, needs a capturing group "(?(<name>)|)", // conditional, needs a named group ]; for category in QUICK_REF_CATEGORIES { for item in category.items { // Skip partial patterns that are meant to be combined if partial_patterns.contains(&item.insert) { continue; } let result = Regex::new(item.insert); assert!( result.is_ok(), "Pattern '{}' (insert: '{}') in category '{}' failed to compile: {:?}", item.syntax, item.insert, category.name, result.err() ); } } } #[test] fn test_partial_patterns_work_when_combined() { // Test that quantifier patterns work when applied to something let quantifiers = [ "*", "+", "?", "{1}", "{1,}", "{1,3}", "*?", "+?", "??", "{1,3}?", ]; for q in quantifiers { let pattern = format!("a{}", q); let result = Regex::new(&pattern); assert!( result.is_ok(), "Quantifier '{}' failed when combined: {:?}", q, result.err() ); } // Test alternation let result = Regex::new("a|b"); assert!(result.is_ok(), "Alternation pattern failed"); } #[test] fn test_context_dependent_patterns() { // Test backreferences work with proper context let result = Regex::new(r"(\w+)\s+\1"); assert!(result.is_ok(), "Backreference \\1 should work with group"); // Test named backreference with named group let result = Regex::new(r"(?<word>\w+)\s+\k<word>"); assert!( result.is_ok(), "Named backreference \\k<word> should work with named group" ); // Test Python-style named backreference let result = Regex::new(r"(?P<word>\w+)\s+(?P=word)"); assert!( result.is_ok(), "Python-style named backreference should work" ); // Test conditional with group let result = Regex::new(r"(a)?(?(1)b|c)"); assert!(result.is_ok(), "Conditional (?(1)...) should work"); // Test conditional with named group let result = Regex::new(r"(?<test>a)?(?(<test>)b|c)"); assert!(result.is_ok(), "Conditional with named group should work"); } #[test] fn test_flattened_entries_not_empty() { let entries = get_flattened_entries(); assert!(!entries.is_empty(), "Flattened entries should not be empty"); // Check we have at least some categories and items let category_count = entries .iter() .filter(|e| matches!(e, QuickRefEntry::Category(_))) .count(); let item_count = entries .iter() .filter(|e| matches!(e, QuickRefEntry::Item(_))) .count(); assert!(category_count > 0, "Should have at least one category"); assert!(item_count > 0, "Should have at least one item"); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore_regex/colors.rs
crates/nu-explore/src/explore_regex/colors.rs
//! Color scheme and style helpers for the regex explorer UI. use ratatui::style::{Color, Modifier, Style, Stylize}; // UI colors - using standard ANSI colors that adapt to terminal theme pub const ACCENT: Color = Color::Cyan; pub const SUCCESS: Color = Color::Green; pub const ERROR: Color = Color::Red; pub const WARNING: Color = Color::Yellow; // Text colors - using standard colors for terminal compatibility pub const BG_DARK: Color = Color::Black; pub const FG_PRIMARY: Color = Color::Reset; // Uses terminal default pub const FG_MUTED: Color = Color::DarkGray; // Highlight colors for regex matches as an array for easy iteration pub const HIGHLIGHT_COLORS: &[Color] = &[ Color::LightBlue, Color::LightGreen, Color::LightRed, Color::LightYellow, Color::Blue, Color::Green, Color::Red, Color::Yellow, Color::Magenta, ]; /// Returns the appropriate foreground color for a given highlight background. /// Uses white for darker backgrounds, black for lighter ones. pub const fn highlight_fg(color: Color) -> Color { match color { Color::Red | Color::Magenta | Color::Blue => Color::White, _ => Color::Black, } } /// Creates a highlight style for the given group index (cycles through colors). pub fn highlight_style(group: usize) -> Style { let bg = HIGHLIGHT_COLORS[group % HIGHLIGHT_COLORS.len()]; Style::new().bg(bg).fg(highlight_fg(bg)) } /// Style presets for common UI elements pub mod styles { use super::*; /// Style for focused/active elements pub fn focused() -> Style { Style::new().fg(FG_PRIMARY).bold() } /// Style for unfocused/inactive elements pub fn unfocused() -> Style { Style::new().fg(FG_MUTED) } /// Style for the focus indicator ("> ") pub fn focus_indicator() -> Style { Style::new().fg(FG_PRIMARY) } /// Style for muted separator text pub fn separator() -> Style { Style::new().fg(FG_MUTED) } /// Style for status badges (the brackets) pub fn status_bracket() -> Style { Style::new().fg(FG_MUTED) } /// Style for success status text pub fn status_success() -> Style { Style::new().fg(SUCCESS) } /// Style for error status text pub fn status_error() -> Style { Style::new().fg(ERROR) } /// Style for warning status text pub fn status_warning() -> Style { Style::new().fg(WARNING) } /// Style for category headers in quick reference pub fn category_header() -> Style { Style::new() .fg(ACCENT) .bold() .add_modifier(Modifier::UNDERLINED) } /// Style for selected item (inverted colors) pub fn selected() -> Style { Style::new().fg(BG_DARK).bg(ACCENT) } /// Style for selected item text (bold variant) pub fn selected_bold() -> Style { selected().bold() } /// Style for active cursor in text areas pub fn cursor_active() -> Style { Style::new().bg(ACCENT).fg(BG_DARK) } /// Style for hidden cursor pub fn cursor_hidden() -> Style { Style::new().hidden() } /// Border style for focused panels pub fn border_focused() -> Style { Style::new().fg(ACCENT) } /// Border style for focused panels with error state pub fn border_error() -> Style { Style::new().fg(ERROR) } /// Border style for unfocused panels pub fn border_unfocused() -> Style { Style::new().fg(FG_MUTED) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore_config/app.rs
crates/nu-explore/src/explore_config/app.rs
//! Application state and drawing logic for the explore config TUI. use crate::explore_config::syntax_highlight::highlight_nushell_content; use crate::explore_config::tree::{ build_tree_items, filter_tree_items, get_value_at_path, set_value_at_path, }; use crate::explore_config::types::{ App, EditorMode, Focus, NodeInfo, NuValueType, ValueType, calculate_cursor_position, }; use ansi_str::get_blocks; use nu_protocol::engine::{EngineState, Stack}; use ratatui::Frame; use ratatui::layout::{Constraint, Direction, Layout, Rect}; use ratatui::style::{Color, Modifier, Style, Stylize}; use ratatui::text::{Line, Span, Text}; use ratatui::widgets::{Block, Borders, Paragraph, Scrollbar, ScrollbarOrientation, Wrap}; use serde_json::Value; use std::collections::HashMap; use std::fs::File; use std::io::{self, Write}; use std::sync::Arc; use tui_tree_widget::{Tree, TreeState}; /// Convert an ANSI-styled string to a ratatui Line. /// /// This parses ANSI escape codes in the input string and converts them /// to ratatui Span objects with appropriate styles. fn ansi_string_to_line(ansi_text: &str) -> Line<'static> { let mut spans = Vec::new(); for block in get_blocks(ansi_text) { let text = block.text().to_string(); let style = ansi_style_to_ratatui(block.style()); spans.push(Span::styled(text, style)); } if spans.is_empty() { Line::from(String::new()) } else { Line::from(spans) } } /// Convert an ansi_str Style to a ratatui Style. fn ansi_style_to_ratatui(style: &ansi_str::Style) -> Style { let mut out = Style::default(); if let Some(clr) = style.foreground() { out.fg = ansi_color_to_ratatui_color(clr); } if let Some(clr) = style.background() { out.bg = ansi_color_to_ratatui_color(clr); } if style.is_bold() { out.add_modifier |= Modifier::BOLD; } if style.is_faint() { out.add_modifier |= Modifier::DIM; } if style.is_italic() { out.add_modifier |= Modifier::ITALIC; } if style.is_underline() { out.add_modifier |= Modifier::UNDERLINED; } if style.is_slow_blink() || style.is_rapid_blink() { out.add_modifier |= Modifier::SLOW_BLINK; } if style.is_inverse() { out.add_modifier |= Modifier::REVERSED; } if style.is_hide() { out.add_modifier |= Modifier::HIDDEN; } out } /// Convert an ansi_str Color to a ratatui Color. fn ansi_color_to_ratatui_color(clr: ansi_str::Color) -> Option<Color> { use ansi_str::Color::*; let color = match clr { Black => Color::Black, BrightBlack => Color::DarkGray, Red => Color::Red, BrightRed => Color::LightRed, Green => Color::Green, BrightGreen => Color::LightGreen, Yellow => Color::Yellow, BrightYellow => Color::LightYellow, Blue => Color::Blue, BrightBlue => Color::LightBlue, Magenta => Color::Magenta, BrightMagenta => Color::LightMagenta, Cyan => Color::Cyan, BrightCyan => Color::LightCyan, White => Color::White, BrightWhite => Color::Gray, Purple => Color::Magenta, BrightPurple => Color::LightMagenta, Fixed(i) => Color::Indexed(i), Rgb(r, g, b) => Color::Rgb(r, g, b), }; Some(color) } impl App { pub fn new( json_data: Value, output_file: Option<String>, config_mode: bool, nu_type_map: Option<HashMap<String, NuValueType>>, doc_map: Option<HashMap<String, String>>, engine_state: Arc<EngineState>, stack: Arc<Stack>, ) -> Self { let mut node_map = HashMap::new(); let tree_items = build_tree_items(&json_data, &mut node_map, &nu_type_map, &doc_map); let status_msg = if config_mode { "↑↓ Navigate | ←→ Collapse/Expand | Tab Switch pane | Ctrl+S Apply | q Quit" } else { "↑↓ Navigate | ←→ Collapse/Expand | Tab Switch pane | Ctrl+S Save | q Quit" }; App { tree_state: TreeState::default(), json_data, tree_items: tree_items.clone(), unfiltered_tree_items: tree_items, node_map, focus: Focus::Tree, editor_mode: EditorMode::Normal, editor_content: String::new(), editor_cursor: 0, editor_scroll: 0, selected_identifier: String::new(), status_message: String::from(status_msg), modified: false, confirmed_save: false, output_file, config_mode, nu_type_map, doc_map, search_query: String::new(), search_active: false, engine_state, stack, } } pub fn rebuild_tree(&mut self) { // Save current selection path from tree state let current_selection = self.tree_state.selected().to_vec(); let mut node_map = HashMap::new(); // Use the stored nu_type_map to preserve Nushell type information across rebuilds // This ensures that type displays remain accurate after edits in config mode let tree_items = build_tree_items( &self.json_data, &mut node_map, &self.nu_type_map, &self.doc_map, ); self.unfiltered_tree_items = tree_items.clone(); self.node_map = node_map; // Re-apply search filter if active if self.search_active && !self.search_query.is_empty() { self.tree_items = filter_tree_items(&self.unfiltered_tree_items, &self.search_query); } else { self.tree_items = tree_items; } // Try to restore selection if the node still exists if let Some(last_id) = current_selection.last() && self.node_map.contains_key(last_id) { self.tree_state.select(current_selection); } } /// Apply search filter to tree items pub fn apply_search_filter(&mut self) { if self.search_query.is_empty() { self.tree_items = self.unfiltered_tree_items.clone(); } else { self.tree_items = filter_tree_items(&self.unfiltered_tree_items, &self.search_query); } // Select first item if available self.tree_state.select_first(); self.force_update_editor(); } /// Clear search and restore full tree pub fn clear_search(&mut self) { self.search_query.clear(); self.search_active = false; self.tree_items = self.unfiltered_tree_items.clone(); self.tree_state.select_first(); self.force_update_editor(); } pub fn get_current_node_info(&self) -> Option<&NodeInfo> { if self.selected_identifier.is_empty() { return None; } self.node_map.get(&self.selected_identifier) } pub fn force_update_editor(&mut self) { let selected = self.tree_state.selected(); if selected.is_empty() { self.selected_identifier.clear(); self.editor_content.clear(); return; } // Use last() to get the actual selected node, not first() // selected() returns the path through the tree, so last is the actual selection self.selected_identifier = selected.last().cloned().unwrap_or_default(); if let Some(node_info) = self.node_map.get(&self.selected_identifier) { if let Some(value) = get_value_at_path(&self.json_data, &node_info.path) { self.editor_content = match value { Value::String(s) => s.clone(), Value::Null => String::from("null"), Value::Bool(b) => b.to_string(), Value::Number(n) => n.to_string(), _ => serde_json::to_string_pretty(value).unwrap_or_default(), }; } else { self.editor_content.clear(); } } else { self.editor_content.clear(); } self.editor_cursor = 0; self.editor_scroll = 0; } pub fn apply_edit(&mut self) { if self.selected_identifier.is_empty() { self.status_message = String::from("No node selected"); return; } let node_info = match self.node_map.get(&self.selected_identifier) { Some(info) => info.clone(), None => { self.status_message = String::from("Node not found"); return; } }; // Determine the new value based on content and original type let new_value: Value = if let Some(original_value) = get_value_at_path(&self.json_data, &node_info.path) { match original_value { // For strings, use content directly (don't parse as JSON) Value::String(_) => Value::String(self.editor_content.clone()), // For other leaf types, try to parse appropriately Value::Null => { if self.editor_content.trim() == "null" { Value::Null } else { // Try to parse as JSON, fall back to string serde_json::from_str(&self.editor_content) .unwrap_or_else(|_| Value::String(self.editor_content.clone())) } } Value::Bool(_) => match self.editor_content.trim() { "true" => Value::Bool(true), "false" => Value::Bool(false), _ => Value::String(self.editor_content.clone()), }, Value::Number(_) => { // Try to parse as number if let Ok(n) = self.editor_content.trim().parse::<i64>() { Value::Number(n.into()) } else if let Ok(n) = self.editor_content.trim().parse::<f64>() { serde_json::Number::from_f64(n) .map(Value::Number) .unwrap_or_else(|| Value::String(self.editor_content.clone())) } else { Value::String(self.editor_content.clone()) } } // For arrays and objects, parse as JSON Value::Array(_) | Value::Object(_) => { match serde_json::from_str(&self.editor_content) { Ok(v) => v, Err(e) => { self.status_message = format!("✗ JSON parse error: {}", e); return; } } } } } else { // Fallback: try to parse as JSON serde_json::from_str(&self.editor_content) .unwrap_or_else(|_| Value::String(self.editor_content.clone())) }; // Apply the change to the JSON data if set_value_at_path(&mut self.json_data, &node_info.path, new_value) { self.rebuild_tree(); self.modified = true; self.status_message = String::from("✓ Value updated successfully"); } else { self.status_message = String::from("✗ Failed to update value"); } } pub fn save_to_file(&mut self) -> io::Result<()> { if self.config_mode { // In config mode, we mark as "ready to apply" - actual application happens on exit self.confirmed_save = true; self.status_message = String::from("✓ Changes staged - will be applied to config on exit"); return Ok(()); } let filename = self .output_file .clone() .unwrap_or_else(|| String::from("output.json")); let json_string = serde_json::to_string_pretty(&self.json_data)?; let mut file = File::create(&filename)?; file.write_all(json_string.as_bytes())?; self.modified = false; self.status_message = format!("✓ Saved to {}", filename); Ok(()) } pub fn draw(&mut self, frame: &mut Frame) { let chunks = Layout::default() .direction(Direction::Vertical) .constraints([ Constraint::Length(1), // Title bar Constraint::Min(1), // Main content Constraint::Length(1), // Status bar ]) .split(frame.area()); // Title bar self.draw_title_bar(frame, chunks[0]); // Main content (tree + editor) let main_chunks = Layout::default() .direction(Direction::Horizontal) .constraints([Constraint::Percentage(45), Constraint::Percentage(55)]) .split(chunks[1]); // Left pane: Tree self.draw_tree(frame, main_chunks[0]); // Right pane: Editor panel self.draw_editor_panel(frame, main_chunks[1]); // Status bar self.draw_status_bar(frame, chunks[2]); } fn draw_title_bar(&self, frame: &mut Frame, area: Rect) { let modified_indicator = if self.modified { " [*]" } else { "" }; let title = format!(" Nushell Config Explorer{}", modified_indicator); let title_bar = Paragraph::new(title).style(Style::default().bg(Color::Blue).fg(Color::White).bold()); frame.render_widget(title_bar, area); } fn draw_tree(&mut self, frame: &mut Frame, area: Rect) { let is_focused = self.focus == Focus::Tree || self.focus == Focus::Search; let is_searching = self.focus == Focus::Search; let border_color = if is_searching { Color::Yellow } else if is_focused { Color::Cyan } else { Color::DarkGray }; // Build title based on search state let title = if is_searching { format!(" Search: {}▌ ", self.search_query) } else if self.search_active { format!(" Tree [filter: \"{}\"] ", self.search_query) } else if is_focused { " Tree [focused] ".to_string() } else { " Tree ".to_string() }; let tree_block = Block::default() .title(title) .title_style(Style::default().bold().fg(if is_searching { Color::Yellow } else { Color::Reset })) .borders(Borders::ALL) .border_style(Style::default().fg(border_color)); let tree_widget = Tree::new(&self.tree_items) .expect("all item identifiers are unique") .block(tree_block) .experimental_scrollbar(Some( Scrollbar::new(ScrollbarOrientation::VerticalRight) .begin_symbol(None) .track_symbol(None) .end_symbol(None), )) .highlight_style( Style::default() .fg(Color::Black) .bg(Color::LightGreen) .add_modifier(Modifier::BOLD), ) .highlight_symbol("▶ ") .node_closed_symbol("▸ ") .node_open_symbol("▾ ") .node_no_children_symbol(" "); frame.render_stateful_widget(tree_widget, area, &mut self.tree_state); } fn draw_editor_panel(&self, frame: &mut Frame, area: Rect) { let is_focused = self.focus == Focus::Editor; let border_color = if is_focused { Color::Cyan } else { Color::DarkGray }; let panel_block = Block::default() .title(if is_focused { " Editor [focused] " } else { " Editor " }) .title_style(Style::default().bold()) .borders(Borders::ALL) .border_style(Style::default().fg(border_color)); let inner_area = panel_block.inner(area); frame.render_widget(panel_block, area); // Split the editor panel into sections let editor_chunks = Layout::default() .direction(Direction::Vertical) .constraints([ Constraint::Length(3), // Path display Constraint::Length(3), // Type info Constraint::Min(5), // Editor area Constraint::Length(12), // Description (new section) Constraint::Length(3), // Help text (with border) ]) .split(inner_area); // Path display (read-only) self.draw_path_widget(frame, editor_chunks[0]); // Type info self.draw_type_widget(frame, editor_chunks[1]); // Editor area self.draw_editor_widget(frame, editor_chunks[2]); // Description (new section) self.draw_description_widget(frame, editor_chunks[3]); // Help text self.draw_editor_help(frame, editor_chunks[4]); } fn draw_path_widget(&self, frame: &mut Frame, area: Rect) { let path_block = Block::default() .title(" Path ") .title_style(Style::default().fg(Color::Yellow)) .borders(Borders::ALL) .border_style(Style::default().fg(Color::DarkGray)); let path_display = if let Some(node_info) = self.get_current_node_info() { if node_info.path.is_empty() { String::from("(root)") } else { node_info .path .iter() .map(|p| { // Check if it's an array index if p.parse::<usize>().is_ok() { format!("[{}]", p) } else if p.contains(' ') || p.contains('.') { format!("[\"{}\"]", p) } else { format!(".{}", p) } }) .collect::<Vec<_>>() .join("") .trim_start_matches('.') .to_string() } } else { String::from("(no selection)") }; let path_text = Paragraph::new(path_display) .style(Style::default().fg(Color::White)) .block(path_block); frame.render_widget(path_text, area); } fn draw_type_widget(&self, frame: &mut Frame, area: Rect) { let type_block = Block::default() .title(" Type ") .title_style(Style::default().fg(Color::Yellow)) .borders(Borders::ALL) .border_style(Style::default().fg(Color::DarkGray)); let (type_label, type_color, extra_info) = if let Some(node_info) = self.get_current_node_info() { let extra = match node_info.value_type { ValueType::Array => { if let Some(Value::Array(arr)) = get_value_at_path(&self.json_data, &node_info.path) { format!(" ({} items)", arr.len()) } else { String::new() } } ValueType::Object => { if let Some(Value::Object(obj)) = get_value_at_path(&self.json_data, &node_info.path) { format!(" ({} keys)", obj.len()) } else { String::new() } } ValueType::String => { if let Some(Value::String(s)) = get_value_at_path(&self.json_data, &node_info.path) { format!(" ({} chars)", s.len()) } else { String::new() } } _ => String::new(), }; // In config mode, use nushell types if available if self.config_mode { if let Some(ref nu_type) = node_info.nu_type { (nu_type.label().to_string(), nu_type.color(), extra) } else { ( node_info.value_type.label().to_string(), node_info.value_type.color(), extra, ) } } else { ( node_info.value_type.label().to_string(), node_info.value_type.color(), extra, ) } } else { ("unknown".to_string(), Color::DarkGray, String::new()) }; let type_line = Line::from(vec![ Span::styled( format!(" {} ", &type_label), Style::default().fg(Color::Black).bg(type_color).bold(), ), Span::styled(extra_info, Style::default().fg(Color::DarkGray)), ]); let type_text = Paragraph::new(type_line).block(type_block); frame.render_widget(type_text, area); } fn draw_editor_widget(&self, frame: &mut Frame, area: Rect) { let is_editing = self.editor_mode == EditorMode::Editing && self.focus == Focus::Editor; let editor_block = Block::default() .title(if is_editing { " Value [editing] " } else { " Value " }) .title_style(Style::default().fg(if is_editing { Color::Green } else { Color::Yellow })) .borders(Borders::ALL) .border_style(Style::default().fg(if is_editing { Color::Green } else { Color::DarkGray })); let inner_area = editor_block.inner(area); frame.render_widget(editor_block, area); // Calculate visible lines let visible_height = inner_area.height as usize; let lines: Vec<&str> = self.editor_content.lines().collect(); let total_lines = lines.len().max(1); // Calculate cursor position let cursor_pos = calculate_cursor_position(&self.editor_content, self.editor_cursor); let cursor_line = cursor_pos.line; let cursor_col = cursor_pos.col; // Render content with syntax highlighting // Highlight the entire content at once so multi-line constructs (records, lists, etc.) // are properly recognized let highlighted_lines: Vec<Line> = if self.config_mode { let highlighted = highlight_nushell_content(&self.engine_state, &self.stack, &self.editor_content); highlighted .lines .iter() .map(|line| ansi_string_to_line(line)) .collect() } else { self.editor_content .lines() .map(|line| Line::from(line.to_string())) .collect() }; let content_lines: Vec<Line> = highlighted_lines .into_iter() .enumerate() .skip(self.editor_scroll) .take(visible_height) .map(|(idx, highlighted_line)| { // Apply background highlight for current line when editing if is_editing && idx == cursor_line { // Apply background to all spans in the line let spans: Vec<Span> = highlighted_line .spans .into_iter() .map(|span| { Span::styled(span.content, span.style.bg(Color::Rgb(40, 40, 40))) }) .collect(); Line::from(spans) } else { highlighted_line } }) .collect(); let content = if content_lines.is_empty() { if self.editor_content.is_empty() { Text::from(Line::from(Span::styled( "(empty)", Style::default().fg(Color::DarkGray).italic(), ))) } else { Text::from(content_lines) } } else { Text::from(content_lines) }; let paragraph = Paragraph::new(content); frame.render_widget(paragraph, inner_area); // Show cursor when editing if is_editing && inner_area.width > 0 && inner_area.height > 0 { let cursor_y = (cursor_line.saturating_sub(self.editor_scroll)) as u16; let cursor_x = cursor_col as u16; if cursor_y < inner_area.height { frame.set_cursor_position(( inner_area.x + cursor_x.min(inner_area.width - 1), inner_area.y + cursor_y, )); } } // Show scroll indicator if needed if total_lines > visible_height { let scroll_info = format!( " {}-{}/{} ", self.editor_scroll + 1, (self.editor_scroll + visible_height).min(total_lines), total_lines ); let scroll_len = scroll_info.len(); let scroll_span = Span::styled(scroll_info, Style::default().fg(Color::DarkGray)); let scroll_paragraph = Paragraph::new(scroll_span); let scroll_area = Rect { x: area.x + area.width.saturating_sub(scroll_len as u16 + 1), y: area.y, width: scroll_len as u16, height: 1, }; frame.render_widget(scroll_paragraph, scroll_area); } } fn draw_description_widget(&self, frame: &mut Frame, area: Rect) { let node_info = self.get_current_node_info(); // Determine if we have documentation for this node let (description, has_doc) = if self.config_mode { if let Some(info) = node_info { // Build the config path from the node path (e.g., ["history", "file_format"] -> "history.file_format") let config_path = info.path.join("."); if let Some(ref doc_map) = self.doc_map { if let Some(doc) = doc_map.get(&config_path) { (doc.clone(), true) } else { // Try parent paths for nested items let mut found_doc = None; let mut path_parts = info.path.clone(); while !path_parts.is_empty() && found_doc.is_none() { let parent_path = path_parts.join("."); if let Some(doc) = doc_map.get(&parent_path) { found_doc = Some(doc.clone()); } path_parts.pop(); } if let Some(doc) = found_doc { (doc, true) } else { ( "No documentation available for this setting.".to_string(), false, ) } } } else { ("Documentation not loaded.".to_string(), false) } } else { ("Select a node to see its description.".to_string(), false) } } else { ( "Documentation is only available in config mode.".to_string(), false, ) }; // Use different styling based on whether documentation exists let (title_style, border_style) = if self.config_mode && !has_doc { // Highlight missing documentation with yellow/warning color ( Style::default().fg(Color::Yellow).bold(), Style::default().fg(Color::Yellow), ) } else { ( Style::default().fg(Color::Yellow), Style::default().fg(Color::DarkGray), ) }; let title = if self.config_mode && !has_doc { " Description [missing] " } else { " Description " }; let desc_block = Block::default() .title(title) .title_style(title_style) .borders(Borders::ALL) .border_style(border_style); // Truncate description to fit in the available area let inner_height = area.height.saturating_sub(2) as usize; // Account for borders let lines: Vec<&str> = description.lines().take(inner_height).collect(); let display_text = lines.join("\n"); let desc_text = Paragraph::new(display_text) .style(Style::default().fg(if has_doc { Color::White } else { Color::DarkGray })) .block(desc_block) .wrap(Wrap { trim: true }); frame.render_widget(desc_text, area); } fn draw_editor_help(&self, frame: &mut Frame, area: Rect) { let help_block = Block::default() .title(" Help ") .title_style(Style::default().fg(Color::Yellow)) .borders(Borders::ALL) .border_style(Style::default().fg(Color::DarkGray)); let help_text = if self.focus == Focus::Editor { if self.editor_mode == EditorMode::Editing { Line::from(vec![ Span::styled("Ctrl+S", Style::default().fg(Color::Green).bold()), Span::raw("/"), Span::styled("Alt+Enter", Style::default().fg(Color::Green).bold()), Span::raw(" Apply "), Span::styled("Esc", Style::default().fg(Color::Red).bold()), Span::raw(" Cancel "), Span::styled("Ctrl+↑↓", Style::default().fg(Color::Yellow).bold()), Span::raw(" Scroll"), ]) } else { Line::from(vec![ Span::styled("Enter/e", Style::default().fg(Color::Green).bold()), Span::raw(" Edit "), Span::styled("Tab", Style::default().fg(Color::Yellow).bold()), Span::raw(" Switch pane "), Span::styled("↑↓", Style::default().fg(Color::Yellow).bold()), Span::raw(" Scroll"), ]) } } else { Line::from(vec![ Span::styled("Tab", Style::default().fg(Color::Yellow).bold()), Span::raw(" Switch to editor"), ]) }; let help = Paragraph::new(help_text) .style(Style::default().fg(Color::DarkGray)) .block(help_block); frame.render_widget(help, area); } fn draw_status_bar(&self, frame: &mut Frame, area: Rect) { let status_style = Style::default().bg(Color::Rgb(30, 30, 30)).fg(Color::White); let status = Paragraph::new(format!(" {}", self.status_message)).style(status_style); frame.render_widget(status, area); } pub fn scroll_editor(&mut self, delta: i32) { let lines_count = self.editor_content.lines().count(); if delta < 0 { self.editor_scroll = self.editor_scroll.saturating_sub((-delta) as usize); } else { self.editor_scroll = (self.editor_scroll + delta as usize).min(lines_count.saturating_sub(1)); } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore_config/command.rs
crates/nu-explore/src/explore_config/command.rs
//! Command definition for the `explore config` command. use crate::explore_config::conversion::{ build_nu_type_map, build_original_value_map, json_to_nu_value_with_types, nu_value_to_json, parse_config_documentation, }; use crate::explore_config::example_data::get_example_json; use crate::explore_config::tree::print_json_tree; use crate::explore_config::tui::run_config_tui; use crate::explore_config::types::NuValueType; use nu_engine::command_prelude::*; use nu_protocol::{PipelineData, report_shell_warning}; use serde_json::Value; use std::collections::HashMap; use std::sync::Arc; /// Type alias for the tuple returned when determining data source and mode type ConfigDataResult = ( Value, bool, Option<HashMap<String, NuValueType>>, Option<HashMap<String, nu_protocol::Value>>, Option<HashMap<String, String>>, ); /// A command to explore and edit nushell configuration interactively. #[derive(Clone)] pub struct ExploreConfigCommand; impl Command for ExploreConfigCommand { fn name(&self) -> &str { "explore config" } fn description(&self) -> &str { "Launch a TUI to view and edit the nushell configuration interactively." } fn signature(&self) -> nu_protocol::Signature { Signature::build("explore config") .input_output_types(vec![ (Type::Nothing, Type::String), (Type::String, Type::String), ]) .switch( "use-example-data", "Show the nushell configuration TUI using example data", Some('e'), ) .switch( "tree", "Do not show the TUI, just show a tree structure of the data", Some('t'), ) .named( "output", SyntaxShape::String, "Optional output file to save changes to (default: output.json)", Some('o'), ) .category(Category::Viewers) } fn extra_description(&self) -> &str { r#"By default, opens the current nushell configuration ($env.config) in the TUI. Changes made in config mode are applied to the running session when you quit. You can also pipe JSON data to explore arbitrary data structures, or use --use-example-data to see sample configuration data. TUI Keybindings: Tab Switch between tree and editor panes ↑↓ Navigate tree / scroll editor ←→ Collapse/Expand tree nodes Enter/Space Toggle tree node expansion Enter/Space On leaf nodes, open editor pane and start editing Enter/e Start editing (in editor pane) Ctrl+S Apply edit Alt+Enter Apply edit (alternative) Esc Cancel edit q Quit (applies config changes if modified) Ctrl+C Force quit without saving"# } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let input_span = input.span().unwrap_or(call.head); let (string_input, _span, _metadata) = input.collect_string_strict(input_span)?; let use_example = call.has_flag(engine_state, stack, "use-example-data")?; let cli_mode = call.has_flag(engine_state, stack, "tree")?; let output_file: Option<String> = call.get_flag(engine_state, stack, "output")?; // Determine the data source and mode // nu_type_map is used in config mode to track original nushell types // original_values is used to preserve values that can't be roundtripped (closures, dates, etc.) // doc_map is used in config mode to show documentation for config options let (json_data, config_mode, nu_type_map, original_values, doc_map): ConfigDataResult = if use_example { // Use example data (get_example_json(), false, None, None, None) } else if !string_input.trim().is_empty() { // Use piped input data let data = serde_json::from_str(&string_input).map_err(|e| ShellError::GenericError { error: "Could not parse JSON from input".into(), msg: format!("JSON parse error: {e}"), span: Some(call.head), help: Some("Make sure the input is valid JSON".into()), inner: vec![], })?; (data, false, None, None, None) } else { // Default: use nushell configuration // Get the raw $env.config Value directly to preserve key ordering // (using Config::into_value would lose order because HashMap iteration is unordered) let nu_value = stack .get_env_var(engine_state, "config") .cloned() .unwrap_or_else(|| { // Fallback to Config struct if $env.config is not set let config = stack.get_config(engine_state); config.as_ref().clone().into_value(call.head) }); let json_data = nu_value_to_json(engine_state, &nu_value, call.head)?; // Build nu_type_map to track original nushell types let mut nu_type_map = HashMap::new(); build_nu_type_map(&nu_value, Vec::new(), &mut nu_type_map); // Build original_values map for types that can't be roundtripped (closures, dates, etc.) let mut original_values = HashMap::new(); build_original_value_map(&nu_value, Vec::new(), &mut original_values); // Parse documentation from doc_config.nu let doc_map = parse_config_documentation(); ( json_data, true, Some(nu_type_map), Some(original_values), Some(doc_map), ) }; if cli_mode { // Original CLI behavior print_json_tree(&json_data, "", true, None); } else { // TUI mode - clone the type map and original values so we can use them after the TUI returns let type_map_for_conversion = nu_type_map.clone(); let original_values_for_conversion = original_values.clone(); let result = run_config_tui( json_data, output_file, config_mode, nu_type_map, doc_map, Arc::new(engine_state.clone()), Arc::new(stack.clone()), )?; // If in config mode and data was modified, apply changes to the config if config_mode && let Some(modified_json) = result { // Convert JSON back to nu_protocol::Value, using type map and original values // to preserve types like Duration, Filesize, and Closure let nu_value = json_to_nu_value_with_types( &modified_json, call.head, &type_map_for_conversion, &original_values_for_conversion, Vec::new(), ) .map_err(|e| ShellError::GenericError { error: "Could not convert JSON to nu Value".into(), msg: format!("conversion error: {e}"), span: Some(call.head), help: None, inner: vec![], })?; // Update $env.config with the new value stack.add_env_var("config".into(), nu_value.clone()); // Update the internal Config struct directly, without calling update_config() // which would overwrite $env.config with Config::into_value() and lose key ordering // (because Config uses HashMap for color_config/explore/plugins fields) let old_config = stack.get_config(engine_state); let mut new_config = (*old_config).clone(); let result = new_config.update_from_value(&old_config, &nu_value); // Store the updated Config struct directly on the stack stack.config = Some(Arc::new(new_config)); if let Some(warning) = result? { report_shell_warning(Some(stack), engine_state, &warning); } } } Ok(PipelineData::empty()) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Open the nushell configuration in an interactive TUI editor", example: r#"explore config"#, result: None, }, Example { description: "Explore JSON data interactively", example: r#"open --raw data.json | explore config"#, result: None, }, Example { description: "Explore with example data to see TUI features", example: r#"explore config --use-example-data"#, result: None, }, ] } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore_config/tree.rs
crates/nu-explore/src/explore_config/tree.rs
//! Tree building, path operations, and CLI tree printing utilities. use crate::explore_config::types::{NodeInfo, NuValueType, ValueType}; use serde_json::Value; use std::collections::HashMap; use tui_tree_widget::TreeItem; /// Check if a JSON value is a leaf node (not an object or array) pub fn is_leaf(value: &Value) -> bool { !value.is_object() && !value.is_array() } /// Render a leaf value as a string pub fn render_leaf(value: &Value) -> String { serde_json::to_string(value).unwrap_or_else(|_| "<unserializable>".to_string()) } /// Print a JSON tree structure to stdout (for CLI mode) pub fn print_json_tree(value: &Value, prefix: &str, is_tail: bool, key: Option<&str>) { if let Some(k) = key { let connector = if is_tail { "└── " } else { "├── " }; let leaf_part = if is_leaf(value) { format!(" {}", render_leaf(value)) } else { String::new() }; println!("{}{}{}:{}", prefix, connector, k, leaf_part); } if !is_leaf(value) { let branch = if is_tail { " " } else { "│ " }; let child_prefix = if key.is_none() { prefix.to_string() } else { format!("{}{}", prefix, branch) }; match value { Value::Object(map) => { let mut entries: Vec<(&str, &Value)> = map.iter().map(|(kk, vv)| (kk.as_str(), vv)).collect(); entries.sort_by_key(|(kk, _)| *kk); for (idx, &(kk, vv)) in entries.iter().enumerate() { let child_tail = idx == entries.len() - 1; print_json_tree(vv, &child_prefix, child_tail, Some(kk)); } } Value::Array(arr) => { for (idx, vv) in arr.iter().enumerate() { let child_tail = idx == arr.len() - 1; let idx_str = idx.to_string(); print_json_tree(vv, &child_prefix, child_tail, Some(&idx_str)); } } _ => {} } } } /// Filter tree items based on a search query. /// Returns a new tree with only items (and their ancestors) that match the query. /// The search is case-insensitive and matches against the item's identifier (path). pub fn filter_tree_items( items: &[TreeItem<'static, String>], query: &str, ) -> Vec<TreeItem<'static, String>> { let query_lower = query.to_lowercase(); filter_tree_items_recursive(items, &query_lower) } /// Recursively filter tree items based on a search query. /// /// This function traverses the tree and includes items that either: /// 1. Have an identifier that contains the query string (case-insensitive match) /// 2. Have descendants that match the query (ancestor preservation) /// /// # Arguments /// * `items` - The tree items to filter /// * `query` - The lowercase search query to match against identifiers /// /// # Returns /// A new vector of tree items containing only matching items and their ancestors. /// - Leaf items that match are cloned directly /// - Parent items with matching children are rebuilt with only the filtered children /// - Parent items that match but have no matching children are shown as collapsed leaves /// /// # Note /// If rebuilding a parent with filtered children fails (e.g., due to duplicate identifiers), /// the item is included as a collapsed leaf to ensure no matches are silently dropped. fn filter_tree_items_recursive( items: &[TreeItem<'static, String>], query: &str, ) -> Vec<TreeItem<'static, String>> { let mut result = Vec::new(); for item in items { let identifier = item.identifier().clone(); let identifier_lower = identifier.to_lowercase(); // Check if this item's identifier matches the query let self_matches = identifier_lower.contains(query); // Recursively filter children let filtered_children = filter_tree_items_recursive(item.children(), query); // Include this item if it matches OR if any of its children matched if self_matches || !filtered_children.is_empty() { if item.children().is_empty() { // Leaf item - just clone it result.push(item.clone()); } else if !filtered_children.is_empty() { // Has matching children - rebuild with filtered children match rebuild_item_with_children(item, filtered_children) { Ok(new_item) => result.push(new_item), Err(_) => { // Fallback: if rebuild fails, include as collapsed leaf // This ensures matching items aren't silently dropped result.push(TreeItem::new_leaf(identifier, format_collapsed_label(item))); } } } else { // Self matches but has children that don't match // Include as a leaf (collapsed view of matching parent) result.push(TreeItem::new_leaf(identifier, format_collapsed_label(item))); } } } result } /// Rebuild a tree item with new children, preserving the display format fn rebuild_item_with_children( original: &TreeItem<'static, String>, new_children: Vec<TreeItem<'static, String>>, ) -> Result<TreeItem<'static, String>, std::io::Error> { let identifier = original.identifier().clone(); // Extract the display text by getting the height (number of lines) and reconstructing // Since we can't access the text directly, use the identifier as a base for the label // The original label format is preserved in the clone, so we just need the identifier // to build a similar looking label let label = format_parent_label(&identifier, new_children.len()); TreeItem::new(identifier, label, new_children) } /// Format a label for a parent node based on identifier fn format_parent_label(identifier: &str, child_count: usize) -> String { // Extract the key name from the identifier (last part after the last dot) let key = identifier .rsplit('.') .next() .unwrap_or(identifier) .trim_start_matches('[') .trim_end_matches(']'); format!("{} {{{} keys}}", key, child_count) } /// Format a display label for a tree item shown in collapsed form. /// /// This is used when a parent item matches the search query but none of its /// children match. The item is displayed as a leaf node with a label indicating /// how many children it contains. /// /// # Arguments /// * `item` - The tree item to create a collapsed label for /// /// # Returns /// A string label in the format: /// - `"key {N keys}"` for items with children (where N is the child count) /// - `"key"` for leaf items (no children) /// /// # Example /// For an item with identifier `"color_config.string"` and 3 children, /// this returns `"string {3 keys}"`. fn format_collapsed_label(item: &TreeItem<'static, String>) -> String { let identifier = item.identifier(); let key = identifier .rsplit('.') .next() .unwrap_or(identifier) .trim_start_matches('[') .trim_end_matches(']'); let child_count = item.children().len(); if child_count > 0 { format!("{} {{{} keys}}", key, child_count) } else { key.to_string() } } /// Build tree items for the TUI tree widget pub fn build_tree_items( json_data: &Value, node_map: &mut HashMap<String, NodeInfo>, nu_type_map: &Option<HashMap<String, NuValueType>>, doc_map: &Option<HashMap<String, String>>, ) -> Vec<TreeItem<'static, String>> { build_tree_items_recursive( json_data, node_map, nu_type_map, doc_map, Vec::new(), String::new(), ) } fn build_tree_items_recursive( value: &Value, node_map: &mut HashMap<String, NodeInfo>, nu_type_map: &Option<HashMap<String, NuValueType>>, doc_map: &Option<HashMap<String, String>>, current_path: Vec<String>, parent_id: String, ) -> Vec<TreeItem<'static, String>> { match value { Value::Object(map) => { // Sort keys alphabetically let mut entries: Vec<(&String, &Value)> = map.iter().collect(); entries.sort_by_key(|(k, _)| *k); entries .into_iter() .map(|(key, val)| { let mut path = current_path.clone(); path.push(key.clone()); let identifier = if parent_id.is_empty() { key.clone() } else { format!("{}.{}", parent_id, key) }; let value_type = ValueType::from_value(val); let nu_type = nu_type_map .as_ref() .and_then(|m| m.get(&identifier).cloned()); // Check if documentation exists for this path let config_path = path.join("."); let has_doc = doc_map .as_ref() .is_some_and(|m| m.contains_key(&config_path)) || should_suppress_doc_warning(&path); node_map.insert( identifier.clone(), NodeInfo { path: path.clone(), value_type, nu_type, }, ); let display = format_tree_label(key, val, has_doc, doc_map.is_some()); if is_leaf(val) { TreeItem::new_leaf(identifier, display) } else { let children = build_tree_items_recursive( val, node_map, nu_type_map, doc_map, path, identifier.clone(), ); TreeItem::new(identifier, display, children) .expect("all item identifiers are unique") } }) .collect() } Value::Array(arr) => arr .iter() .enumerate() .map(|(idx, val)| { let mut path = current_path.clone(); path.push(idx.to_string()); let identifier = if parent_id.is_empty() { format!("[{}]", idx) } else { format!("{}[{}]", parent_id, idx) }; let value_type = ValueType::from_value(val); let nu_type = nu_type_map .as_ref() .and_then(|m| m.get(&identifier).cloned()); // Check if documentation exists for this path let config_path = path.join("."); let has_doc = doc_map .as_ref() .is_some_and(|m| m.contains_key(&config_path)) || should_suppress_doc_warning(&path); node_map.insert( identifier.clone(), NodeInfo { path: path.clone(), value_type, nu_type, }, ); let display = format_array_item_label(idx, val, has_doc, doc_map.is_some()); if is_leaf(val) { TreeItem::new_leaf(identifier, display) } else { let children = build_tree_items_recursive( val, node_map, nu_type_map, doc_map, path, identifier.clone(), ); TreeItem::new(identifier, display, children) .expect("all item identifiers are unique") } }) .collect(), _ => Vec::new(), } } /// Escape control characters that would cause multi-line rendering in tree labels fn escape_for_display(s: &str) -> String { s.replace('\r', "\\r") .replace('\n', "\\n") .replace('\t', "\\t") } /// Check if a path should suppress the "missing documentation" warning. /// This is used for user-defined list items like keybindings and menus entries, /// where individual items won't have documentation. fn should_suppress_doc_warning(path: &[String]) -> bool { // Suppress warnings for any nested items under keybindings or menus // e.g., ["keybindings", "0", "name"] or ["menus", "1", "source"] if path.len() >= 2 { let first = path[0].as_str(); if first == "keybindings" || first == "menus" { return true; } } false } fn format_tree_label(key: &str, value: &Value, has_doc: bool, is_config_mode: bool) -> String { let doc_marker = if is_config_mode && !has_doc { "⚠ " } else { "" }; // Escape control characters in key to prevent multi-line tree items let safe_key = escape_for_display(key); match value { Value::Null => format!("{}{}: null", doc_marker, safe_key), Value::Bool(b) => format!("{}{}: {}", doc_marker, safe_key, b), Value::Number(n) => format!("{}{}: {}", doc_marker, safe_key, n), Value::String(s) => { // Truncate safely at char boundary, not byte boundary // Use nth() to check if string has more than 40 chars without counting all chars let needs_truncation = s.chars().nth(40).is_some(); let preview = if needs_truncation { let truncated: String = s.chars().take(37).collect(); format!("{}...", truncated) } else { s.clone() }; format!( "{}{}: \"{}\"", doc_marker, safe_key, escape_for_display(&preview) ) } Value::Array(arr) => format!("{}{} [{} items]", doc_marker, safe_key, arr.len()), Value::Object(obj) => format!("{}{} {{{} keys}}", doc_marker, safe_key, obj.len()), } } fn format_array_item_label( idx: usize, value: &Value, has_doc: bool, is_config_mode: bool, ) -> String { let doc_marker = if is_config_mode && !has_doc { "⚠ " } else { "" }; match value { Value::Null => format!("{}[{}]: null", doc_marker, idx), Value::Bool(b) => format!("{}[{}]: {}", doc_marker, idx, b), Value::Number(n) => format!("{}[{}]: {}", doc_marker, idx, n), Value::String(s) => { // Truncate safely at char boundary, not byte boundary // Use nth() to check if string has more than 40 chars without counting all chars let needs_truncation = s.chars().nth(40).is_some(); let preview = if needs_truncation { let truncated: String = s.chars().take(37).collect(); format!("{}...", truncated) } else { s.clone() }; format!( "{}[{}]: \"{}\"", doc_marker, idx, escape_for_display(&preview) ) } Value::Array(arr) => format!("{}[{}] [{} items]", doc_marker, idx, arr.len()), Value::Object(obj) => format!("{}[{}] {{{} keys}}", doc_marker, idx, obj.len()), } } /// Get a value at a specific path in the JSON tree pub fn get_value_at_path<'a>(value: &'a Value, path: &[String]) -> Option<&'a Value> { let mut current = value; for part in path { match current { Value::Object(map) => { current = map.get(part)?; } Value::Array(arr) => { let idx: usize = part.parse().ok()?; current = arr.get(idx)?; } _ => return None, } } Some(current) } /// Set a value at a specific path in the JSON tree pub fn set_value_at_path(value: &mut Value, path: &[String], new_value: Value) -> bool { if path.is_empty() { *value = new_value; return true; } let mut current = value; for (i, part) in path.iter().enumerate() { if i == path.len() - 1 { // Last part, set the value match current { Value::Object(map) => { map.insert(part.clone(), new_value); return true; } Value::Array(arr) => { if let Ok(idx) = part.parse::<usize>() && idx < arr.len() { arr[idx] = new_value; return true; } return false; } _ => return false, } } else { // Navigate deeper match current { Value::Object(map) => { if let Some(next) = map.get_mut(part) { current = next; } else { return false; } } Value::Array(arr) => { if let Ok(idx) = part.parse::<usize>() { if idx < arr.len() { current = &mut arr[idx]; } else { return false; } } else { return false; } } _ => return false, } } } false } #[cfg(test)] mod tests { use super::*; #[test] fn test_escape_for_display_newlines() { assert_eq!(escape_for_display("hello\nworld"), "hello\\nworld"); assert_eq!(escape_for_display("a\nb\nc"), "a\\nb\\nc"); } #[test] fn test_escape_for_display_carriage_returns() { assert_eq!(escape_for_display("hello\rworld"), "hello\\rworld"); assert_eq!(escape_for_display("line\r\nend"), "line\\r\\nend"); } #[test] fn test_escape_for_display_tabs() { assert_eq!(escape_for_display("hello\tworld"), "hello\\tworld"); } #[test] fn test_escape_for_display_mixed() { assert_eq!( escape_for_display("line1\nline2\r\nline3\tend"), "line1\\nline2\\r\\nline3\\tend" ); } #[test] fn test_escape_for_display_no_special_chars() { assert_eq!(escape_for_display("hello world"), "hello world"); assert_eq!(escape_for_display(""), ""); } #[test] fn test_format_tree_label_escapes_newlines_in_string_value() { let value = Value::String("line1\nline2\nline3".to_string()); let label = format_tree_label("key", &value, false, false); assert!( !label.contains('\n'), "Label should not contain actual newlines" ); assert!( label.contains("\\n"), "Label should contain escaped newlines" ); } #[test] fn test_format_tree_label_truncates_long_strings() { let long_string = "a".repeat(100); let value = Value::String(long_string); let label = format_tree_label("key", &value, false, false); assert!(label.contains("..."), "Long strings should be truncated"); assert!(label.len() < 100, "Label should be shorter than original"); } #[test] fn test_format_tree_label_handles_closure_like_strings() { // Simulate a closure string with newlines like what we'd get from Nushell let closure_str = "{|| (date now) - $in |\n if $in < 1hr {\n 'red'\n }\n}"; let value = Value::String(closure_str.to_string()); let label = format_tree_label("datetime", &value, false, false); // The label should NOT contain any actual newlines assert!( !label.contains('\n'), "Label should not contain actual newlines: {}", label ); // But it SHOULD contain escaped newlines assert!( label.contains("\\n"), "Label should contain escaped newlines: {}", label ); } #[test] fn test_format_array_item_label_escapes_newlines() { let value = Value::String("line1\nline2".to_string()); let label = format_array_item_label(0, &value, false, false); assert!( !label.contains('\n'), "Label should not contain actual newlines" ); assert!( label.contains("\\n"), "Label should contain escaped newlines" ); } #[test] fn test_should_suppress_doc_warning_keybindings() { // Top-level keybindings should NOT suppress (it has its own doc) assert!(!should_suppress_doc_warning(&["keybindings".to_string()])); // Nested keybindings items SHOULD suppress assert!(should_suppress_doc_warning(&[ "keybindings".to_string(), "0".to_string() ])); assert!(should_suppress_doc_warning(&[ "keybindings".to_string(), "0".to_string(), "name".to_string() ])); assert!(should_suppress_doc_warning(&[ "keybindings".to_string(), "1".to_string(), "keycode".to_string() ])); } #[test] fn test_should_suppress_doc_warning_menus() { // Top-level menus should NOT suppress (it has its own doc) assert!(!should_suppress_doc_warning(&["menus".to_string()])); // Nested menus items SHOULD suppress assert!(should_suppress_doc_warning(&[ "menus".to_string(), "0".to_string() ])); assert!(should_suppress_doc_warning(&[ "menus".to_string(), "0".to_string(), "source".to_string() ])); } #[test] fn test_filter_tree_items_empty_query() { // Empty query should return all items unchanged let items = vec![ TreeItem::new_leaf("a".to_string(), "a: value"), TreeItem::new_leaf("b".to_string(), "b: value"), ]; let filtered = filter_tree_items(&items, ""); assert_eq!(filtered.len(), 2); } #[test] fn test_filter_tree_items_matching_leaf() { let items = vec![ TreeItem::new_leaf("color".to_string(), "color: red"), TreeItem::new_leaf("size".to_string(), "size: large"), ]; let filtered = filter_tree_items(&items, "color"); assert_eq!(filtered.len(), 1); assert_eq!(filtered[0].identifier(), "color"); } #[test] fn test_filter_tree_items_case_insensitive() { let items = vec![ TreeItem::new_leaf("Color".to_string(), "Color: red"), TreeItem::new_leaf("SIZE".to_string(), "SIZE: large"), ]; let filtered = filter_tree_items(&items, "color"); assert_eq!(filtered.len(), 1); assert_eq!(filtered[0].identifier(), "Color"); let filtered2 = filter_tree_items(&items, "SIZE"); assert_eq!(filtered2.len(), 1); } #[test] fn test_filter_tree_items_no_matches() { let items = vec![ TreeItem::new_leaf("color".to_string(), "color: red"), TreeItem::new_leaf("size".to_string(), "size: large"), ]; let filtered = filter_tree_items(&items, "nonexistent"); assert_eq!(filtered.len(), 0); } #[test] fn test_filter_tree_items_partial_match() { let items = vec![ TreeItem::new_leaf("color_config".to_string(), "color_config: {}"), TreeItem::new_leaf("history".to_string(), "history: {}"), ]; let filtered = filter_tree_items(&items, "color"); assert_eq!(filtered.len(), 1); assert_eq!(filtered[0].identifier(), "color_config"); } #[test] fn test_should_suppress_doc_warning_other_paths() { // Other config paths should NOT suppress assert!(!should_suppress_doc_warning(&["history".to_string()])); assert!(!should_suppress_doc_warning(&[ "history".to_string(), "file_format".to_string() ])); assert!(!should_suppress_doc_warning(&[ "color_config".to_string(), "string".to_string() ])); assert!(!should_suppress_doc_warning(&[])); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore_config/conversion.rs
crates/nu-explore/src/explore_config/conversion.rs
//! Conversion utilities between Nu values and JSON, and config documentation parsing. use crate::explore_config::types::NuValueType; use nu_protocol::ShellError; use nu_protocol::engine::EngineState; use nu_utils::ConfigFileKind; use serde_json::Value; use std::collections::HashMap; use std::error::Error; /// Convert a nu_protocol::Value to a serde_json::Value /// This properly handles closures by converting them to their string representation #[allow(clippy::only_used_in_recursion)] pub fn nu_value_to_json( engine_state: &EngineState, value: &nu_protocol::Value, span: nu_protocol::Span, ) -> Result<Value, ShellError> { Ok(match value { nu_protocol::Value::Bool { val, .. } => Value::Bool(*val), nu_protocol::Value::Int { val, .. } => Value::Number((*val).into()), nu_protocol::Value::Float { val, .. } => serde_json::Number::from_f64(*val) .map(Value::Number) .unwrap_or(Value::Null), nu_protocol::Value::String { val, .. } => Value::String(val.clone()), nu_protocol::Value::Nothing { .. } => Value::Null, nu_protocol::Value::List { vals, .. } => { let json_vals: Result<Vec<_>, _> = vals .iter() .map(|v| nu_value_to_json(engine_state, v, span)) .collect(); Value::Array(json_vals?) } nu_protocol::Value::Record { val, .. } => { let mut map = serde_json::Map::new(); for (k, v) in val.iter() { map.insert(k.clone(), nu_value_to_json(engine_state, v, span)?); } Value::Object(map) } nu_protocol::Value::Closure { val, .. } => { // Convert closure to its string representation instead of serializing internal structure let closure_string = val.coerce_into_string(engine_state, value.span()) .map_err(|e| ShellError::GenericError { error: "Failed to convert closure to string".to_string(), msg: "".to_string(), span: Some(value.span()), help: None, inner: vec![e], })?; Value::String(closure_string.to_string()) } nu_protocol::Value::Filesize { val, .. } => Value::Number(val.get().into()), nu_protocol::Value::Duration { val, .. } => Value::Number((*val).into()), nu_protocol::Value::Date { val, .. } => Value::String(val.to_string()), nu_protocol::Value::Glob { val, .. } => Value::String(val.to_string()), nu_protocol::Value::CellPath { val, .. } => { let parts: Vec<Value> = val .members .iter() .map(|m| match m { nu_protocol::ast::PathMember::String { val, .. } => Value::String(val.clone()), nu_protocol::ast::PathMember::Int { val, .. } => { Value::Number((*val as i64).into()) } }) .collect(); Value::Array(parts) } nu_protocol::Value::Binary { val, .. } => Value::Array( val.iter() .map(|b| Value::Number((*b as i64).into())) .collect(), ), nu_protocol::Value::Range { .. } => Value::Null, nu_protocol::Value::Error { error, .. } => { return Err(*error.clone()); } nu_protocol::Value::Custom { val, .. } => { let collected = val.to_base_value(value.span())?; nu_value_to_json(engine_state, &collected, span)? } }) } /// Parse the doc_config.nu file to extract documentation for each config path /// Returns a HashMap mapping config paths (e.g., "history.file_format") to their documentation pub fn parse_config_documentation() -> HashMap<String, String> { let doc_content = ConfigFileKind::Config.doc(); let mut doc_map = HashMap::new(); let mut current_comments: Vec<String> = Vec::new(); for line in doc_content.lines() { let trimmed = line.trim(); if trimmed.is_empty() { // Empty lines clear the comment buffer - this ensures section headings // (which are separated from actual documentation by blank lines) // don't get included in the documentation for settings current_comments.clear(); } else if trimmed.starts_with('#') { // Collect comment lines (strip the leading # and space) let comment = trimmed.trim_start_matches('#').trim(); if !comment.is_empty() { current_comments.push(comment.to_string()); } } else if trimmed.starts_with("$env.config.") { // This is a config setting line // Extract the path (everything between "$env.config." and " =" or end of relevant part) if let Some(path) = extract_config_path(trimmed) && !current_comments.is_empty() { // Join all collected comments as the documentation let doc = current_comments.join("\n"); doc_map.insert(path, doc); } // Clear comments after processing a setting current_comments.clear(); } else { // Non-comment, non-config, non-empty line - might be code examples, clear comments current_comments.clear(); } } doc_map } /// Extract the config path from a line like "$env.config.history.file_format = ..." /// Returns the path without "$env.config." prefix (e.g., "history.file_format") pub fn extract_config_path(line: &str) -> Option<String> { let line = line.trim(); if !line.starts_with("$env.config.") { return None; } // Remove "$env.config." prefix let rest = &line["$env.config.".len()..]; // Find where the path ends (at '=' or end of line for bare references) let path_end = rest.find(['=', ' ']).unwrap_or(rest.len()); let path = rest[..path_end].trim(); if path.is_empty() { None } else { Some(path.to_string()) } } /// Build a map of path identifiers to NuValueType for tracking original nushell types pub fn build_nu_type_map( value: &nu_protocol::Value, current_path: Vec<String>, type_map: &mut HashMap<String, NuValueType>, ) { let identifier = path_to_identifier(&current_path); if !identifier.is_empty() { type_map.insert(identifier.clone(), NuValueType::from_nu_value(value)); } match value { nu_protocol::Value::Record { val, .. } => { for (k, v) in val.iter() { let mut path = current_path.clone(); path.push(k.clone()); build_nu_type_map(v, path, type_map); } } nu_protocol::Value::List { vals, .. } => { for (idx, v) in vals.iter().enumerate() { let mut path = current_path.clone(); path.push(idx.to_string()); build_nu_type_map(v, path, type_map); } } _ => {} } } /// Build a map of path identifiers to original Nu values for types that can't be roundtripped /// (like Closures, Dates, Ranges, etc.) pub fn build_original_value_map( value: &nu_protocol::Value, current_path: Vec<String>, value_map: &mut HashMap<String, nu_protocol::Value>, ) { let identifier = path_to_identifier(&current_path); // Store values that can't be roundtripped through JSON if !identifier.is_empty() { match value { nu_protocol::Value::Closure { .. } | nu_protocol::Value::Date { .. } | nu_protocol::Value::Range { .. } => { value_map.insert(identifier.clone(), value.clone()); } _ => {} } } match value { nu_protocol::Value::Record { val, .. } => { for (k, v) in val.iter() { let mut path = current_path.clone(); path.push(k.clone()); build_original_value_map(v, path, value_map); } } nu_protocol::Value::List { vals, .. } => { for (idx, v) in vals.iter().enumerate() { let mut path = current_path.clone(); path.push(idx.to_string()); build_original_value_map(v, path, value_map); } } _ => {} } } /// Convert a path vector to an identifier string (e.g., ["history", "file_format"] -> "history.file_format") fn path_to_identifier(path: &[String]) -> String { if path.is_empty() { String::new() } else { path.iter() .enumerate() .map(|(i, p)| { if p.parse::<usize>().is_ok() { format!("[{}]", p) } else if i == 0 { p.clone() } else { format!(".{}", p) } }) .collect::<String>() } } /// Convert a serde_json::Value to a nu_protocol::Value (simple version without type info) #[allow(dead_code)] pub fn json_to_nu_value( json: &Value, span: nu_protocol::Span, ) -> Result<nu_protocol::Value, Box<dyn Error>> { json_to_nu_value_with_types(json, span, &None, &None, Vec::new()) } /// Convert a serde_json::Value to a nu_protocol::Value, using type information to preserve /// original Nu types like Duration, Filesize, and Closure pub fn json_to_nu_value_with_types( json: &Value, span: nu_protocol::Span, type_map: &Option<HashMap<String, NuValueType>>, original_values: &Option<HashMap<String, nu_protocol::Value>>, current_path: Vec<String>, ) -> Result<nu_protocol::Value, Box<dyn Error>> { let identifier = path_to_identifier(&current_path); let original_type = type_map.as_ref().and_then(|m| m.get(&identifier)); Ok(match json { Value::Null => nu_protocol::Value::nothing(span), Value::Bool(b) => nu_protocol::Value::bool(*b, span), Value::Number(n) => { // Check if we need to convert to a special type based on original if let Some(orig_type) = original_type { match orig_type { NuValueType::Duration => { if let Some(i) = n.as_i64() { return Ok(nu_protocol::Value::duration(i, span)); } } NuValueType::Filesize => { if let Some(i) = n.as_i64() { return Ok(nu_protocol::Value::filesize(i, span)); } } _ => {} } } // Default number handling if let Some(i) = n.as_i64() { nu_protocol::Value::int(i, span) } else if let Some(f) = n.as_f64() { nu_protocol::Value::float(f, span) } else { return Err(format!("Unsupported number: {}", n).into()); } } Value::String(s) => { // Check if we need to restore an original value that can't be roundtripped if let Some(orig_type) = original_type { match orig_type { NuValueType::Closure | NuValueType::Date | NuValueType::Range => { // Try to get the original value - closures, dates, and ranges // can't be reconstructed from their string representation if let Some(original_values_map) = original_values && let Some(original_value) = original_values_map.get(&identifier) { // Return the original value since we can't reconstruct these types return Ok(original_value.clone()); } // If no original value found, keep as string // This will likely cause a config error, but that's the expected behavior // since the user modified something that can't be properly converted } NuValueType::Glob => { return Ok(nu_protocol::Value::glob(s.clone(), false, span)); } _ => {} } } nu_protocol::Value::string(s.clone(), span) } Value::Array(arr) => { // Check if this was originally binary data if let Some(NuValueType::Binary) = original_type { let bytes: Result<Vec<u8>, _> = arr .iter() .map(|v| { v.as_i64() .and_then(|i| u8::try_from(i).ok()) .ok_or("Invalid byte value") }) .collect(); if let Ok(bytes) = bytes { return Ok(nu_protocol::Value::binary(bytes, span)); } } // Check if this was originally a CellPath if let Some(NuValueType::CellPath) = original_type { use nu_protocol::ast::PathMember; use nu_protocol::casing::Casing; let members: Result<Vec<PathMember>, _> = arr .iter() .map(|v| match v { Value::String(s) => Ok(PathMember::String { val: s.clone(), span, optional: false, casing: Casing::Sensitive, }), Value::Number(n) => { if let Some(i) = n.as_u64() { Ok(PathMember::Int { val: i as usize, span, optional: false, }) } else { Err("Invalid cell path member") } } _ => Err("Invalid cell path member"), }) .collect(); if let Ok(members) = members { return Ok(nu_protocol::Value::cell_path( nu_protocol::ast::CellPath { members }, span, )); } } // Regular array/list let values: Result<Vec<_>, _> = arr .iter() .enumerate() .map(|(idx, v)| { let mut path = current_path.clone(); path.push(idx.to_string()); json_to_nu_value_with_types(v, span, type_map, original_values, path) }) .collect(); nu_protocol::Value::list(values?, span) } Value::Object(obj) => { let mut record = nu_protocol::Record::new(); for (k, v) in obj { let mut path = current_path.clone(); path.push(k.clone()); record.push( k.clone(), json_to_nu_value_with_types(v, span, type_map, original_values, path)?, ); } nu_protocol::Value::record(record, span) } }) } #[cfg(test)] mod tests { use super::*; use nu_protocol::Span; fn test_span() -> Span { Span::test_data() } #[test] fn test_duration_roundtrip() { // Create a type map with a duration type let mut type_map = HashMap::new(); type_map.insert("timeout".to_string(), NuValueType::Duration); let type_map = Some(type_map); // Create JSON with a number that should be converted to duration let json = serde_json::json!({ "timeout": 5000000000_i64 // 5 seconds in nanoseconds }); let result = json_to_nu_value_with_types(&json, test_span(), &type_map, &None, Vec::new()).unwrap(); // Check that it's a record with a duration value if let nu_protocol::Value::Record { val, .. } = result { let timeout = val.get("timeout").expect("timeout field should exist"); assert!( matches!(timeout, nu_protocol::Value::Duration { .. }), "Expected Duration, got {:?}", timeout ); if let nu_protocol::Value::Duration { val, .. } = timeout { assert_eq!(*val, 5000000000); } } else { panic!("Expected Record, got {:?}", result); } } #[test] fn test_filesize_roundtrip() { let mut type_map = HashMap::new(); type_map.insert("size".to_string(), NuValueType::Filesize); let type_map = Some(type_map); let json = serde_json::json!({ "size": 1048576_i64 // 1 MiB in bytes }); let result = json_to_nu_value_with_types(&json, test_span(), &type_map, &None, Vec::new()).unwrap(); if let nu_protocol::Value::Record { val, .. } = result { let size = val.get("size").expect("size field should exist"); assert!( matches!(size, nu_protocol::Value::Filesize { .. }), "Expected Filesize, got {:?}", size ); } else { panic!("Expected Record, got {:?}", result); } } #[test] fn test_nested_duration() { let mut type_map = HashMap::new(); type_map.insert( "plugin_gc.default.stop_after".to_string(), NuValueType::Duration, ); let type_map = Some(type_map); let json = serde_json::json!({ "plugin_gc": { "default": { "stop_after": 0_i64 } } }); let result = json_to_nu_value_with_types(&json, test_span(), &type_map, &None, Vec::new()).unwrap(); // Navigate to the nested value if let nu_protocol::Value::Record { val: outer, .. } = result { let plugin_gc = outer.get("plugin_gc").expect("plugin_gc should exist"); if let nu_protocol::Value::Record { val: inner, .. } = plugin_gc { let default = inner.get("default").expect("default should exist"); if let nu_protocol::Value::Record { val: default_rec, .. } = default { let stop_after = default_rec .get("stop_after") .expect("stop_after should exist"); assert!( matches!(stop_after, nu_protocol::Value::Duration { .. }), "Expected Duration, got {:?}", stop_after ); } else { panic!("Expected Record for default"); } } else { panic!("Expected Record for plugin_gc"); } } else { panic!("Expected Record"); } } #[test] fn test_closure_restored_from_original() { // Create a type map marking this as a closure let mut type_map = HashMap::new(); type_map.insert("hook".to_string(), NuValueType::Closure); let type_map = Some(type_map); // Create an original value map with the closure let mut original_values = HashMap::new(); // We can't easily create a real closure in tests, so we'll test the path exists // In practice, the original closure value would be stored here let json = serde_json::json!({ "hook": "{|| print 'hello'}" }); // Without original value, it stays as string let result = json_to_nu_value_with_types( &json, test_span(), &type_map, &Some(original_values.clone()), Vec::new(), ) .unwrap(); if let nu_protocol::Value::Record { val, .. } = result { let hook = val.get("hook").expect("hook field should exist"); // Without an original value stored, it remains a string assert!( matches!(hook, nu_protocol::Value::String { .. }), "Expected String when no original closure available, got {:?}", hook ); } else { panic!("Expected Record"); } // Now test with an original value stored (using a simple value as stand-in) // In real usage, this would be the actual Closure value original_values.insert( "hook".to_string(), nu_protocol::Value::string("original_closure_placeholder", test_span()), ); let result = json_to_nu_value_with_types( &json, test_span(), &type_map, &Some(original_values), Vec::new(), ) .unwrap(); if let nu_protocol::Value::Record { val, .. } = result { let hook = val.get("hook").expect("hook field should exist"); // With original value stored, it should return that value if let nu_protocol::Value::String { val: s, .. } = hook { assert_eq!(s, "original_closure_placeholder"); } else { panic!("Expected the original value to be returned"); } } else { panic!("Expected Record"); } } #[test] fn test_glob_roundtrip() { let mut type_map = HashMap::new(); type_map.insert("pattern".to_string(), NuValueType::Glob); let type_map = Some(type_map); let json = serde_json::json!({ "pattern": "*.txt" }); let result = json_to_nu_value_with_types(&json, test_span(), &type_map, &None, Vec::new()).unwrap(); if let nu_protocol::Value::Record { val, .. } = result { let pattern = val.get("pattern").expect("pattern field should exist"); assert!( matches!(pattern, nu_protocol::Value::Glob { .. }), "Expected Glob, got {:?}", pattern ); } else { panic!("Expected Record"); } } #[test] fn test_binary_roundtrip() { let mut type_map = HashMap::new(); type_map.insert("data".to_string(), NuValueType::Binary); let type_map = Some(type_map); let json = serde_json::json!({ "data": [0, 1, 2, 255] }); let result = json_to_nu_value_with_types(&json, test_span(), &type_map, &None, Vec::new()).unwrap(); if let nu_protocol::Value::Record { val, .. } = result { let data = val.get("data").expect("data field should exist"); assert!( matches!(data, nu_protocol::Value::Binary { .. }), "Expected Binary, got {:?}", data ); if let nu_protocol::Value::Binary { val, .. } = data { assert_eq!(val, &vec![0u8, 1, 2, 255]); } } else { panic!("Expected Record"); } } #[test] fn test_list_with_typed_elements() { let mut type_map = HashMap::new(); type_map.insert("timeouts[0]".to_string(), NuValueType::Duration); type_map.insert("timeouts[1]".to_string(), NuValueType::Duration); let type_map = Some(type_map); let json = serde_json::json!({ "timeouts": [1000000000_i64, 2000000000_i64] }); let result = json_to_nu_value_with_types(&json, test_span(), &type_map, &None, Vec::new()).unwrap(); if let nu_protocol::Value::Record { val, .. } = result { let timeouts = val.get("timeouts").expect("timeouts field should exist"); if let nu_protocol::Value::List { vals, .. } = timeouts { assert_eq!(vals.len(), 2); for (i, v) in vals.iter().enumerate() { assert!( matches!(v, nu_protocol::Value::Duration { .. }), "Expected Duration at index {}, got {:?}", i, v ); } } else { panic!("Expected List"); } } else { panic!("Expected Record"); } } #[test] fn test_without_type_map_uses_defaults() { // Without a type map, numbers stay as numbers, strings as strings let json = serde_json::json!({ "timeout": 5000000000_i64, "name": "test" }); let result = json_to_nu_value_with_types(&json, test_span(), &None, &None, Vec::new()).unwrap(); if let nu_protocol::Value::Record { val, .. } = result { let timeout = val.get("timeout").expect("timeout field should exist"); assert!( matches!(timeout, nu_protocol::Value::Int { .. }), "Expected Int without type map, got {:?}", timeout ); let name = val.get("name").expect("name field should exist"); assert!( matches!(name, nu_protocol::Value::String { .. }), "Expected String, got {:?}", name ); } else { panic!("Expected Record"); } } #[test] fn test_path_to_identifier() { assert_eq!(path_to_identifier(&[]), ""); assert_eq!(path_to_identifier(&["foo".to_string()]), "foo"); assert_eq!( path_to_identifier(&["foo".to_string(), "bar".to_string()]), "foo.bar" ); assert_eq!( path_to_identifier(&["foo".to_string(), "0".to_string()]), "foo[0]" ); assert_eq!( path_to_identifier(&["foo".to_string(), "0".to_string(), "bar".to_string()]), "foo[0].bar" ); } #[test] fn test_build_nu_type_map() { let span = test_span(); // Create a nested Nu value structure let mut inner_record = nu_protocol::Record::new(); inner_record.push( "stop_after".to_string(), nu_protocol::Value::duration(0, span), ); let mut outer_record = nu_protocol::Record::new(); outer_record.push( "default".to_string(), nu_protocol::Value::record(inner_record, span), ); let mut root_record = nu_protocol::Record::new(); root_record.push( "plugin_gc".to_string(), nu_protocol::Value::record(outer_record, span), ); let root_value = nu_protocol::Value::record(root_record, span); let mut type_map = HashMap::new(); build_nu_type_map(&root_value, Vec::new(), &mut type_map); assert_eq!(type_map.get("plugin_gc"), Some(&NuValueType::Record)); assert_eq!( type_map.get("plugin_gc.default"), Some(&NuValueType::Record) ); assert_eq!( type_map.get("plugin_gc.default.stop_after"), Some(&NuValueType::Duration) ); } #[test] fn test_build_original_value_map() { let span = test_span(); // Create a structure with a duration (which can be roundtripped) and simulate // what would happen with non-roundtrippable types let mut record = nu_protocol::Record::new(); record.push( "duration".to_string(), nu_protocol::Value::duration(0, span), ); record.push( "string".to_string(), nu_protocol::Value::string("test", span), ); let root_value = nu_protocol::Value::record(record, span); let mut value_map = HashMap::new(); build_original_value_map(&root_value, Vec::new(), &mut value_map); // Duration and String are roundtrippable, so they shouldn't be in the map assert!(!value_map.contains_key("duration")); assert!(!value_map.contains_key("string")); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore_config/types.rs
crates/nu-explore/src/explore_config/types.rs
//! Type definitions for the explore config TUI application. use nu_protocol::engine::{EngineState, Stack}; use ratatui::style::Color; use serde_json::Value; use std::collections::HashMap; use std::sync::Arc; /// Path through the JSON tree represented as a vector of keys/indices pub type NodePath = Vec<String>; /// Mode for the editor pane #[derive(Debug, Clone, Copy, PartialEq)] pub enum EditorMode { Normal, Editing, } /// Information about a node in the tree #[derive(Debug, Clone)] pub struct NodeInfo { pub path: NodePath, pub value_type: ValueType, pub nu_type: Option<NuValueType>, } /// JSON value types #[derive(Debug, Clone, Copy, PartialEq)] pub enum ValueType { Null, Bool, Number, String, Array, Object, } /// Nushell-specific value types for display in config mode #[derive(Debug, Clone, PartialEq)] pub enum NuValueType { Nothing, Bool, Int, Float, String, List, Record, Closure, Filesize, Duration, Date, Glob, CellPath, Binary, Range, Custom(String), Error, } impl NuValueType { pub fn from_nu_value(value: &nu_protocol::Value) -> Self { match value { nu_protocol::Value::Nothing { .. } => NuValueType::Nothing, nu_protocol::Value::Bool { .. } => NuValueType::Bool, nu_protocol::Value::Int { .. } => NuValueType::Int, nu_protocol::Value::Float { .. } => NuValueType::Float, nu_protocol::Value::String { .. } => NuValueType::String, nu_protocol::Value::List { .. } => NuValueType::List, nu_protocol::Value::Record { .. } => NuValueType::Record, nu_protocol::Value::Closure { .. } => NuValueType::Closure, nu_protocol::Value::Filesize { .. } => NuValueType::Filesize, nu_protocol::Value::Duration { .. } => NuValueType::Duration, nu_protocol::Value::Date { .. } => NuValueType::Date, nu_protocol::Value::Glob { .. } => NuValueType::Glob, nu_protocol::Value::CellPath { .. } => NuValueType::CellPath, nu_protocol::Value::Binary { .. } => NuValueType::Binary, nu_protocol::Value::Range { .. } => NuValueType::Range, nu_protocol::Value::Custom { val, .. } => NuValueType::Custom(val.type_name()), nu_protocol::Value::Error { .. } => NuValueType::Error, } } pub fn label(&self) -> &str { match self { NuValueType::Nothing => "nothing", NuValueType::Bool => "bool", NuValueType::Int => "int", NuValueType::Float => "float", NuValueType::String => "string", NuValueType::List => "list", NuValueType::Record => "record", NuValueType::Closure => "closure", NuValueType::Filesize => "filesize", NuValueType::Duration => "duration", NuValueType::Date => "date", NuValueType::Glob => "glob", NuValueType::CellPath => "cell-path", NuValueType::Binary => "binary", NuValueType::Range => "range", NuValueType::Custom(name) => name, NuValueType::Error => "error", } } pub fn color(&self) -> Color { match self { NuValueType::Nothing => Color::DarkGray, NuValueType::Bool => Color::LightCyan, NuValueType::Int => Color::Magenta, NuValueType::Float => Color::Magenta, NuValueType::String => Color::Green, NuValueType::List => Color::Yellow, NuValueType::Record => Color::Blue, NuValueType::Closure => Color::Cyan, NuValueType::Filesize => Color::LightMagenta, NuValueType::Duration => Color::LightMagenta, NuValueType::Date => Color::LightYellow, NuValueType::Glob => Color::LightGreen, NuValueType::CellPath => Color::LightBlue, NuValueType::Binary => Color::Gray, NuValueType::Range => Color::Yellow, NuValueType::Custom(_) => Color::Rgb(255, 165, 0), // Orange NuValueType::Error => Color::Red, } } } impl ValueType { pub fn from_value(value: &Value) -> Self { match value { Value::Null => ValueType::Null, Value::Bool(_) => ValueType::Bool, Value::Number(_) => ValueType::Number, Value::String(_) => ValueType::String, Value::Array(_) => ValueType::Array, Value::Object(_) => ValueType::Object, } } pub fn label(&self) -> &'static str { match self { ValueType::Null => "null", ValueType::Bool => "boolean", ValueType::Number => "number", ValueType::String => "string", ValueType::Array => "array", ValueType::Object => "object", } } pub fn color(&self) -> Color { match self { ValueType::Null => Color::DarkGray, ValueType::Bool => Color::Magenta, ValueType::Number => Color::Cyan, ValueType::String => Color::Green, ValueType::Array => Color::Yellow, ValueType::Object => Color::Blue, } } } /// Result from running the app - whether to continue or quit pub enum AppResult { Continue, Quit, } /// Represents a cursor position within multi-line text #[derive(Debug, Clone, Copy)] pub struct CursorPosition { /// The line number (0-indexed) pub line: usize, /// The column within the line (0-indexed) pub col: usize, } /// Calculate the line and column position of a cursor within multi-line text /// /// # Arguments /// * `content` - The text content to analyze /// * `cursor` - The cursor position as a byte offset /// /// # Returns /// A `CursorPosition` with the line and column numbers (both 0-indexed) pub fn calculate_cursor_position(content: &str, cursor: usize) -> CursorPosition { let mut pos = 0; let mut cursor_line = 0; let mut cursor_col = 0; for (line_idx, line) in content.lines().enumerate() { if pos + line.len() >= cursor { cursor_line = line_idx; cursor_col = cursor - pos; break; } pos += line.len() + 1; // +1 for newline cursor_line = line_idx + 1; } CursorPosition { line: cursor_line, col: cursor_col, } } /// Focus mode including search #[derive(Debug, Clone, Copy, PartialEq)] pub enum Focus { Tree, Editor, Search, } /// The main application state for the TUI pub struct App { pub tree_state: tui_tree_widget::TreeState<String>, pub json_data: Value, pub tree_items: Vec<tui_tree_widget::TreeItem<'static, String>>, /// Unfiltered tree items - used to restore after clearing search pub unfiltered_tree_items: Vec<tui_tree_widget::TreeItem<'static, String>>, pub node_map: HashMap<String, NodeInfo>, pub focus: Focus, pub editor_mode: EditorMode, pub editor_content: String, pub editor_cursor: usize, pub editor_scroll: usize, pub selected_identifier: String, pub status_message: String, pub modified: bool, /// In config mode, tracks whether user has confirmed they want to save (via Ctrl+S) pub confirmed_save: bool, pub output_file: Option<String>, pub config_mode: bool, /// Type map for preserving Nushell types across tree rebuilds in config mode pub nu_type_map: Option<HashMap<String, NuValueType>>, pub doc_map: Option<HashMap<String, String>>, /// Search/filter state pub search_query: String, pub search_active: bool, /// Engine state for syntax highlighting pub engine_state: Arc<EngineState>, /// Stack for syntax highlighting pub stack: Arc<Stack>, }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore_config/example_data.rs
crates/nu-explore/src/explore_config/example_data.rs
//! Example JSON data for testing the explore config TUI. use serde_json::Value; /// Example JSON data for testing (nushell config) #[allow(dead_code)] pub fn get_example_json() -> Value { let json_str = r##"{ "filesize": { "unit": "B", "show_unit": false, "precision": 2 }, "table": { "mode": "rounded", "index_mode": "always", "show_empty": false, "padding": { "left": 1, "right": 1 }, "trim": { "methodology": "wrapping", "wrapping_try_keep_words": true }, "header_on_separator": true, "abbreviated_row_count": null, "footer_inheritance": true, "missing_value_symbol": "❎", "batch_duration": 1000000000, "stream_page_size": 1000 }, "ls": { "use_ls_colors": true, "clickable_links": true }, "color_config": { "shape_internallcall": "cyan_bold", "leading_trailing_space_bg": { "bg": "dark_gray_dimmed" }, "string": "{|x| if $x =~ '^#[a-fA-F\\d]+' { $x } else { 'default' } }", "date": "{||\n (date now) - $in | if $in < 1hr {\n 'red3b' #\"\\e[38;5;160m\" #'#e61919' # 160\n } else if $in < 6hr {\n 'orange3' #\"\\e[38;5;172m\" #'#e68019' # 172\n } else if $in < 1day {\n 'yellow3b' #\"\\e[38;5;184m\" #'#e5e619' # 184\n } else if $in < 3day {\n 'chartreuse2b' #\"\\e[38;5;112m\" #'#80e619' # 112\n } else if $in < 1wk {\n 'green3b' #\"\\e[38;5;40m\" #'#19e619' # 40\n } else if $in < 6wk {\n 'darkturquoise' #\"\\e[38;5;44m\" #'#19e5e6' # 44\n } else if $in < 52wk {\n 'deepskyblue3b' #\"\\e[38;5;32m\" #'#197fe6' # 32\n } else { 'dark_gray' }\n }", "hints": "dark_gray", "shape_matching_brackets": { "fg": "red", "bg": "default", "attr": "b" }, "nothing": "red", "shape_string_interpolation": "cyan_bold", "shape_externalarg": "light_purple", "shape_external_resolved": "light_yellow_bold", "cellpath": "cyan", "foreground": "green3b", "shape_filepath": "cyan", "separator": "yd", "shape_garbage": { "fg": "red", "attr": "u" }, "shape_external": "darkorange", "float": "red", "shape_block": "#33ff00", "shape_bool": "{|| if $in { 'light_cyan' } else { 'light_red' } }", "binary": "red", "duration": "blue_bold", "header": "cb", "filesize": "{|e| if $e == 0b { 'black' } else if $e < 1mb { 'ub' } else { 'cyan' } }", "range": "purple", "search_result": "blue_reverse", "bool": "{|| if $in { 'light_cyan' } else { 'light_red' } }", "int": "green", "row_index": "yb", "shape_closure": "#ffb000" }, "footer_mode": "auto", "float_precision": 2, "recursion_limit": 50, "use_ansi_coloring": "true", "completions": { "sort": "smart", "case_sensitive": false, "quick": true, "partial": true, "algorithm": "prefix", "external": { "enable": true, "max_results": 10, "completer": null }, "use_ls_colors": true }, "edit_mode": "emacs", "history": { "max_size": 1000000, "sync_on_enter": true, "file_format": "sqlite", "isolation": true }, "keybindings": [ { "name": "open_command_editor", "modifier": "control", "keycode": "char_o", "event": { "send": "openeditor" }, "mode": [ "emacs", "vi_normal", "vi_insert" ] }, { "name": "clear_everything", "modifier": "control", "keycode": "char_l", "event": [ { "send": "clearscrollback" } ], "mode": "emacs" }, { "name": "insert_newline", "modifier": "shift", "keycode": "enter", "event": { "edit": "insertnewline" }, "mode": "emacs" }, { "name": "completion_menu", "modifier": "none", "keycode": "tab", "event": { "until": [ { "send": "menu", "name": "completion_menu" }, { "send": "menunext" } ] }, "mode": "emacs" }, { "name": "completion_previous", "modifier": "shift", "keycode": "backtab", "event": { "send": "menuprevious" }, "mode": "emacs" }, { "name": "insert_last_token", "modifier": "alt", "keycode": "char_.", "event": [ { "edit": "insertstring", "value": " !$" }, { "send": "enter" } ], "mode": "emacs" }, { "name": "complete_hint_chunk", "modifier": "alt", "keycode": "right", "event": { "until": [ { "send": "historyhintwordcomplete" }, { "edit": "movewordright" } ] }, "mode": "emacs" }, { "name": "un_complete_hint_chunk", "modifier": "alt", "keycode": "left", "event": [ { "edit": "backspaceword" } ], "mode": "emacs" }, { "name": "delete-word", "modifier": "control", "keycode": "backspace", "event": { "until": [ { "edit": "backspaceword" } ] }, "mode": [ "emacs", "vi_normal", "vi_insert" ] }, { "name": "trigger-history-menu", "modifier": "control", "keycode": "char_x", "event": { "until": [ { "send": "menu", "name": "history_menu" }, { "send": "menupagenext" } ] }, "mode": "emacs" }, { "name": "trigger-history-previous", "modifier": "control", "keycode": "char_z", "event": { "until": [ { "send": "menupageprevious" }, { "edit": "undo" } ] }, "mode": "emacs" }, { "name": "change_dir_with_fzf", "modifier": "control", "keycode": "char_f", "event": { "send": "executehostcommand", "cmd": "cd (ls | where type == dir | each { |it| $it.name} | str join (char nl) | fzf | decode utf-8 | str trim)" }, "mode": "emacs" }, { "name": "complete_in_cd", "modifier": "none", "keycode": "f2", "event": [ { "edit": "clear" }, { "edit": "insertString", "value": "./" }, { "send": "Menu", "name": "completion_menu" } ], "mode": "emacs" }, { "name": "reload_config", "modifier": "none", "keycode": "f5", "event": [ { "edit": "clear" }, { "send": "executehostcommand", "cmd": "source C:\\Users\\username\\AppData\\Roaming\\nushell\\env.nu; source C:\\Users\\username\\AppData\\Roaming\\nushell\\config.nu" } ], "mode": [ "emacs", "vi_insert", "vi_normal" ] }, { "name": "clear", "modifier": "none", "keycode": "esc", "event": { "edit": "clear" }, "mode": "emacs" }, { "name": "test_fkeys", "modifier": "none", "keycode": "f3", "event": [ { "edit": "clear" }, { "edit": "insertstring", "value": "C:\\Users\\username\\source\\repos\\forks\\nushell" } ], "mode": "emacs" }, { "name": "abbr", "modifier": "control", "keycode": "space", "event": [ { "send": "menu", "name": "abbr_menu" }, { "edit": "insertchar", "value": " " } ], "mode": [ "emacs", "vi_normal", "vi_insert" ] }, { "name": "fzf_edit", "modifier": "control", "keycode": "char_d", "event": [ { "send": "executehostcommand", "cmd": "do { |$file| if (not ($file | is-empty)) { nvim $file } } (fzf | str trim)" } ], "mode": [ "emacs", "vi_normal", "vi_insert" ] }, { "name": "history_menu_by_session", "modifier": "alt", "keycode": "char_r", "event": { "send": "menu", "name": "history_menu_by_session" }, "mode": "emacs" }, { "name": "fuzzy_history", "modifier": "control", "keycode": "char_r", "event": [ { "send": "ExecuteHostCommand", "cmd": "do {\n $env.SHELL = 'c:/progra~1/git/usr/bin/bash.exe'\n commandline edit -r (\n history\n | get command\n | reverse\n | uniq\n | str join (char -i 0)\n | fzf --scheme=history --read0 --layout=reverse --height=40% --bind 'tab:change-preview-window(right,70%|right)' -q (commandline) --preview='echo -n {} | nu --stdin -c 'nu-highlight''\n | decode utf-8\n | str trim\n )\n }" } ], "mode": [ "emacs", "vi_normal", "vi_insert" ] }, { "name": "fuzzy_dir", "modifier": "control", "keycode": "char_s", "event": { "send": "executehostcommand", "cmd": "commandline edit -a (ls **/* | where type == dir | get name | to text | fzf -q (commandline) | str trim);commandline set-cursor --end" }, "mode": "emacs" }, { "name": "fzf_dir_menu_nu_ui", "modifier": "control", "keycode": "char_n", "event": { "send": "menu", "name": "fzf_dir_menu_nu_ui" }, "mode": [ "emacs", "vi_normal", "vi_insert" ] }, { "name": "fzf_history_menu_fzf_ui", "modifier": "control", "keycode": "char_e", "event": { "send": "menu", "name": "fzf_history_menu_fzf_ui" }, "mode": [ "emacs", "vi_normal", "vi_insert" ] }, { "name": "fzf_history_menu_nu_ui", "modifier": "control", "keycode": "char_w", "event": { "send": "menu", "name": "fzf_history_menu_nu_ui" }, "mode": [ "emacs", "vi_normal", "vi_insert" ] }, { "name": "commands_menu", "modifier": "control", "keycode": "char_t", "event": { "send": "menu", "name": "commands_menu" }, "mode": [ "emacs", "vi_normal", "vi_insert" ] }, { "name": "vars_menu", "modifier": "control", "keycode": "char_y", "event": { "send": "menu", "name": "vars_menu" }, "mode": [ "emacs", "vi_normal", "vi_insert" ] }, { "name": "commands_with_description", "modifier": "control", "keycode": "char_u", "event": { "send": "menu", "name": "commands_with_description" }, "mode": [ "emacs", "vi_normal", "vi_insert" ] }, { "name": "trigger-help-menu", "modifier": "control", "keycode": "char_q", "event": { "until": [ { "send": "menu", "name": "help_menu" }, { "send": "menunext" } ] }, "mode": "emacs" }, { "name": "copy_selection", "modifier": "control_shift", "keycode": "char_c", "event": { "edit": "copyselection" }, "mode": "emacs" }, { "name": "cut_selection", "modifier": "control_shift", "keycode": "char_x", "event": { "edit": "cutselection" }, "mode": "emacs" }, { "name": "select_all", "modifier": "control_shift", "keycode": "char_a", "event": { "edit": "selectall" }, "mode": "emacs" }, { "name": "paste", "modifier": "control_shift", "keycode": "char_v", "event": { "edit": "pastecutbufferbefore" }, "mode": "emacs" }, { "name": "ide_completion_menu", "modifier": "control", "keycode": "char_n", "event": { "until": [ { "send": "menu", "name": "ide_completion_menu" }, { "send": "menunext" }, { "edit": "complete" } ] }, "mode": [ "emacs", "vi_normal", "vi_insert" ] }, { "name": "quick_assign", "modifier": "alt", "keycode": "char_a", "event": [ { "edit": "MoveToStart" }, { "edit": "InsertString", "value": "let foo = " }, { "edit": "MoveLeftBefore", "value": "o" }, { "edit": "MoveLeftUntil", "value": "f", "select": true } ], "mode": [ "emacs", "vi_insert", "vi_normal" ] } ], "menus": [ { "name": "ide_completion_menu", "marker": " \n❯ 📎 ", "only_buffer_difference": false, "style": { "text": "green", "selected_text": { "attr": "r" }, "description_text": "yellow", "match_text": { "fg": "#33ff00" }, "selected_match_text": { "fg": "#33ff00", "attr": "r" } }, "type": { "layout": "ide", "min_completion_width": 0, "max_completion_width": 50, "padding": 0, "border": true, "cursor_offset": 0, "description_mode": "prefer_right", "min_description_width": 0, "max_description_width": 50, "max_description_height": 10, "description_offset": 1, "correct_cursor_pos": true }, "source": null }, { "name": "completion_menu", "marker": " \n❯ 📎 ", "only_buffer_difference": false, "style": { "text": "green", "selected_text": { "attr": "r" }, "description_text": "yellow", "match_text": { "fg": "#33ff00" }, "selected_match_text": { "fg": "#33ff00", "attr": "r" } }, "type": { "layout": "columnar", "columns": 4, "col_width": 20, "col_padding": 2, "tab_traversal": "vertical" }, "source": null }, { "name": "history_menu", "marker": "🔍 ", "only_buffer_difference": false, "style": { "text": "#ffb000", "selected_text": { "fg": "#ffb000", "attr": "r" }, "description_text": "yellow" }, "type": { "layout": "list", "page_size": 10 }, "source": null }, { "name": "help_menu", "marker": "? ", "only_buffer_difference": true, "style": { "text": "#7F00FF", "selected_text": { "fg": "#ffff00", "bg": "#7F00FF", "attr": "b" }, "description_text": "#ffff00" }, "type": { "layout": "description", "columns": 4, "col_width": 20, "col_padding": 2, "selection_rows": 4, "description_rows": 10 }, "source": null }, { "name": "fzf_history_menu_fzf_ui", "marker": "# ", "only_buffer_difference": false, "style": { "text": "green", "selected_text": "green_reverse", "description_text": "yellow" }, "type": { "layout": "columnar", "columns": 4, "col_width": 20, "col_padding": 2 }, "source": "{|buffer, position|\n open $nu.history-path | get history.command_line | to text | fzf +s --tac | str trim\n | where $it =~ $buffer\n | each {|v| {value: ($v | str trim)} }\n }" }, { "name": "fzf_history_menu_nu_ui", "marker": "# ", "only_buffer_difference": false, "style": { "text": "#66ff66", "selected_text": { "fg": "#66ff66", "attr": "r" }, "description_text": "yellow" }, "type": { "layout": "list", "page_size": 10 }, "source": "{|buffer, position|\n open $nu.history-path | get history.command_line | to text\n | fzf -f $buffer\n | lines\n | each {|v| {value: ($v | str trim)} }\n }" }, { "name": "fzf_dir_menu_nu_ui", "marker": "# ", "only_buffer_difference": true, "style": { "text": "#66ff66", "selected_text": { "fg": "#66ff66", "attr": "r" }, "description_text": "yellow" }, "type": { "layout": "list", "page_size": 10 }, "source": "{|buffer, position|\n ls $env.PWD | where type == dir\n | sort-by name | get name | to text\n | fzf -f $buffer\n | each {|v| {value: ($v | str trim)} }\n }" }, { "name": "commands_menu", "marker": "# ", "only_buffer_difference": false, "style": { "text": "green", "selected_text": "green_reverse", "description_text": "yellow" }, "type": { "layout": "columnar", "columns": 4, "col_width": 20, "col_padding": 2 }, "source": "{|buffer, position|\n scope commands\n | where name =~ $buffer\n | each {|it| {value: $it.name description: $it.usage} }\n }" }, { "name": "vars_menu", "marker": "V ", "only_buffer_difference": true, "style": { "text": "green", "selected_text": "green_reverse", "description_text": "yellow" }, "type": { "layout": "list", "page_size": 10 }, "source": "{|buffer, position|\n scope variables\n | where name =~ $buffer\n | sort-by name\n | each {|it| {value: $it.name description: $it.type} }\n }" }, { "name": "commands_with_description", "marker": "# ", "only_buffer_difference": true, "style": { "text": "green", "selected_text": "green_reverse", "description_text": "yellow" }, "type": { "layout": "description", "columns": 4, "col_width": 20, "col_padding": 2, "selection_rows": 4, "description_rows": 10 }, "source": "{|buffer, position|\n scope commands\n | where name =~ $buffer\n | each {|it| {value: $it.name description: $it.usage} }\n }" }, { "name": "abbr_menu", "marker": "👀 ", "only_buffer_difference": false, "style": { "text": "green", "selected_text": "green_reverse", "description_text": "yellow" }, "type": { "layout": "columnar", "columns": 1, "col_width": 20, "col_padding": 2 }, "source": "{|buffer, position|\n scope aliases\n | where name == $buffer\n | each {|it| {value: $it.expansion} }\n }" }, { "name": "history_menu_by_session", "marker": "# ", "only_buffer_difference": false, "style": { "text": "green", "selected_text": "green_reverse", "description_text": "yellow" }, "type": { "layout": "list", "page_size": 10 }, "source": "{|buffer, position|\n history -l\n | where session_id == (history session)\n | select command\n | where command =~ $buffer\n | each {|it| {value: $it.command} }\n | reverse\n | uniq\n }" } ], "hooks": { "pre_prompt": [ "{|| null }", "{||\n zoxide add -- $env.PWD\n}" ], "pre_execution": [ "{|| null }" ], "env_change": { "PWD": [ "{|before, after|\n print (lsg)\n # null\n }", "{|before, _|\n if $before == null {\n let file = ($nu.home-path | path join \".local\" \"share\" \"nushell\" \"startup-times.nuon\")\n if not ($file | path exists) {\n mkdir ($file | path dirname)\n touch $file\n }\n let ver = (version)\n open $file | append {\n date: (date now)\n time: $nu.startup-time\n build: ($ver.build_rust_channel)\n allocator: ($ver.allocator)\n version: ($ver.version)\n commit: ($ver.commit_hash)\n build_time: ($ver.build_time)\n bytes_loaded: (view files | get size | math sum)\n } | collect { save --force $file }\n }\n }", { "condition": "{|_, after| not ($after | path join 'toolkit.nu' | path exists) }", "code": "hide toolkit" }, { "condition": "{|_, after| $after | path join 'toolkit.nu' | path exists }", "code": "\n print $'(ansi default_underline)(ansi default_bold)toolkit(ansi reset) module (ansi green_italic)detected(ansi reset)...'\n print $'(ansi yellow_italic)activating(ansi reset) (ansi default_underline)(ansi default_bold)toolkit(ansi reset) module with `(ansi default_dimmed)(ansi default_italic)use toolkit.nu(ansi reset)`'\n use toolkit.nu\n " } ] }, "display_output": "{||\n # if (term size).columns > 100 { table -e } else { table }\n table\n }", "command_not_found": "{||\n null # return an error message when a command is not found\n }" }, "rm": { "always_trash": true }, "shell_integration": { "osc2": true, "osc7": true, "osc8": true, "osc9_9": true, "osc133": true, "osc633": true, "reset_application_mode": true }, "buffer_editor": "nvim", "show_banner": true, "bracketed_paste": true, "render_right_prompt_on_last_line": false, "explore": { "try": { "reactive": true }, "table": { "selected_cell": { "bg": "blue" }, "show_cursor": false } }, "cursor_shape": { "emacs": "underscore", "vi_insert": "block", "vi_normal": "line" }, "datetime_format": { "normal": null, "table": null }, "error_style": "fancy", "display_errors": { "exit_code": true, "termination_signal": true }, "use_kitty_protocol": true, "highlight_resolved_externals": true, "plugins": {}, "plugin_gc": { "default": { "enabled": true, "stop_after": 0 }, "plugins": { "gstat": { "enabled": true, "stop_after": 0 } } } }"##; serde_json::from_str(json_str).expect("Failed to parse example JSON") }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore_config/mod.rs
crates/nu-explore/src/explore_config/mod.rs
//! Explore config TUI - an interactive configuration viewer and editor. //! //! This module provides the `explore config` command which launches a TUI //! for viewing and editing nushell configuration interactively. mod app; mod command; mod conversion; mod example_data; mod input; mod syntax_highlight; mod tree; mod tui; mod types; pub use command::ExploreConfigCommand;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore_config/syntax_highlight.rs
crates/nu-explore/src/explore_config/syntax_highlight.rs
//! Syntax highlighting for nushell code in the explore config TUI. //! //! This module provides syntax highlighting functionality that converts nushell code //! into ANSI-styled text that can be rendered in the TUI. use nu_ansi_term::Style; use nu_color_config::get_shape_color; use nu_parser::{flatten_block, parse}; use nu_protocol::engine::{EngineState, Stack, StateWorkingSet}; use std::sync::Arc; /// Result of syntax highlighting multi-line nushell code pub struct HighlightedContent { /// The ANSI-styled lines pub lines: Vec<String>, } /// Highlight a multi-line string of nushell code and return ANSI-styled lines. /// /// This function parses the entire input as nushell code and applies syntax highlighting /// colors based on the user's configuration. The result is split into lines to match /// the original line structure. /// /// By parsing the entire content at once, multi-line constructs like records, lists, /// and closures are properly recognized and highlighted. pub fn highlight_nushell_content( engine_state: &Arc<EngineState>, stack: &Arc<Stack>, content: &str, ) -> HighlightedContent { if content.is_empty() { return HighlightedContent { lines: vec![String::new()], }; } let config = stack.get_config(engine_state); let mut working_set = StateWorkingSet::new(engine_state); let block = parse(&mut working_set, None, content.as_bytes(), false); let shapes = flatten_block(&working_set, &block); let global_span_offset = engine_state.next_span_start(); let mut result = String::new(); let mut last_seen_span_end = global_span_offset; for (raw_span, flat_shape) in &shapes { // Handle alias spans for external commands let span = if let nu_parser::FlatShape::External(alias_span) = flat_shape { alias_span } else { raw_span }; if span.end <= last_seen_span_end || last_seen_span_end < global_span_offset || span.start < global_span_offset { // We've already output something for this span, skip it continue; } // Add any gap between the last span and this one (e.g., whitespace, newlines) if span.start > last_seen_span_end { let gap = &content [(last_seen_span_end - global_span_offset)..(span.start - global_span_offset)]; result.push_str(gap); } // Get the token text let token = &content[(span.start - global_span_offset)..(span.end - global_span_offset)]; // Get the style for this shape and apply it let style = get_shape_color(flat_shape.as_str(), &config); result.push_str(&style.paint(token).to_string()); last_seen_span_end = span.end; } // Add any remaining text after the last span let remainder = &content[(last_seen_span_end - global_span_offset)..]; if !remainder.is_empty() { result.push_str(&Style::new().paint(remainder).to_string()); } // Split the highlighted result into lines // We need to handle this carefully to preserve ANSI codes across line boundaries let lines: Vec<String> = result.lines().map(|s| s.to_string()).collect(); // Handle the edge case where content ends with a newline // (lines() doesn't include an empty string at the end for trailing newlines) let final_lines = if lines.is_empty() { vec![String::new()] } else { lines }; HighlightedContent { lines: final_lines } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore_config/tui.rs
crates/nu-explore/src/explore_config/tui.rs
//! TUI runtime functions for running the explore config application. use crate::explore_config::input::{ handle_editor_editing_input, handle_editor_normal_input, handle_search_input, handle_tree_input, }; use crate::explore_config::types::{App, AppResult, EditorMode, Focus, NuValueType}; use crossterm::event::{ self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind, KeyModifiers, }; use crossterm::terminal::{ EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode, }; use nu_protocol::engine::{EngineState, Stack}; use ratatui::Terminal; use ratatui::backend::CrosstermBackend; use serde_json::Value; use std::collections::HashMap; use std::error::Error; use std::io; use std::sync::Arc; /// Run the TUI and return the modified JSON data if changes were made in config mode pub fn run_config_tui( json_data: Value, output_file: Option<String>, config_mode: bool, nu_type_map: Option<HashMap<String, NuValueType>>, doc_map: Option<HashMap<String, String>>, engine_state: Arc<EngineState>, stack: Arc<Stack>, ) -> Result<Option<Value>, Box<dyn Error>> { // Terminal initialization enable_raw_mode()?; let mut stdout = io::stdout(); crossterm::execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?; let backend = CrosstermBackend::new(stdout); let mut terminal = Terminal::new(backend)?; // Clear the screen initially terminal.clear()?; let mut app = App::new( json_data, output_file, config_mode, nu_type_map, doc_map, engine_state, stack, ); // Select the first item app.tree_state.select_first(); app.force_update_editor(); let res = run_config_app(&mut terminal, &mut app); // Restore terminal - this is critical for clean exit disable_raw_mode()?; crossterm::execute!( terminal.backend_mut(), LeaveAlternateScreen, DisableMouseCapture )?; terminal.show_cursor()?; if let Err(err) = res { eprintln!("Error: {err:?}"); return Ok(None); } // Return the modified data if in config mode and changes were made if config_mode && app.modified { Ok(Some(app.json_data)) } else { Ok(None) } } fn run_config_app( terminal: &mut Terminal<CrosstermBackend<io::Stdout>>, app: &mut App, ) -> io::Result<()> { loop { terminal.draw(|frame| app.draw(frame))?; if let Event::Key(key) = event::read()? { if key.kind != KeyEventKind::Press { continue; } // Global keybindings (skip Ctrl+S when in editing mode so it applies the edit instead) let in_editing_mode = app.focus == Focus::Editor && app.editor_mode == EditorMode::Editing; match key.code { KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => { return Ok(()); } KeyCode::Char('s') if key.modifiers.contains(KeyModifiers::CONTROL) && !in_editing_mode => { if let Err(e) = app.save_to_file() { app.status_message = format!("✗ Save failed: {}", e); } continue; } _ => {} } // Handle based on focus and mode let result = match (app.focus, app.editor_mode) { (Focus::Search, _) => handle_search_input(app, key.code, key.modifiers), (Focus::Tree, _) => handle_tree_input(app, key.code, key.modifiers), (Focus::Editor, EditorMode::Normal) => { handle_editor_normal_input(app, key.code, key.modifiers) } (Focus::Editor, EditorMode::Editing) => { handle_editor_editing_input(app, key.code, key.modifiers) } }; if let AppResult::Quit = result { return Ok(()); } } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-explore/src/explore_config/input.rs
crates/nu-explore/src/explore_config/input.rs
//! Keyboard input handling for the explore config TUI. use crate::explore_config::types::{ App, AppResult, EditorMode, Focus, ValueType, calculate_cursor_position, }; use crossterm::event::{KeyCode, KeyModifiers}; /// Handle keyboard input when search mode is active pub fn handle_search_input(app: &mut App, key: KeyCode, modifiers: KeyModifiers) -> AppResult { match key { KeyCode::Esc => { // Cancel search and restore full tree app.clear_search(); app.focus = Focus::Tree; app.status_message = get_tree_status_message(app); } KeyCode::Enter => { // Confirm search and return to tree navigation app.search_active = !app.search_query.is_empty(); app.focus = Focus::Tree; app.status_message = get_tree_status_message(app); } KeyCode::Backspace => { app.search_query.pop(); app.apply_search_filter(); } KeyCode::Char(c) if !modifiers.contains(KeyModifiers::CONTROL) => { app.search_query.push(c); app.apply_search_filter(); } _ => {} } AppResult::Continue } /// Handle keyboard input when the tree pane is focused pub fn handle_tree_input(app: &mut App, key: KeyCode, modifiers: KeyModifiers) -> AppResult { match key { // Enter search mode with / or Ctrl+F KeyCode::Char('/') => { app.focus = Focus::Search; // Don't clear existing search query - allow refining app.status_message = String::from("Search: Type to filter tree | Enter to confirm | Esc to cancel"); return AppResult::Continue; } KeyCode::Char('f') if modifiers.contains(KeyModifiers::CONTROL) => { app.focus = Focus::Search; app.status_message = String::from("Search: Type to filter tree | Enter to confirm | Esc to cancel"); return AppResult::Continue; } // Clear search filter with Escape when search is active KeyCode::Esc if app.search_active => { app.clear_search(); app.status_message = get_tree_status_message(app); return AppResult::Continue; } KeyCode::Char('q') => { // In config mode, allow quit if user has confirmed save with Ctrl+S // In non-config mode, allow quit if there are no unsaved changes if app.modified && !app.confirmed_save { app.status_message = String::from("Unsaved changes! Press Ctrl+C to force quit or Ctrl+S to save"); return AppResult::Continue; } else { return AppResult::Quit; } } KeyCode::Up => { app.tree_state.key_up(); app.force_update_editor(); } KeyCode::Down => { app.tree_state.key_down(); app.force_update_editor(); } KeyCode::Left => { app.tree_state.key_left(); app.force_update_editor(); } KeyCode::Right => { app.tree_state.key_right(); app.force_update_editor(); } KeyCode::Char(' ') => { app.tree_state.toggle_selected(); } KeyCode::Enter => { // Check if the selected node is a leaf (non-nested) value let is_leaf = app .get_current_node_info() .map(|info| !matches!(info.value_type, ValueType::Object | ValueType::Array)) .unwrap_or(false); if is_leaf { // Switch to editor pane and enter edit mode app.focus = Focus::Editor; app.editor_mode = EditorMode::Editing; app.editor_cursor = 0; app.status_message = String::from("Editing - Ctrl+S to apply, Esc to cancel"); } else { // Toggle tree expansion for nested values app.tree_state.toggle_selected(); } } KeyCode::Home => { app.tree_state.select_first(); app.force_update_editor(); } KeyCode::End => { app.tree_state.select_last(); app.force_update_editor(); } KeyCode::PageUp => { app.tree_state .select_relative(|current| current.map_or(0, |current| current.saturating_sub(10))); app.force_update_editor(); } KeyCode::PageDown => { app.tree_state .select_relative(|current| current.map_or(0, |current| current.saturating_add(10))); app.force_update_editor(); } KeyCode::Tab => { app.focus = Focus::Editor; app.status_message = String::from("Editor focused - press Enter or 'e' to edit value"); } _ => {} } AppResult::Continue } /// Get the default status message for tree focus pub fn get_tree_status_message(app: &App) -> String { let save_action = if app.config_mode { "Apply" } else { "Save" }; if app.search_active { format!( "Filter: \"{}\" | Esc to clear | / to modify", app.search_query ) } else { format!( "↑↓ Navigate | / Search | ←→ Collapse/Expand | Tab Switch pane | Ctrl+S {} | q Quit", save_action ) } } /// Handle keyboard input when the editor pane is focused in normal mode pub fn handle_editor_normal_input( app: &mut App, key: KeyCode, _modifiers: KeyModifiers, ) -> AppResult { match key { KeyCode::Tab => { app.focus = Focus::Tree; app.status_message = get_tree_status_message(app); } KeyCode::Enter | KeyCode::Char('e') => { app.editor_mode = EditorMode::Editing; app.editor_cursor = 0; app.status_message = String::from("Editing - Ctrl+S to apply, Esc to cancel"); } KeyCode::Up => { app.scroll_editor(-1); } KeyCode::Down => { app.scroll_editor(1); } KeyCode::PageUp => { app.scroll_editor(-10); } KeyCode::PageDown => { app.scroll_editor(10); } KeyCode::Char('q') => { // In config mode, allow quit if user has confirmed save with Ctrl+S // In non-config mode, allow quit if there are no unsaved changes if app.modified && !app.confirmed_save { app.status_message = String::from("Unsaved changes! Press Ctrl+C to force quit or Ctrl+S to save"); } else { return AppResult::Quit; } } _ => {} } AppResult::Continue } /// Handle keyboard input when the editor pane is focused in editing mode pub fn handle_editor_editing_input( app: &mut App, key: KeyCode, modifiers: KeyModifiers, ) -> AppResult { match key { KeyCode::Esc => { app.editor_mode = EditorMode::Normal; app.force_update_editor(); // Restore original value app.status_message = String::from("Edit cancelled"); } // Alt+Enter to apply edit KeyCode::Enter if modifiers.contains(KeyModifiers::ALT) => { app.apply_edit(); app.editor_mode = EditorMode::Normal; } // Ctrl+S to apply edit (most reliable across platforms) KeyCode::Char('s') if modifiers.contains(KeyModifiers::CONTROL) => { app.apply_edit(); app.editor_mode = EditorMode::Normal; } KeyCode::Enter => { // Insert newline app.editor_content.insert(app.editor_cursor, '\n'); app.editor_cursor += 1; } KeyCode::Backspace => { if app.editor_cursor > 0 { app.editor_cursor -= 1; app.editor_content.remove(app.editor_cursor); } } KeyCode::Delete => { if app.editor_cursor < app.editor_content.len() { app.editor_content.remove(app.editor_cursor); } } KeyCode::Left => { app.editor_cursor = app.editor_cursor.saturating_sub(1); } KeyCode::Right => { app.editor_cursor = (app.editor_cursor + 1).min(app.editor_content.len()); } KeyCode::Up if modifiers.contains(KeyModifiers::CONTROL) => { app.scroll_editor(-1); } KeyCode::Down if modifiers.contains(KeyModifiers::CONTROL) => { app.scroll_editor(1); } KeyCode::Up => { // Move cursor up one line let lines: Vec<&str> = app.editor_content.lines().collect(); let cursor_pos = calculate_cursor_position(&app.editor_content, app.editor_cursor); if cursor_pos.line > 0 { let prev_line = lines.get(cursor_pos.line - 1).unwrap_or(&""); let new_col = cursor_pos.col.min(prev_line.len()); let mut new_pos = 0; for (i, line) in lines.iter().enumerate() { if i == cursor_pos.line - 1 { app.editor_cursor = new_pos + new_col; break; } new_pos += line.len() + 1; } } } KeyCode::Down => { // Move cursor down one line let lines: Vec<&str> = app.editor_content.lines().collect(); let cursor_pos = calculate_cursor_position(&app.editor_content, app.editor_cursor); if cursor_pos.line < lines.len().saturating_sub(1) { let next_line = lines.get(cursor_pos.line + 1).unwrap_or(&""); let new_col = cursor_pos.col.min(next_line.len()); let mut new_pos = 0; for (i, line) in lines.iter().enumerate() { if i == cursor_pos.line + 1 { app.editor_cursor = new_pos + new_col; break; } new_pos += line.len() + 1; } } } KeyCode::Home => { // Move to beginning of line // Handle edge cases: empty content or cursor at position 0 if app.editor_content.is_empty() || app.editor_cursor == 0 { app.editor_cursor = 0; } else { let cursor_pos = calculate_cursor_position(&app.editor_content, app.editor_cursor); // Calculate the start position of the current line let mut line_start = 0; for (idx, line) in app.editor_content.lines().enumerate() { if idx == cursor_pos.line { app.editor_cursor = line_start; break; } line_start += line.len() + 1; } } } KeyCode::End => { // Move to end of line // Handle edge case: empty content if app.editor_content.is_empty() { app.editor_cursor = 0; } else { let cursor_pos = calculate_cursor_position(&app.editor_content, app.editor_cursor); let lines: Vec<&str> = app.editor_content.lines().collect(); // Calculate the start position of the current line, then add line length let mut line_start = 0; for (idx, line) in lines.iter().enumerate() { if idx == cursor_pos.line { app.editor_cursor = line_start + line.len(); break; } line_start += line.len() + 1; } // Handle edge case: cursor is past the last line (e.g., after trailing newline) // In this case, cursor_pos.line might be beyond the lines vector if cursor_pos.line >= lines.len() { app.editor_cursor = app.editor_content.len(); } } } KeyCode::Char(c) => { app.editor_content.insert(app.editor_cursor, c); app.editor_cursor += 1; } KeyCode::Tab => { // Insert 2 spaces for indentation app.editor_content.insert_str(app.editor_cursor, " "); app.editor_cursor += 2; } _ => {} } AppResult::Continue }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-std/src/lib.rs
crates/nu-std/src/lib.rs
#![doc = include_str!("../README.md")] use log::trace; use nu_parser::parse; use nu_protocol::{ VirtualPathId, engine::{FileStack, StateWorkingSet, VirtualPath}, report_parse_error, }; use std::path::PathBuf; fn create_virt_file(working_set: &mut StateWorkingSet, name: &str, content: &str) -> VirtualPathId { let sanitized_name = PathBuf::from(name).to_string_lossy().to_string(); let file_id = working_set.add_file(sanitized_name.clone(), content.as_bytes()); working_set.add_virtual_path(sanitized_name, VirtualPath::File(file_id)) } pub fn load_standard_library( engine_state: &mut nu_protocol::engine::EngineState, ) -> Result<(), miette::ErrReport> { trace!("load_standard_library"); let mut working_set = StateWorkingSet::new(engine_state); // Contents of the std virtual directory let mut std_virt_paths = vec![]; // std/mod.nu let std_mod_virt_file_id = create_virt_file( &mut working_set, "std/mod.nu", include_str!("../std/mod.nu"), ); std_virt_paths.push(std_mod_virt_file_id); // Submodules/subdirectories ... std/<module>/mod.nu let mut std_submodules = vec![ // Loaded at startup - Not technically part of std ( "mod.nu", "std/prelude", include_str!("../std/prelude/mod.nu"), ), // std submodules ("mod.nu", "std/assert", include_str!("../std/assert/mod.nu")), ("mod.nu", "std/bench", include_str!("../std/bench/mod.nu")), ("mod.nu", "std/dirs", include_str!("../std/dirs/mod.nu")), ("mod.nu", "std/dt", include_str!("../std/dt/mod.nu")), ( "mod.nu", "std/formats", include_str!("../std/formats/mod.nu"), ), ("mod.nu", "std/help", include_str!("../std/help/mod.nu")), ("mod.nu", "std/input", include_str!("../std/input/mod.nu")), ("mod.nu", "std/iter", include_str!("../std/iter/mod.nu")), ("mod.nu", "std/log", include_str!("../std/log/mod.nu")), ("mod.nu", "std/math", include_str!("../std/math/mod.nu")), ("mod.nu", "std/util", include_str!("../std/util/mod.nu")), ("mod.nu", "std/xml", include_str!("../std/xml/mod.nu")), ("mod.nu", "std/config", include_str!("../std/config/mod.nu")), ( "mod.nu", "std/testing", include_str!("../std/testing/mod.nu"), ), ("mod.nu", "std/clip", include_str!("../std/clip/mod.nu")), ("mod.nu", "std/random", include_str!("../std/random/mod.nu")), ]; for (filename, std_subdir_name, content) in std_submodules.drain(..) { let mod_dir = PathBuf::from(std_subdir_name); let name = mod_dir.join(filename); let virt_file_id = create_virt_file(&mut working_set, &name.to_string_lossy(), content); // Place file in virtual subdir let mod_dir_filelist = vec![virt_file_id]; let virt_dir_id = working_set.add_virtual_path( mod_dir.to_string_lossy().to_string(), VirtualPath::Dir(mod_dir_filelist), ); // Add the subdir to the list of paths in std std_virt_paths.push(virt_dir_id); } // Create std virtual dir with all subdirs and files let std_dir = PathBuf::from("std").to_string_lossy().to_string(); let _ = working_set.add_virtual_path(std_dir, VirtualPath::Dir(std_virt_paths)); // Add std-rfc files let mut std_rfc_virt_paths = vec![]; // std-rfc/mod.nu let std_rfc_mod_virt_file_id = create_virt_file( &mut working_set, "std-rfc/mod.nu", include_str!("../std-rfc/mod.nu"), ); std_rfc_virt_paths.push(std_rfc_mod_virt_file_id); // Submodules/subdirectories ... std-rfc/<module>/mod.nu let mut std_rfc_submodules = vec![ ( "mod.nu", "std-rfc/clip", include_str!("../std-rfc/clip/mod.nu"), ), ( "mod.nu", "std-rfc/conversions", include_str!("../std-rfc/conversions/mod.nu"), ), #[cfg(feature = "sqlite")] ("mod.nu", "std-rfc/kv", include_str!("../std-rfc/kv/mod.nu")), ( "mod.nu", "std-rfc/path", include_str!("../std-rfc/path/mod.nu"), ), ( "mod.nu", "std-rfc/str", include_str!("../std-rfc/str/mod.nu"), ), ( "mod.nu", "std-rfc/tables", include_str!("../std-rfc/tables/mod.nu"), ), ( "mod.nu", "std-rfc/iter", include_str!("../std-rfc/iter/mod.nu"), ), ( "mod.nu", "std-rfc/random", include_str!("../std-rfc/random/mod.nu"), ), ]; for (filename, std_rfc_subdir_name, content) in std_rfc_submodules.drain(..) { let mod_dir = PathBuf::from(std_rfc_subdir_name); let name = mod_dir.join(filename); let virt_file_id = create_virt_file(&mut working_set, &name.to_string_lossy(), content); // Place file in virtual subdir let mod_dir_filelist = vec![virt_file_id]; let virt_dir_id = working_set.add_virtual_path( mod_dir.to_string_lossy().to_string(), VirtualPath::Dir(mod_dir_filelist), ); // Add the subdir to the list of paths in std std_rfc_virt_paths.push(virt_dir_id); } // Create std virtual dir with all subdirs and files let std_rfc_dir = PathBuf::from("std-rfc").to_string_lossy().to_string(); let _ = working_set.add_virtual_path(std_rfc_dir, VirtualPath::Dir(std_rfc_virt_paths)); // Load prelude let (_, delta) = { let source = r#" # Prelude use std/prelude * "#; // Add a placeholder file to the stack of files being evaluated. // The name of this file doesn't matter; it's only there to set the current working directory to NU_STDLIB_VIRTUAL_DIR. let placeholder = PathBuf::from("load std/prelude"); working_set.files = FileStack::with_file(placeholder); let block = parse( &mut working_set, Some("loading stdlib prelude"), source.as_bytes(), false, ); // Remove the placeholder file from the stack of files being evaluated. working_set.files.pop(); if let Some(err) = working_set.parse_errors.first() { report_parse_error(None, &working_set, err); } (block, working_set.render()) }; engine_state.merge_delta(delta)?; Ok(()) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_gstat/src/lib.rs
crates/nu_plugin_gstat/src/lib.rs
mod gstat; mod nu; pub use gstat::GStat; pub use nu::GStatPlugin;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_gstat/src/main.rs
crates/nu_plugin_gstat/src/main.rs
use nu_plugin::{MsgPackSerializer, serve_plugin}; use nu_plugin_gstat::GStatPlugin; fn main() { serve_plugin(&GStatPlugin, MsgPackSerializer {}) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_gstat/src/gstat.rs
crates/nu_plugin_gstat/src/gstat.rs
use git2::{Branch, BranchType, DescribeOptions, Repository}; use nu_protocol::{IntoSpanned, LabeledError, Span, Spanned, Value, record}; use std::{fmt::Write, ops::BitAnd, path::Path}; // git status // https://github.com/git/git/blob/9875c515535860450bafd1a177f64f0a478900fa/Documentation/git-status.txt // git status borrowed from here and tweaked // https://github.com/glfmn/glitter/blob/master/lib/git.rs #[derive(Default)] pub struct GStat; impl GStat { pub fn new() -> Self { Default::default() } pub fn gstat( &self, value: &Value, current_dir: &str, path: Option<Spanned<String>>, calculate_tag: bool, span: Span, ) -> Result<Value, LabeledError> { // use std::any::Any; // eprintln!("input type: {:?} value: {:#?}", &value.type_id(), &value); // eprintln!("path type: {:?} value: {:#?}", &path.type_id(), &path); // If the path isn't set, get it from input, and failing that, set to "." let path = match path { Some(path) => path, None => { if !value.is_nothing() { value.coerce_string()?.into_spanned(value.span()) } else { String::from(".").into_spanned(span) } } }; // Make the path absolute based on the current_dir let absolute_path = Path::new(current_dir).join(&path.item); // This path has to exist if !absolute_path.exists() { return Err(LabeledError::new("error with path").with_label( format!("path does not exist [{}]", absolute_path.display()), path.span, )); } let metadata = std::fs::metadata(&absolute_path).map_err(|e| { LabeledError::new("error with metadata").with_label( format!( "unable to get metadata for [{}], error: {}", absolute_path.display(), e ), path.span, ) })?; // This path has to be a directory if !metadata.is_dir() { return Err(LabeledError::new("error with directory").with_label( format!("path is not a directory [{}]", absolute_path.display()), path.span, )); } let repo_path = match absolute_path.canonicalize() { Ok(p) => p, Err(e) => { return Err(LabeledError::new(format!( "error canonicalizing [{}]", absolute_path.display() )) .with_label(e.to_string(), path.span)); } }; let (stats, repo) = if let Ok(mut repo) = Repository::discover(repo_path) { (Stats::new(&mut repo), repo) } else { return Ok(self.create_empty_git_status(span)); }; let repo_name = repo .path() .parent() .and_then(|p| p.file_name()) .map(|p| p.to_string_lossy().to_string()) .unwrap_or_else(|| "".to_string()); let tag = calculate_tag .then(|| { let mut desc_opts = DescribeOptions::new(); desc_opts.describe_tags(); repo.describe(&desc_opts).ok()?.format(None).ok() }) .flatten() .unwrap_or_else(|| "no_tag".to_string()); // Leave this in case we want to turn it into a table instead of a list // Ok(Value::List { // vals: vec![Value::Record { // cols, // vals, // span: *span, // }], // span: *span, // }) Ok(Value::record( record! { "idx_added_staged" => Value::int(stats.idx_added_staged as i64, span), "idx_modified_staged" => Value::int(stats.idx_modified_staged as i64, span), "idx_deleted_staged" => Value::int(stats.idx_deleted_staged as i64, span), "idx_renamed" => Value::int(stats.idx_renamed as i64, span), "idx_type_changed" => Value::int(stats.idx_type_changed as i64, span), "wt_untracked" => Value::int(stats.wt_untracked as i64, span), "wt_modified" => Value::int(stats.wt_modified as i64, span), "wt_deleted" => Value::int(stats.wt_deleted as i64, span), "wt_type_changed" => Value::int(stats.wt_type_changed as i64, span), "wt_renamed" => Value::int(stats.wt_renamed as i64, span), "ignored" => Value::int(stats.ignored as i64, span), "conflicts" => Value::int(stats.conflicts as i64, span), "ahead" => Value::int(stats.ahead as i64, span), "behind" => Value::int(stats.behind as i64, span), "stashes" => Value::int(stats.stashes as i64, span), "repo_name" => Value::string(repo_name, span), "tag" => Value::string(tag, span), "branch" => Value::string(stats.branch, span), "remote" => Value::string(stats.remote, span), "state" => Value::string(stats.state, span), }, span, )) } fn create_empty_git_status(&self, span: Span) -> Value { Value::record( record! { "idx_added_staged" => Value::int(-1, span), "idx_modified_staged" => Value::int(-1, span), "idx_deleted_staged" => Value::int(-1, span), "idx_renamed" => Value::int(-1, span), "idx_type_changed" => Value::int(-1, span), "wt_untracked" => Value::int(-1, span), "wt_modified" => Value::int(-1, span), "wt_deleted" => Value::int(-1, span), "wt_type_changed" => Value::int(-1, span), "wt_renamed" => Value::int(-1, span), "ignored" => Value::int(-1, span), "conflicts" => Value::int(-1, span), "ahead" => Value::int(-1, span), "behind" => Value::int(-1, span), "stashes" => Value::int(-1, span), "repo_name" => Value::string("no_repository", span), "tag" => Value::string("no_tag", span), "branch" => Value::string("no_branch", span), "remote" => Value::string("no_remote", span), "state" => Value::string("no_state", span), }, span, ) } } /// Stats which the interpreter uses to populate the gist expression #[derive(Debug, PartialEq, Eq, Default, Clone)] pub struct Stats { /// Number of files to be added pub idx_added_staged: u16, /// Number of staged changes to files pub idx_modified_staged: u16, /// Number of staged deletions pub idx_deleted_staged: u16, /// Number of renamed files pub idx_renamed: u16, /// Index file type change pub idx_type_changed: u16, /// Number of untracked files which are new to the repository pub wt_untracked: u16, /// Number of modified files which have not yet been staged pub wt_modified: u16, /// Number of deleted files pub wt_deleted: u16, /// Working tree file type change pub wt_type_changed: u16, /// Working tree renamed pub wt_renamed: u16, // Ignored files pub ignored: u16, /// Number of unresolved conflicts in the repository pub conflicts: u16, /// Number of commits ahead of the upstream branch pub ahead: u16, /// Number of commits behind the upstream branch pub behind: u16, /// Number of stashes on the current branch pub stashes: u16, /// The branch name or other stats of the HEAD pointer pub branch: String, /// The of the upstream branch pub remote: String, /// State of the repository (Clean, Merge, Rebase, etc.) /// See all states at https://docs.rs/git2/latest/git2/enum.RepositoryState.html pub state: String, } impl Stats { /// Populate stats with the status of the given repository pub fn new(repo: &mut Repository) -> Stats { let mut st: Stats = Default::default(); st.read_branch(repo); st.state = format!("{:?}", repo.state()).to_lowercase(); let mut opts = git2::StatusOptions::new(); opts.include_untracked(true) .recurse_untracked_dirs(true) .renames_head_to_index(true); if let Ok(statuses) = repo.statuses(Some(&mut opts)) { for status in statuses.iter() { let flags = status.status(); if check(flags, git2::Status::INDEX_NEW) { st.idx_added_staged += 1; } if check(flags, git2::Status::INDEX_MODIFIED) { st.idx_modified_staged += 1; } if check(flags, git2::Status::INDEX_DELETED) { st.idx_deleted_staged += 1; } if check(flags, git2::Status::INDEX_RENAMED) { st.idx_renamed += 1; } if check(flags, git2::Status::INDEX_TYPECHANGE) { st.idx_type_changed += 1; } if check(flags, git2::Status::WT_NEW) { st.wt_untracked += 1; } if check(flags, git2::Status::WT_MODIFIED) { st.wt_modified += 1; } if check(flags, git2::Status::WT_DELETED) { st.wt_deleted += 1; } if check(flags, git2::Status::WT_TYPECHANGE) { st.wt_type_changed += 1; } if check(flags, git2::Status::WT_RENAMED) { st.wt_renamed += 1; } if check(flags, git2::Status::IGNORED) { st.ignored += 1; } if check(flags, git2::Status::CONFLICTED) { st.conflicts += 1; } } } let _ = repo.stash_foreach(|_, &_, &_| { st.stashes += 1; true }); st } /// Read the branch-name of the repository /// /// If in detached head, grab the first few characters of the commit ID if possible, otherwise /// simply provide HEAD as the branch name. This is to mimic the behaviour of `git status`. fn read_branch(&mut self, repo: &Repository) { self.branch = match repo.head() { Ok(head) => { if let Some(name) = head.shorthand() { // try to use first 8 characters or so of the ID in detached HEAD if name == "HEAD" { if let Ok(commit) = head.peel_to_commit() { let mut id = String::new(); for byte in &commit.id().as_bytes()[..4] { write!(&mut id, "{byte:02x}").ok(); } id } else { "HEAD".to_string() } // Grab the branch from the reference } else { let branch = name.to_string(); // Since we have a branch name, look for the name of the upstream branch self.read_upstream_name(repo, &branch); branch } } else { "HEAD".to_string() } } Err(ref err) if err.code() == git2::ErrorCode::BareRepo => "master".to_string(), Err(_) if repo.is_empty().unwrap_or(false) => "master".to_string(), Err(_) => "HEAD".to_string(), }; } /// Read name of the upstream branch fn read_upstream_name(&mut self, repo: &Repository, branch: &str) { // First grab branch from the name self.remote = if let Ok(branch) = repo.find_branch(branch, BranchType::Local) { // Grab the upstream from the branch if let Ok(upstream) = branch.upstream() { // While we have the upstream branch, traverse the graph and count // ahead-behind commits. self.read_ahead_behind(repo, &branch, &upstream); if let Ok(Some(name)) = upstream.name() { name.to_string() } else { String::new() } } else { String::new() } } else { String::new() }; } /// Read ahead-behind information between the local and upstream branches fn read_ahead_behind(&mut self, repo: &Repository, local: &Branch, upstream: &Branch) { if let (Some(local), Some(upstream)) = (local.get().target(), upstream.get().target()) && let Ok((ahead, behind)) = repo.graph_ahead_behind(local, upstream) { self.ahead = ahead as u16; self.behind = behind as u16; } } } // impl AddAssign for Stats { // fn add_assign(&mut self, rhs: Self) { // self.untracked += rhs.untracked; // self.added_staged += rhs.added_staged; // self.modified += rhs.modified; // self.modified_staged += rhs.modified_staged; // self.renamed += rhs.renamed; // self.deleted += rhs.deleted; // self.deleted_staged += rhs.deleted_staged; // self.ahead += rhs.ahead; // self.behind += rhs.behind; // self.conflicts += rhs.conflicts; // self.stashes += rhs.stashes; // } // } /// Check the bits of a flag against the value to see if they are set #[inline] fn check<B>(val: B, flag: B) -> bool where B: BitAnd<Output = B> + PartialEq + Copy, { val & flag == flag }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_gstat/src/nu/mod.rs
crates/nu_plugin_gstat/src/nu/mod.rs
use crate::GStat; use nu_plugin::{EngineInterface, EvaluatedCall, Plugin, PluginCommand, SimplePluginCommand}; use nu_protocol::{Category, LabeledError, Signature, Spanned, SyntaxShape, Value}; pub struct GStatPlugin; impl Plugin for GStatPlugin { fn version(&self) -> String { env!("CARGO_PKG_VERSION").into() } fn commands(&self) -> Vec<Box<dyn PluginCommand<Plugin = Self>>> { vec![Box::new(GStat)] } } impl SimplePluginCommand for GStat { type Plugin = GStatPlugin; fn name(&self) -> &str { "gstat" } fn description(&self) -> &str { "Get the git status of a repo" } fn signature(&self) -> Signature { Signature::build(PluginCommand::name(self)) .switch("no-tag", "Disable git tag resolving", None) .optional("path", SyntaxShape::Filepath, "path to repo") .category(Category::Custom("prompt".to_string())) } fn run( &self, _plugin: &GStatPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: &Value, ) -> Result<Value, LabeledError> { let repo_path: Option<Spanned<String>> = call.opt(0)?; // eprintln!("input value: {:#?}", &input); let current_dir = engine.get_current_dir()?; let disable_tag = call.has_flag("no-tag")?; self.gstat(input, &current_dir, repo_path, !disable_tag, call.head) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-base/src/lib.rs
crates/nu-cmd-base/src/lib.rs
#![doc = include_str!("../README.md")] pub mod formats; pub mod hook; pub mod input_handler; pub mod util; mod wrap_call; pub use wrap_call::*;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-base/src/input_handler.rs
crates/nu-cmd-base/src/input_handler.rs
use nu_protocol::{PipelineData, ShellError, Signals, Span, Value, ast::CellPath}; use std::sync::Arc; pub trait CmdArgument { fn take_cell_paths(&mut self) -> Option<Vec<CellPath>>; } /// Arguments with only cell_path. /// /// If commands is going to use `operate` function, and it only required optional cell_paths /// Using this to simplify code. pub struct CellPathOnlyArgs { cell_paths: Option<Vec<CellPath>>, } impl CmdArgument for CellPathOnlyArgs { fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> { self.cell_paths.take() } } impl From<Vec<CellPath>> for CellPathOnlyArgs { fn from(cell_paths: Vec<CellPath>) -> Self { Self { cell_paths: (!cell_paths.is_empty()).then_some(cell_paths), } } } /// A simple wrapper for `PipelineData::map` method. /// /// In detail, for each elements, invoking relative `cmd` with `arg`. /// /// If `arg` tell us that its cell path is not None, only map over data under these columns. /// Else it will apply each column inside a table. /// /// The validation of input element should be handle by `cmd` itself. pub fn operate<C, A>( cmd: C, mut arg: A, input: PipelineData, span: Span, signals: &Signals, ) -> Result<PipelineData, ShellError> where A: CmdArgument + Send + Sync + 'static, C: Fn(&Value, &A, Span) -> Value + Send + Sync + 'static + Clone + Copy, { match arg.take_cell_paths() { None => input.map( move |v| { match v { // Propagate errors inside the input Value::Error { .. } => v, _ => cmd(&v, &arg, span), } }, signals, ), Some(column_paths) => { let arg = Arc::new(arg); input.map( move |mut v| { for path in &column_paths { let opt = arg.clone(); let r = v.update_cell_path( &path.members, Box::new(move |old| { match old { // Propagate errors inside the input Value::Error { .. } => old.clone(), _ => cmd(old, &opt, span), } }), ); if let Err(error) = r { return Value::error(error, span); } } v }, signals, ) } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-base/src/hook.rs
crates/nu-cmd-base/src/hook.rs
use miette::Result; use nu_engine::{eval_block, eval_block_with_early_return, redirect_env}; use nu_parser::parse; use nu_protocol::{ PipelineData, PositionalArg, ShellError, Span, Type, Value, VarId, debugger::WithoutDebug, engine::{Closure, EngineState, Stack, StateWorkingSet}, report_error::{report_parse_error, report_shell_error}, }; use std::{collections::HashMap, sync::Arc}; pub fn eval_env_change_hook( env_change_hook: &HashMap<String, Vec<Value>>, engine_state: &mut EngineState, stack: &mut Stack, ) -> Result<(), ShellError> { for (env, hooks) in env_change_hook { let before = engine_state.previous_env_vars.get(env); let after = stack.get_env_var(engine_state, env); if before != after { let before = before.cloned().unwrap_or_default(); let after = after.cloned().unwrap_or_default(); eval_hooks( engine_state, stack, vec![("$before".into(), before), ("$after".into(), after.clone())], hooks, "env_change", )?; Arc::make_mut(&mut engine_state.previous_env_vars).insert(env.clone(), after); } } Ok(()) } pub fn eval_hooks( engine_state: &mut EngineState, stack: &mut Stack, arguments: Vec<(String, Value)>, hooks: &[Value], hook_name: &str, ) -> Result<(), ShellError> { for hook in hooks { eval_hook( engine_state, stack, None, arguments.clone(), hook, &format!("{hook_name} list, recursive"), )?; } Ok(()) } pub fn eval_hook( engine_state: &mut EngineState, stack: &mut Stack, input: Option<PipelineData>, arguments: Vec<(String, Value)>, value: &Value, hook_name: &str, ) -> Result<PipelineData, ShellError> { let mut output = PipelineData::empty(); let span = value.span(); match value { Value::String { val, .. } => { let (block, delta, vars) = { let mut working_set = StateWorkingSet::new(engine_state); let mut vars: Vec<(VarId, Value)> = vec![]; for (name, val) in arguments { let var_id = working_set.add_variable( name.as_bytes().to_vec(), val.span(), Type::Any, false, ); vars.push((var_id, val)); } let output = parse( &mut working_set, Some(&format!("{hook_name} hook")), val.as_bytes(), false, ); if let Some(err) = working_set.parse_errors.first() { report_parse_error(Some(stack), &working_set, err); return Err(ShellError::GenericError { error: format!("Failed to run {hook_name} hook"), msg: "source code has errors".into(), span: Some(span), help: None, inner: Vec::new(), }); } (output, working_set.render(), vars) }; engine_state.merge_delta(delta)?; let input = if let Some(input) = input { input } else { PipelineData::empty() }; let var_ids: Vec<VarId> = vars .into_iter() .map(|(var_id, val)| { stack.add_var(var_id, val); var_id }) .collect(); match eval_block::<WithoutDebug>(engine_state, stack, &block, input).map(|p| p.body) { Ok(pipeline_data) => { output = pipeline_data; } Err(err) => { report_shell_error(Some(stack), engine_state, &err); } } for var_id in var_ids.iter() { stack.remove_var(*var_id); } } Value::List { vals, .. } => { eval_hooks(engine_state, stack, arguments, vals, hook_name)?; } Value::Record { val, .. } => { // Hooks can optionally be a record in this form: // { // condition: {|before, after| ... } # block that evaluates to true/false // code: # block or a string // } // The condition block will be run to check whether the main hook (in `code`) should be run. // If it returns true (the default if a condition block is not specified), the hook should be run. let do_run_hook = if let Some(condition) = val.get("condition") { let other_span = condition.span(); if let Ok(closure) = condition.as_closure() { match run_hook( engine_state, stack, closure, None, arguments.clone(), other_span, ) { Ok(pipeline_data) => { if let PipelineData::Value(Value::Bool { val, .. }, ..) = pipeline_data { val } else { return Err(ShellError::RuntimeTypeMismatch { expected: Type::Bool, actual: pipeline_data.get_type(), span: pipeline_data.span().unwrap_or(other_span), }); } } Err(err) => { return Err(err); } } } else { return Err(ShellError::RuntimeTypeMismatch { expected: Type::Closure, actual: condition.get_type(), span: other_span, }); } } else { // always run the hook true }; if do_run_hook { let Some(follow) = val.get("code") else { return Err(ShellError::CantFindColumn { col_name: "code".into(), span: Some(span), src_span: span, }); }; let source_span = follow.span(); match follow { Value::String { val, .. } => { let (block, delta, vars) = { let mut working_set = StateWorkingSet::new(engine_state); let mut vars: Vec<(VarId, Value)> = vec![]; for (name, val) in arguments { let var_id = working_set.add_variable( name.as_bytes().to_vec(), val.span(), Type::Any, false, ); vars.push((var_id, val)); } let output = parse( &mut working_set, Some(&format!("{hook_name} hook")), val.as_bytes(), false, ); if let Some(err) = working_set.parse_errors.first() { report_parse_error(Some(stack), &working_set, err); return Err(ShellError::GenericError { error: format!("Failed to run {hook_name} hook"), msg: "source code has errors".into(), span: Some(span), help: None, inner: Vec::new(), }); } (output, working_set.render(), vars) }; engine_state.merge_delta(delta)?; let input = PipelineData::empty(); let var_ids: Vec<VarId> = vars .into_iter() .map(|(var_id, val)| { stack.add_var(var_id, val); var_id }) .collect(); match eval_block::<WithoutDebug>(engine_state, stack, &block, input) .map(|p| p.body) { Ok(pipeline_data) => { output = pipeline_data; } Err(err) => { report_shell_error(Some(stack), engine_state, &err); } } for var_id in var_ids.iter() { stack.remove_var(*var_id); } } Value::Closure { val, .. } => { run_hook(engine_state, stack, val, input, arguments, source_span)?; } other => { return Err(ShellError::RuntimeTypeMismatch { expected: Type::custom("string or closure"), actual: other.get_type(), span: source_span, }); } } } } Value::Closure { val, .. } => { output = run_hook(engine_state, stack, val, input, arguments, span)?; } other => { return Err(ShellError::RuntimeTypeMismatch { expected: Type::custom("string, closure, record, or list"), actual: other.get_type(), span: other.span(), }); } } engine_state.merge_env(stack)?; Ok(output) } fn run_hook( engine_state: &EngineState, stack: &mut Stack, closure: &Closure, optional_input: Option<PipelineData>, arguments: Vec<(String, Value)>, span: Span, ) -> Result<PipelineData, ShellError> { let block = engine_state.get_block(closure.block_id); let input = optional_input.unwrap_or_else(PipelineData::empty); let mut callee_stack = stack .captures_to_stack_preserve_out_dest(closure.captures.clone()) .reset_pipes(); for (idx, PositionalArg { var_id, .. }) in block.signature.required_positional.iter().enumerate() { if let Some(var_id) = var_id { if let Some(arg) = arguments.get(idx) { callee_stack.add_var(*var_id, arg.1.clone()) } else { return Err(ShellError::IncompatibleParametersSingle { msg: "This hook block has too many parameters".into(), span, }); } } } let pipeline_data = eval_block_with_early_return::<WithoutDebug>( engine_state, &mut callee_stack, block, input, )? .body; if let PipelineData::Value(Value::Error { error, .. }, _) = pipeline_data { return Err(*error); } // If all went fine, preserve the environment of the called block redirect_env(engine_state, stack, &callee_stack); Ok(pipeline_data) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-base/src/util.rs
crates/nu-cmd-base/src/util.rs
use nu_protocol::{ Range, ShellError, Span, Value, engine::{EngineState, Stack}, }; use std::ops::Bound; type MakeRangeError = fn(&str, Span) -> ShellError; /// Returns a inclusive pair of boundary in given `range`. pub fn process_range(range: &Range) -> Result<(isize, isize), MakeRangeError> { match range { Range::IntRange(range) => { let start = range.start().try_into().unwrap_or(0); let end = match range.end() { Bound::Included(v) => v as isize, Bound::Excluded(v) => (v - 1) as isize, Bound::Unbounded => isize::MAX, }; Ok((start, end)) } Range::FloatRange(_) => Err(|msg, span| ShellError::TypeMismatch { err_message: msg.to_string(), span, }), } } const HELP_MSG: &str = "Nushell's config file can be found with the command: $nu.config-path. \ For more help: (https://nushell.sh/book/configuration.html#configurations-with-built-in-commands)"; fn get_editor_commandline( value: &Value, var_name: &str, ) -> Result<(String, Vec<String>), ShellError> { match value { Value::String { val, .. } if !val.is_empty() => Ok((val.to_string(), Vec::new())), Value::List { vals, .. } if !vals.is_empty() => { let mut editor_cmd = vals.iter().map(|l| l.coerce_string()); match editor_cmd.next().transpose()? { Some(editor) if !editor.is_empty() => { let params = editor_cmd.collect::<Result<_, ShellError>>()?; Ok((editor, params)) } _ => Err(ShellError::GenericError { error: "Editor executable is missing".into(), msg: "Set the first element to an executable".into(), span: Some(value.span()), help: Some(HELP_MSG.into()), inner: vec![], }), } } Value::String { .. } | Value::List { .. } => Err(ShellError::GenericError { error: format!("{var_name} should be a non-empty string or list<String>"), msg: "Specify an executable here".into(), span: Some(value.span()), help: Some(HELP_MSG.into()), inner: vec![], }), x => Err(ShellError::CantConvert { to_type: "string or list<string>".into(), from_type: x.get_type().to_string(), span: value.span(), help: None, }), } } pub fn get_editor( engine_state: &EngineState, stack: &Stack, span: Span, ) -> Result<(String, Vec<String>), ShellError> { let config = stack.get_config(engine_state); let env_vars = stack.get_env_vars(engine_state); if let Ok(buff_editor) = get_editor_commandline(&config.buffer_editor, "$env.config.buffer_editor") { Ok(buff_editor) } else if let Some(value) = env_vars.get("VISUAL") { get_editor_commandline(value, "$env.VISUAL") } else if let Some(value) = env_vars.get("EDITOR") { get_editor_commandline(value, "$env.EDITOR") } else { Err(ShellError::GenericError { error: "No editor configured".into(), msg: "Please specify one via `$env.config.buffer_editor` or `$env.EDITOR`/`$env.VISUAL`" .into(), span: Some(span), help: Some(HELP_MSG.into()), inner: vec![], }) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false