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-test-support/src/playground/nu_process.rs
crates/nu-test-support/src/playground/nu_process.rs
use super::EnvironmentVariable; use crate::fs::{binaries as test_bins_path, executable_path}; use std::{ ffi::{OsStr, OsString}, fmt, process::{Command, ExitStatus}, }; pub trait Executable { fn execute(&mut self) -> Result<Outcome, NuError>; } #[derive(Clone, Debug)] pub struct Outcome { pub out: Vec<u8>, pub err: Vec<u8>, } impl Outcome { pub fn new(out: &[u8], err: &[u8]) -> Outcome { Outcome { out: out.to_vec(), err: err.to_vec(), } } } #[derive(Debug)] pub struct NuError { pub desc: String, pub exit: Option<ExitStatus>, pub output: Option<Outcome>, } #[derive(Clone, Debug, Default)] pub struct NuProcess { pub arguments: Vec<OsString>, pub environment_vars: Vec<EnvironmentVariable>, pub cwd: Option<OsString>, } impl fmt::Display for NuProcess { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "`nu")?; for arg in &self.arguments { write!(f, " {}", arg.to_string_lossy())?; } write!(f, "`") } } impl NuProcess { pub fn arg<T: AsRef<OsStr>>(&mut self, arg: T) -> &mut Self { self.arguments.push(arg.as_ref().to_os_string()); self } pub fn args<T: AsRef<OsStr>>(&mut self, arguments: &[T]) -> &mut NuProcess { self.arguments .extend(arguments.iter().map(|t| t.as_ref().to_os_string())); self } pub fn cwd<T: AsRef<OsStr>>(&mut self, path: T) -> &mut NuProcess { self.cwd = Some(path.as_ref().to_os_string()); self } pub fn construct(&self) -> Command { let mut command = Command::new(executable_path()); if let Some(cwd) = &self.cwd { command.current_dir(cwd); } command.env_clear(); let paths = [test_bins_path()]; let paths_joined = match std::env::join_paths(paths) { Ok(all) => all, Err(_) => panic!("Couldn't join paths for PATH var."), }; command.env(crate::NATIVE_PATH_ENV_VAR, paths_joined); for env_var in &self.environment_vars { command.env(&env_var.name, &env_var.value); } for arg in &self.arguments { command.arg(arg); } command } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-test-support/tests/get_system_locale.rs
crates/nu-test-support/tests/get_system_locale.rs
#![cfg(debug_assertions)] use nu_test_support::locale_override::with_locale_override; use nu_utils::get_system_locale; use num_format::Grouping; #[test] fn test_get_system_locale_en() { let locale = with_locale_override("en_US.UTF-8", get_system_locale); assert_eq!(locale.name(), "en"); assert_eq!(locale.grouping(), Grouping::Standard) } #[test] fn test_get_system_locale_de() { let locale = with_locale_override("de_DE.UTF-8", get_system_locale); assert_eq!(locale.name(), "de"); assert_eq!(locale.grouping(), Grouping::Standard) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-derive-value/src/from.rs
crates/nu-derive-value/src/from.rs
use proc_macro2::TokenStream as TokenStream2; use quote::{ToTokens, quote}; use syn::{ Attribute, Data, DataEnum, DataStruct, DeriveInput, Fields, Generics, Ident, Type, spanned::Spanned, }; use crate::{ attributes::{self, ContainerAttributes, MemberAttributes, ParseAttrs}, case::Case, names::NameResolver, }; #[derive(Debug)] pub struct FromValue; type DeriveError = super::error::DeriveError<FromValue>; type Result<T = TokenStream2> = std::result::Result<T, DeriveError>; /// Inner implementation of the `#[derive(FromValue)]` macro for structs and enums. /// /// Uses `proc_macro2::TokenStream` for better testing support, unlike `proc_macro::TokenStream`. /// /// This function directs the `FromValue` trait derivation to the correct implementation based on /// the input type: /// - For structs: [`derive_struct_from_value`] /// - For enums: [`derive_enum_from_value`] /// - Unions are not supported and will return an error. pub fn derive_from_value(input: TokenStream2) -> Result { let input: DeriveInput = syn::parse2(input).map_err(DeriveError::Syn)?; match input.data { Data::Struct(data_struct) => Ok(derive_struct_from_value( input.ident, data_struct, input.generics, input.attrs, )?), Data::Enum(data_enum) => Ok(derive_enum_from_value( input.ident, data_enum, input.generics, input.attrs, )?), Data::Union(_) => Err(DeriveError::UnsupportedUnions), } } /// Implements the `#[derive(FromValue)]` macro for structs. /// /// This function provides the impl signature for `FromValue`. /// The implementation for `FromValue::from_value` is handled by [`struct_from_value`] and the /// `FromValue::expected_type` is handled by [`struct_expected_type`]. fn derive_struct_from_value( ident: Ident, data: DataStruct, generics: Generics, attrs: Vec<Attribute>, ) -> Result { let container_attrs = ContainerAttributes::parse_attrs(attrs.iter())?; let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); let from_value_impl = struct_from_value(&data, &container_attrs)?; let expected_type_impl = struct_expected_type( &data.fields, container_attrs.type_name.as_deref(), &container_attrs, )?; Ok(quote! { #[automatically_derived] impl #impl_generics nu_protocol::FromValue for #ident #ty_generics #where_clause { #from_value_impl #expected_type_impl } }) } /// Implements `FromValue::from_value` for structs. /// /// This function constructs the `from_value` function for structs. /// The implementation is straightforward as most of the heavy lifting is handled by /// [`parse_value_via_fields`], and this function only needs to construct the signature around it. /// /// For structs with named fields, this constructs a large return type where each field /// contains the implementation for that specific field. /// In structs with unnamed fields, a [`VecDeque`](std::collections::VecDeque) is used to load each /// field one after another, and the result is used to construct the tuple. /// For unit structs, this only checks if the input value is `Value::Nothing`. /// /// # Examples /// /// These examples show what the macro would generate. /// /// Struct with named fields: /// ```rust /// #[derive(IntoValue)] /// struct Pet { /// name: String, /// age: u8, /// favorite_toy: Option<String>, /// } /// /// impl nu_protocol::FromValue for Pet { /// fn from_value( /// v: nu_protocol::Value /// ) -> std::result::Result<Self, nu_protocol::ShellError> { /// let span = v.span(); /// let mut record = v.into_record()?; /// std::result::Result::Ok(Pet { /// name: <String as nu_protocol::FromValue>::from_value( /// record /// .remove("name") /// .ok_or_else(|| nu_protocol::ShellError::CantFindColumn { /// col_name: std::string::ToString::to_string("name"), /// span: std::option::Option::None, /// src_span: span /// })?, /// )?, /// age: <u8 as nu_protocol::FromValue>::from_value( /// record /// .remove("age") /// .ok_or_else(|| nu_protocol::ShellError::CantFindColumn { /// col_name: std::string::ToString::to_string("age"), /// span: std::option::Option::None, /// src_span: span /// })?, /// )?, /// favorite_toy: record /// .remove("favorite_toy") /// .map(|v| <#ty as nu_protocol::FromValue>::from_value(v)) /// .transpose()? /// .flatten(), /// }) /// } /// } /// ``` /// /// Struct with unnamed fields: /// ```rust /// #[derive(IntoValue)] /// struct Color(u8, u8, u8); /// /// impl nu_protocol::FromValue for Color { /// fn from_value( /// v: nu_protocol::Value /// ) -> std::result::Result<Self, nu_protocol::ShellError> { /// let span = v.span(); /// let list = v.into_list()?; /// let mut deque: std::collections::VecDeque<_> = std::convert::From::from(list); /// std::result::Result::Ok(Self( /// { /// <u8 as nu_protocol::FromValue>::from_value( /// deque /// .pop_front() /// .ok_or_else(|| nu_protocol::ShellError::CantFindColumn { /// col_name: std::string::ToString::to_string(&0), /// span: std::option::Option::None, /// src_span: span /// })?, /// )? /// }, /// { /// <u8 as nu_protocol::FromValue>::from_value( /// deque /// .pop_front() /// .ok_or_else(|| nu_protocol::ShellError::CantFindColumn { /// col_name: std::string::ToString::to_string(&1), /// span: std::option::Option::None, /// src_span: span /// })?, /// )? /// }, /// { /// <u8 as nu_protocol::FromValue>::from_value( /// deque /// .pop_front() /// .ok_or_else(|| nu_protocol::ShellError::CantFindColumn { /// col_name: std::string::ToString::to_string(&2), /// span: std::option::Option::None, /// src_span: span /// })?, /// )? /// } /// )) /// } /// } /// ``` /// /// Unit struct: /// ```rust /// #[derive(IntoValue)] /// struct Unicorn; /// /// impl nu_protocol::FromValue for Unicorn { /// fn from_value( /// v: nu_protocol::Value /// ) -> std::result::Result<Self, nu_protocol::ShellError> { /// match v { /// nu_protocol::Value::Nothing {..} => Ok(Self), /// v => std::result::Result::Err(nu_protocol::ShellError::CantConvert { /// to_type: std::string::ToString::to_string(&<Self as nu_protocol::FromValue>::expected_type()), /// from_type: std::string::ToString::to_string(&v.get_type()), /// span: v.span(), /// help: std::option::Option::None /// }) /// } /// } /// } /// ``` fn struct_from_value(data: &DataStruct, container_attrs: &ContainerAttributes) -> Result { let body = parse_value_via_fields(&data.fields, quote!(Self), container_attrs)?; Ok(quote! { fn from_value( v: nu_protocol::Value ) -> std::result::Result<Self, nu_protocol::ShellError> { #body } }) } /// Implements `FromValue::expected_type` for structs. /// /// This function constructs the `expected_type` function for structs based on the provided fields. /// The type depends on the `fields`: /// - Named fields construct a record type where each key corresponds to a field name. /// The specific keys are resolved by [`NameResolver::resolve_ident`]. /// - Unnamed fields construct a custom type with the format `list[type0, type1, type2]`. /// - Unit structs expect `Type::Nothing`. /// /// If the `#[nu_value(type_name = "...")]` attribute is used, the output type will be /// `Type::Custom` with the provided name. /// /// # Examples /// /// These examples show what the macro would generate. /// /// Struct with named fields: /// ```rust /// #[derive(FromValue)] /// struct Pet { /// name: String, /// age: u8, /// #[nu_value(rename = "toy")] /// favorite_toy: Option<String>, /// } /// /// impl nu_protocol::FromValue for Pet { /// fn expected_type() -> nu_protocol::Type { /// nu_protocol::Type::Record( /// std::vec![ /// ( /// std::string::ToString::to_string("name"), /// <String as nu_protocol::FromValue>::expected_type(), /// ), /// ( /// std::string::ToString::to_string("age"), /// <u8 as nu_protocol::FromValue>::expected_type(), /// ), /// ( /// std::string::ToString::to_string("toy"), /// <Option<String> as nu_protocol::FromValue>::expected_type(), /// ) /// ].into_boxed_slice() /// ) /// } /// } /// ``` /// /// Struct with unnamed fields: /// ```rust /// #[derive(FromValue)] /// struct Color(u8, u8, u8); /// /// impl nu_protocol::FromValue for Color { /// fn expected_type() -> nu_protocol::Type { /// nu_protocol::Type::Custom( /// std::format!( /// "[{}, {}, {}]", /// <u8 as nu_protocol::FromValue>::expected_type(), /// <u8 as nu_protocol::FromValue>::expected_type(), /// <u8 as nu_protocol::FromValue>::expected_type() /// ) /// .into_boxed_str() /// ) /// } /// } /// ``` /// /// Unit struct: /// ```rust /// #[derive(FromValue)] /// struct Unicorn; /// /// impl nu_protocol::FromValue for Color { /// fn expected_type() -> nu_protocol::Type { /// nu_protocol::Type::Nothing /// } /// } /// ``` /// /// Struct with passed type name: /// ```rust /// #[derive(FromValue)] /// #[nu_value(type_name = "bird")] /// struct Parrot; /// /// impl nu_protocol::FromValue for Parrot { /// fn expected_type() -> nu_protocol::Type { /// nu_protocol::Type::Custom( /// <std::string::String as std::convert::From::<&str>>::from("bird") /// .into_boxed_str() /// ) /// } /// } /// ``` fn struct_expected_type( fields: &Fields, attr_type_name: Option<&str>, container_attrs: &ContainerAttributes, ) -> Result { let ty = match (fields, attr_type_name) { (_, Some(type_name)) => { quote!(nu_protocol::Type::Custom( <std::string::String as std::convert::From::<&str>>::from(#type_name).into_boxed_str() )) } (Fields::Named(fields), _) => { let mut name_resolver = NameResolver::new(); let mut fields_ts = Vec::with_capacity(fields.named.len()); for field in fields.named.iter() { let member_attrs = MemberAttributes::parse_attrs(&field.attrs)?; let ident = field.ident.as_ref().expect("named has idents"); let ident_s = name_resolver.resolve_ident(ident, container_attrs, &member_attrs, None)?; let ty = &field.ty; fields_ts.push(quote! {( std::string::ToString::to_string(#ident_s), <#ty as nu_protocol::FromValue>::expected_type(), )}); } quote!(nu_protocol::Type::Record( std::vec![#(#fields_ts),*].into_boxed_slice() )) } (f @ Fields::Unnamed(fields), _) => { attributes::deny_fields(f)?; let mut iter = fields.unnamed.iter(); let fields = fields.unnamed.iter().map(|field| { let ty = &field.ty; quote!(<#ty as nu_protocol::FromValue>::expected_type()) }); let mut template = String::new(); template.push('['); if iter.next().is_some() { template.push_str("{}") } iter.for_each(|_| template.push_str(", {}")); template.push(']'); quote! { nu_protocol::Type::Custom( std::format!( #template, #(#fields),* ) .into_boxed_str() ) } } (Fields::Unit, _) => quote!(nu_protocol::Type::Nothing), }; Ok(quote! { fn expected_type() -> nu_protocol::Type { #ty } }) } /// Implements the `#[derive(FromValue)]` macro for enums. /// /// This function constructs the implementation of the `FromValue` trait for enums. /// It is designed to be on the same level as [`derive_struct_from_value`], even though this /// implementation is a lot simpler. /// The main `FromValue::from_value` implementation is handled by [`enum_from_value`]. /// The `FromValue::expected_type` implementation is usually kept empty to use the default /// implementation, but if `#[nu_value(type_name = "...")]` if given, we use that. fn derive_enum_from_value( ident: Ident, data: DataEnum, generics: Generics, attrs: Vec<Attribute>, ) -> Result { let container_attrs = ContainerAttributes::parse_attrs(attrs.iter())?; let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); let from_value_impl = enum_from_value(&data, &attrs)?; let expected_type_impl = enum_expected_type(container_attrs.type_name.as_deref()); Ok(quote! { #[automatically_derived] impl #impl_generics nu_protocol::FromValue for #ident #ty_generics #where_clause { #from_value_impl #expected_type_impl } }) } /// Implements `FromValue::from_value` for enums. /// /// This function constructs the `from_value` implementation for enums. /// It only accepts enums with unit variants, as it is currently unclear how other types of enums /// should be represented via a `Value`. /// This function checks that every field is a unit variant and constructs a match statement over /// all possible variants. /// The input value is expected to be a `Value::String` containing the name of the variant. /// That string is defined by the [`NameResolver::resolve_ident`] method with the `default` value /// being [`Case::Snake`]. /// /// If no matching variant is found, `ShellError::CantConvert` is returned. /// /// This is how such a derived implementation looks: /// ```rust /// #[derive(IntoValue)] /// enum Weather { /// Sunny, /// Cloudy, /// #[nu_value(rename = "rain")] /// Raining /// } /// /// impl nu_protocol::IntoValue for Weather { /// fn into_value(self, span: nu_protocol::Span) -> nu_protocol::Value { /// let span = v.span(); /// let ty = v.get_type(); /// /// let s = v.into_string()?; /// match s.as_str() { /// "sunny" => std::result::Ok(Self::Sunny), /// "cloudy" => std::result::Ok(Self::Cloudy), /// "rain" => std::result::Ok(Self::Raining), /// _ => std::result::Result::Err(nu_protocol::ShellError::CantConvert { /// to_type: std::string::ToString::to_string( /// &<Self as nu_protocol::FromValue>::expected_type() /// ), /// from_type: std::string::ToString::to_string(&ty), /// span: span,help: std::option::Option::None, /// }), /// } /// } /// } /// ``` fn enum_from_value(data: &DataEnum, attrs: &[Attribute]) -> Result { let container_attrs = ContainerAttributes::parse_attrs(attrs.iter())?; let mut name_resolver = NameResolver::new(); let arms: Vec<TokenStream2> = data .variants .iter() .map(|variant| { let member_attrs = MemberAttributes::parse_attrs(&variant.attrs)?; let ident = &variant.ident; let ident_s = name_resolver.resolve_ident(ident, &container_attrs, &member_attrs, Case::Snake)?; match &variant.fields { Fields::Named(fields) => Err(DeriveError::UnsupportedEnums { fields_span: fields.span(), }), Fields::Unnamed(fields) => Err(DeriveError::UnsupportedEnums { fields_span: fields.span(), }), Fields::Unit => Ok(quote!(#ident_s => std::result::Result::Ok(Self::#ident))), } }) .collect::<Result<_>>()?; Ok(quote! { fn from_value( v: nu_protocol::Value ) -> std::result::Result<Self, nu_protocol::ShellError> { let span = v.span(); let ty = v.get_type(); let s = v.into_string()?; match s.as_str() { #(#arms,)* _ => std::result::Result::Err(nu_protocol::ShellError::CantConvert { to_type: std::string::ToString::to_string( &<Self as nu_protocol::FromValue>::expected_type() ), from_type: std::string::ToString::to_string(&ty), span: span, help: std::option::Option::None, }), } } }) } /// Implements `FromValue::expected_type` for enums. /// /// Since it's difficult to name the type of an enum in the current type system, we want to use the /// default implementation if `#[nu_value(type_name = "...")]` was *not* given. /// For that, a `None` value is returned, for a passed type name we return something like this: /// ```rust /// #[derive(IntoValue)] /// #[nu_value(type_name = "sunny | cloudy | raining")] /// enum Weather { /// Sunny, /// Cloudy, /// Raining /// } /// /// impl nu_protocol::FromValue for Weather { /// fn expected_type() -> nu_protocol::Type { /// nu_protocol::Type::Custom( /// <std::string::String as std::convert::From::<&str>>::from("sunny | cloudy | raining") /// .into_boxed_str() /// ) /// } /// } /// ``` fn enum_expected_type(attr_type_name: Option<&str>) -> Option<TokenStream2> { let type_name = attr_type_name?; Some(quote! { fn expected_type() -> nu_protocol::Type { nu_protocol::Type::Custom( <std::string::String as std::convert::From::<&str>>::from(#type_name) .into_boxed_str() ) } }) } /// Parses a `Value` into self. /// /// This function handles parsing a `Value` into the corresponding struct or enum variant (`self`). /// It takes three parameters: `fields`, `self_ident`, and `rename_all`. /// /// - The `fields` parameter specifies the expected structure of the `Value`: /// - Named fields expect a `Value::Record`. /// - Unnamed fields expect a `Value::List`. /// - A unit struct expects `Value::Nothing`. /// /// For named fields, each field in the record is matched to a struct field. /// The name matching uses the identifiers resolved by /// [`NameResolver`](NameResolver::resolve_ident) with `default` being `None`. /// /// The `self_ident` parameter is used to specify the identifier for the returned value. /// For most structs, `Self` is sufficient, but `Self::Variant` may be needed for enum variants. /// /// The `container_attrs` parameters, provided through `#[nu_value]` on the container, defines /// global rules for the `FromValue` implementation. /// This is used for the [`NameResolver`] to resolve the correct ident in the `Value`. /// /// This function is more complex than the equivalent for `IntoValue` due to additional error /// handling: /// - If a named field is missing in the `Value`, `ShellError::CantFindColumn` is returned. /// - For unit structs, if the value is not `Value::Nothing`, `ShellError::CantConvert` is returned. /// /// The implementation avoids local variables for fields to prevent accidental shadowing, ensuring /// that fields with similar names do not cause unexpected behavior. /// This approach is not typically recommended in handwritten Rust, but it is acceptable for code /// generation. fn parse_value_via_fields( fields: &Fields, self_ident: impl ToTokens, container_attrs: &ContainerAttributes, ) -> Result { match fields { Fields::Named(fields) => { let mut name_resolver = NameResolver::new(); let mut fields_ts: Vec<TokenStream2> = Vec::with_capacity(fields.named.len()); for field in fields.named.iter() { let member_attrs = MemberAttributes::parse_attrs(&field.attrs)?; let ident = field.ident.as_ref().expect("named has idents"); let ident_s = name_resolver.resolve_ident(ident, container_attrs, &member_attrs, None)?; let ty = &field.ty; fields_ts.push(match (type_is_option(ty), member_attrs.default) { (true, _) => quote! { #ident: record .remove(#ident_s) .map(|v| <#ty as nu_protocol::FromValue>::from_value(v)) .transpose()? .flatten() }, (false, false) => quote! { #ident: <#ty as nu_protocol::FromValue>::from_value( record .remove(#ident_s) .ok_or_else(|| nu_protocol::ShellError::CantFindColumn { col_name: std::string::ToString::to_string(#ident_s), span: std::option::Option::None, src_span: span })?, )? }, (false, true) => quote! { #ident: record .remove(#ident_s) .map(|v| <#ty as nu_protocol::FromValue>::from_value(v)) .transpose()? .unwrap_or_default() }, }); } Ok(quote! { let span = v.span(); let mut record = v.into_record()?; std::result::Result::Ok(#self_ident {#(#fields_ts),*}) }) } f @ Fields::Unnamed(fields) => { attributes::deny_fields(f)?; let fields = fields.unnamed.iter().enumerate().map(|(i, field)| { let ty = &field.ty; quote! {{ <#ty as nu_protocol::FromValue>::from_value( deque .pop_front() .ok_or_else(|| nu_protocol::ShellError::CantFindColumn { col_name: std::string::ToString::to_string(&#i), span: std::option::Option::None, src_span: span })?, )? }} }); Ok(quote! { let span = v.span(); let list = v.into_list()?; let mut deque: std::collections::VecDeque<_> = std::convert::From::from(list); std::result::Result::Ok(#self_ident(#(#fields),*)) }) } Fields::Unit => Ok(quote! { match v { nu_protocol::Value::Nothing {..} => Ok(#self_ident), v => std::result::Result::Err(nu_protocol::ShellError::CantConvert { to_type: std::string::ToString::to_string(&<Self as nu_protocol::FromValue>::expected_type()), from_type: std::string::ToString::to_string(&v.get_type()), span: v.span(), help: std::option::Option::None }) } }), } } const FULLY_QUALIFIED_OPTION: &str = "std::option::Option"; const PARTIALLY_QUALIFIED_OPTION: &str = "option::Option"; const PRELUDE_OPTION: &str = "Option"; /// Check if the field type is an `Option`. /// /// This function checks if a given type is an `Option`. /// We assume that an `Option` is [`std::option::Option`] because we can't see the whole code and /// can't ask the compiler itself. /// If the `Option` type isn't `std::option::Option`, the user will get a compile error due to a /// type mismatch. /// It's very unusual for people to override `Option`, so this should rarely be an issue. /// /// When [rust#63084](https://github.com/rust-lang/rust/issues/63084) is resolved, we can use /// [`std::any::type_name`] for a static assertion check to get a more direct error messages. fn type_is_option(ty: &Type) -> bool { let s = ty.to_token_stream().to_string(); s.starts_with(PRELUDE_OPTION) || s.starts_with(PARTIALLY_QUALIFIED_OPTION) || s.starts_with(FULLY_QUALIFIED_OPTION) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-derive-value/src/case.rs
crates/nu-derive-value/src/case.rs
use heck::*; #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum Case { // directly supported by heck Pascal, Camel, Snake, Kebab, ScreamingSnake, Title, Cobol, Train, // custom variants Upper, Lower, Flat, ScreamingFlat, } impl Case { pub fn from_str(s: impl AsRef<str>) -> Option<Self> { match s.as_ref() { // The matched case are all useful variants from `convert_case` with aliases // that `serde` uses. "PascalCase" | "UpperCamelCase" => Case::Pascal, "camelCase" | "lowerCamelCase" => Case::Camel, "snake_case" => Case::Snake, "kebab-case" => Case::Kebab, "SCREAMING_SNAKE_CASE" | "UPPER_SNAKE_CASE" | "SHOUTY_SNAKE_CASE" => { Case::ScreamingSnake } "Title Case" => Case::Title, "COBOL-CASE" | "SCREAMING-KEBAB-CASE" | "UPPER-KEBAB-CASE" => Case::Cobol, "Train-Case" => Case::Train, "UPPER CASE" | "UPPER WITH SPACES CASE" => Case::Upper, "lower case" | "lower with spaces case" => Case::Lower, "flatcase" | "lowercase" => Case::Flat, "SCREAMINGFLATCASE" | "UPPERFLATCASE" | "UPPERCASE" => Case::ScreamingFlat, _ => return None, } .into() } } pub trait Casing { fn to_case(&self, case: impl Into<Option<Case>>) -> String; } impl<T: ToString> Casing for T { fn to_case(&self, case: impl Into<Option<Case>>) -> String { let s = self.to_string(); let Some(case) = case.into() else { return s.to_string(); }; match case { Case::Pascal => s.to_upper_camel_case(), Case::Camel => s.to_lower_camel_case(), Case::Snake => s.to_snake_case(), Case::Kebab => s.to_kebab_case(), Case::ScreamingSnake => s.to_shouty_snake_case(), Case::Title => s.to_title_case(), Case::Cobol => s.to_shouty_kebab_case(), Case::Train => s.to_train_case(), Case::Upper => s.to_shouty_snake_case().replace('_', " "), Case::Lower => s.to_snake_case().replace('_', " "), Case::Flat => s.to_snake_case().replace('_', ""), Case::ScreamingFlat => s.to_shouty_snake_case().replace('_', ""), } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-derive-value/src/lib.rs
crates/nu-derive-value/src/lib.rs
//! Macro implementations of `#[derive(FromValue, IntoValue)]`. //! //! As this crate is a [`proc_macro`] crate, it is only allowed to export //! [procedural macros](https://doc.rust-lang.org/reference/procedural-macros.html). //! Therefore, it only exports [`IntoValue`] and [`FromValue`]. //! //! To get documentation for other functions and types used in this crate, run //! `cargo doc -p nu-derive-value --document-private-items`. //! //! This crate uses a lot of //! [`proc_macro2::TokenStream`](https://docs.rs/proc-macro2/1.0.24/proc_macro2/struct.TokenStream.html) //! as `TokenStream2` to allow testing the behavior of the macros directly, including the output //! token stream or if the macro errors as expected. //! The tests for functionality can be found in `nu_protocol::value::test_derive`. //! //! This documentation is often less reference-heavy than typical Rust documentation. //! This is because this crate is a dependency for `nu_protocol`, and linking to it would create a //! cyclic dependency. //! Also all examples in the documentation aren't tested as this crate cannot be compiled as a //! normal library very easily. //! This might change in the future if cargo allows building a proc-macro crate differently for //! `cfg(doctest)` as they are already doing for `cfg(test)`. //! //! The generated code from the derive macros tries to be as //! [hygienic](https://doc.rust-lang.org/reference/macros-by-example.html#hygiene) as possible. //! This ensures that the macro can be called anywhere without requiring specific imports. //! This results in obtuse code, which isn't recommended for manual, handwritten Rust //! but ensures that no other code may influence this generated code or vice versa. use proc_macro::TokenStream; use proc_macro_error2::{Diagnostic, proc_macro_error}; use proc_macro2::TokenStream as TokenStream2; mod attributes; mod case; mod error; mod from; mod into; mod names; #[cfg(test)] mod tests; const HELPER_ATTRIBUTE: &str = "nu_value"; /// Derive macro generating an impl of the trait `IntoValue`. /// /// For further information, see the docs on the trait itself. #[proc_macro_derive(IntoValue, attributes(nu_value))] #[proc_macro_error] pub fn derive_into_value(input: TokenStream) -> TokenStream { let input = TokenStream2::from(input); let output = match into::derive_into_value(input) { Ok(output) => output, Err(e) => Diagnostic::from(e).abort(), }; TokenStream::from(output) } /// Derive macro generating an impl of the trait `FromValue`. /// /// For further information, see the docs on the trait itself. #[proc_macro_derive(FromValue, attributes(nu_value))] #[proc_macro_error] pub fn derive_from_value(input: TokenStream) -> TokenStream { let input = TokenStream2::from(input); let output = match from::derive_from_value(input) { Ok(output) => output, Err(e) => Diagnostic::from(e).abort(), }; TokenStream::from(output) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-derive-value/src/names.rs
crates/nu-derive-value/src/names.rs
use proc_macro2::Span; use std::collections::HashMap; use syn::Ident; use syn::ext::IdentExt; use crate::attributes::{ContainerAttributes, MemberAttributes}; use crate::case::{Case, Casing}; use crate::error::DeriveError; #[derive(Debug, Default)] pub struct NameResolver { seen_names: HashMap<String, Span>, } impl NameResolver { pub fn new() -> Self { Self::default() } /// Resolves an identifier using attributes and ensures its uniqueness. /// /// The identifier is transformed according to these rules: /// - If [`MemberAttributes::rename`] is set, this explicitly renamed value is used. /// The value is defined by the helper attribute `#[nu_value(rename = "...")]` on a member. /// - If the above is not set but [`ContainerAttributes::rename_all`] is, the identifier /// undergoes case conversion as specified by the helper attribute /// `#[nu_value(rename_all = "...")]` on the container (struct or enum). /// - If neither renaming attribute is set, the function applies the case conversion provided /// by the `default` parameter. /// If `default` is `None`, the identifier remains unchanged. /// /// This function checks the transformed identifier against previously seen identifiers to /// ensure it is unique. /// If a duplicate identifier is detected, it returns [`DeriveError::NonUniqueName`]. pub fn resolve_ident<M>( &mut self, ident: &Ident, container_attrs: &ContainerAttributes, member_attrs: &MemberAttributes, default: impl Into<Option<Case>>, ) -> Result<String, DeriveError<M>> { let span = ident.span(); let ident = if let Some(rename) = &member_attrs.rename { rename.clone() } else { let case = container_attrs.rename_all.or(default.into()); ident.unraw().to_case(case) }; if let Some(seen) = self.seen_names.get(&ident) { return Err(DeriveError::NonUniqueName { name: ident.to_string(), first: *seen, second: span, }); } self.seen_names.insert(ident.clone(), span); Ok(ident) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-derive-value/src/tests.rs
crates/nu-derive-value/src/tests.rs
// These tests only check that the derive macros throw the relevant errors. // Functionality of the derived types is tested in nu_protocol::value::test_derive. use crate::error::DeriveError; use crate::from::derive_from_value; use crate::into::derive_into_value; use quote::quote; #[test] fn unsupported_unions() { let input = quote! { #[nu_value] union SomeUnion { f1: u32, f2: f32, } }; let from_res = derive_from_value(input.clone()); assert!( matches!(from_res, Err(DeriveError::UnsupportedUnions)), "expected `DeriveError::UnsupportedUnions`, got {from_res:?}" ); let into_res = derive_into_value(input); assert!( matches!(into_res, Err(DeriveError::UnsupportedUnions)), "expected `DeriveError::UnsupportedUnions`, got {into_res:?}" ); } #[test] fn unsupported_enums() { let input = quote! { #[nu_value(rename_all = "SCREAMING_SNAKE_CASE")] enum ComplexEnum { Unit, Unnamed(u32, f32), Named { u: u32, f: f32, } } }; let from_res = derive_from_value(input.clone()); assert!( matches!(from_res, Err(DeriveError::UnsupportedEnums { .. })), "expected `DeriveError::UnsupportedEnums`, got {from_res:?}" ); let into_res = derive_into_value(input); assert!( matches!(into_res, Err(DeriveError::UnsupportedEnums { .. })), "expected `DeriveError::UnsupportedEnums`, got {into_res:?}" ); } #[test] fn unexpected_attribute() { let input = quote! { #[nu_value(what)] enum SimpleEnum { A, B, } }; let from_res = derive_from_value(input.clone()); assert!( matches!(from_res, Err(DeriveError::UnexpectedAttribute { .. })), "expected `DeriveError::UnexpectedAttribute`, got {from_res:?}" ); let into_res = derive_into_value(input); assert!( matches!(into_res, Err(DeriveError::UnexpectedAttribute { .. })), "expected `DeriveError::UnexpectedAttribute`, got {into_res:?}" ); } #[test] fn unexpected_attribute_on_struct_field() { let input = quote! { struct SimpleStruct { #[nu_value(what)] field_a: i32, field_b: String, } }; let from_res = derive_from_value(input.clone()); assert!( matches!(from_res, Err(DeriveError::UnexpectedAttribute { .. })), "expected `DeriveError::UnexpectedAttribute`, got {from_res:?}" ); let into_res = derive_into_value(input); assert!( matches!(into_res, Err(DeriveError::UnexpectedAttribute { .. })), "expected `DeriveError::UnexpectedAttribute`, got {into_res:?}" ); } #[test] fn unexpected_attribute_on_enum_variant() { let input = quote! { enum SimpleEnum { #[nu_value(what)] A, B, } }; let from_res = derive_from_value(input.clone()); assert!( matches!(from_res, Err(DeriveError::UnexpectedAttribute { .. })), "expected `DeriveError::UnexpectedAttribute`, got {from_res:?}" ); let into_res = derive_into_value(input); assert!( matches!(into_res, Err(DeriveError::UnexpectedAttribute { .. })), "expected `DeriveError::UnexpectedAttribute`, got {into_res:?}" ); } #[test] fn invalid_attribute_position_in_tuple_struct() { let input = quote! { struct SimpleTupleStruct( #[nu_value(what)] i32, String, ); }; let from_res = derive_from_value(input.clone()); assert!( matches!( from_res, Err(DeriveError::InvalidAttributePosition { attribute_span: _ }) ), "expected `DeriveError::InvalidAttributePosition`, got {from_res:?}" ); let into_res = derive_into_value(input); assert!( matches!( into_res, Err(DeriveError::InvalidAttributePosition { attribute_span: _ }) ), "expected `DeriveError::InvalidAttributePosition`, got {into_res:?}" ); } #[test] fn invalid_attribute_value() { let input = quote! { #[nu_value(rename_all = "CrazY-CasE")] enum SimpleEnum { A, B } }; let from_res = derive_from_value(input.clone()); assert!( matches!(from_res, Err(DeriveError::InvalidAttributeValue { .. })), "expected `DeriveError::InvalidAttributeValue`, got {from_res:?}" ); let into_res = derive_into_value(input); assert!( matches!(into_res, Err(DeriveError::InvalidAttributeValue { .. })), "expected `DeriveError::InvalidAttributeValue`, got {into_res:?}" ); } #[test] fn non_unique_struct_keys() { let input = quote! { struct DuplicateStruct { #[nu_value(rename = "field")] some_field: (), field: (), } }; let from_res = derive_from_value(input.clone()); assert!( matches!(from_res, Err(DeriveError::NonUniqueName { .. })), "expected `DeriveError::NonUniqueName`, got {from_res:?}" ); let into_res = derive_into_value(input); assert!( matches!(into_res, Err(DeriveError::NonUniqueName { .. })), "expected `DeriveError::NonUniqueName`, got {into_res:?}" ); } #[test] fn non_unique_enum_variants() { let input = quote! { enum DuplicateEnum { #[nu_value(rename = "variant")] SomeVariant, Variant } }; let from_res = derive_from_value(input.clone()); assert!( matches!(from_res, Err(DeriveError::NonUniqueName { .. })), "expected `DeriveError::NonUniqueName`, got {from_res:?}" ); let into_res = derive_into_value(input); assert!( matches!(into_res, Err(DeriveError::NonUniqueName { .. })), "expected `DeriveError::NonUniqueName`, got {into_res:?}" ); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-derive-value/src/error.rs
crates/nu-derive-value/src/error.rs
use std::{any, fmt::Debug, marker::PhantomData}; use proc_macro_error2::{Diagnostic, Level}; use proc_macro2::Span; #[derive(Debug)] pub enum DeriveError<M> { /// Marker variant, makes the `M` generic parameter valid. _Marker(PhantomData<M>), /// Parsing errors thrown by `syn`. Syn(syn::parse::Error), /// `syn::DeriveInput` was a union, currently not supported UnsupportedUnions, /// Only plain enums are supported right now. UnsupportedEnums { fields_span: Span }, /// Found a `#[nu_value(x)]` attribute where `x` is unexpected. UnexpectedAttribute { meta_span: Span }, /// Found a `#[nu_value(x)]` attribute at a invalid position. InvalidAttributePosition { attribute_span: Span }, /// Found a valid `#[nu_value(x)]` attribute but the passed values is invalid. InvalidAttributeValue { value_span: Span, value: Box<dyn Debug>, }, /// Two keys or variants are called the same name breaking bidirectionality. NonUniqueName { name: String, first: Span, second: Span, }, } impl<M> From<syn::parse::Error> for DeriveError<M> { fn from(value: syn::parse::Error) -> Self { Self::Syn(value) } } impl<M> From<DeriveError<M>> for Diagnostic { fn from(value: DeriveError<M>) -> Self { let derive_name = any::type_name::<M>().split("::").last().expect("not empty"); match value { DeriveError::_Marker(_) => panic!("used marker variant"), DeriveError::Syn(e) => Diagnostic::spanned(e.span(), Level::Error, e.to_string()), DeriveError::UnsupportedUnions => Diagnostic::new( Level::Error, format!("`{derive_name}` cannot be derived from unions"), ) .help("consider refactoring to a struct".to_string()) .note("if you really need a union, consider opening an issue on Github".to_string()), DeriveError::UnsupportedEnums { fields_span } => Diagnostic::spanned( fields_span, Level::Error, format!("`{derive_name}` can only be derived from plain enums"), ) .help( "consider refactoring your data type to a struct with a plain enum as a field" .to_string(), ) .note("more complex enums could be implemented in the future".to_string()), DeriveError::InvalidAttributePosition { attribute_span } => Diagnostic::spanned( attribute_span, Level::Error, "invalid attribute position".to_string(), ) .help(format!( "check documentation for `{derive_name}` for valid placements" )), DeriveError::UnexpectedAttribute { meta_span } => { Diagnostic::spanned(meta_span, Level::Error, "unknown attribute".to_string()).help( format!("check documentation for `{derive_name}` for valid attributes"), ) } DeriveError::InvalidAttributeValue { value_span, value } => { Diagnostic::spanned(value_span, Level::Error, format!("invalid value {value:?}")) .help(format!( "check documentation for `{derive_name}` for valid attribute values" )) } DeriveError::NonUniqueName { name, first, second, } => Diagnostic::new(Level::Error, format!("non-unique name {name:?} found")) .span_error(first, "first occurrence found here".to_string()) .span_error(second, "second occurrence found here".to_string()) .help("use `#[nu_value(rename = \"...\")]` to ensure unique names".to_string()), } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-derive-value/src/into.rs
crates/nu-derive-value/src/into.rs
use proc_macro2::TokenStream as TokenStream2; use quote::{ToTokens, quote}; use syn::{ Attribute, Data, DataEnum, DataStruct, DeriveInput, Fields, Generics, Ident, Index, spanned::Spanned, }; use crate::{ attributes::{self, ContainerAttributes, MemberAttributes, ParseAttrs}, case::Case, names::NameResolver, }; #[derive(Debug)] pub struct IntoValue; type DeriveError = super::error::DeriveError<IntoValue>; type Result<T = TokenStream2> = std::result::Result<T, DeriveError>; /// Inner implementation of the `#[derive(IntoValue)]` macro for structs and enums. /// /// Uses `proc_macro2::TokenStream` for better testing support, unlike `proc_macro::TokenStream`. /// /// This function directs the `IntoValue` trait derivation to the correct implementation based on /// the input type: /// - For structs: [`struct_into_value`] /// - For enums: [`enum_into_value`] /// - Unions are not supported and will return an error. pub fn derive_into_value(input: TokenStream2) -> Result { let input: DeriveInput = syn::parse2(input).map_err(DeriveError::Syn)?; match input.data { Data::Struct(data_struct) => Ok(struct_into_value( input.ident, data_struct, input.generics, input.attrs, )?), Data::Enum(data_enum) => Ok(enum_into_value( input.ident, data_enum, input.generics, input.attrs, )?), Data::Union(_) => Err(DeriveError::UnsupportedUnions), } } /// Implements the `#[derive(IntoValue)]` macro for structs. /// /// Automatically derives the `IntoValue` trait for any struct where each field implements /// `IntoValue`. /// For structs with named fields, the derived implementation creates a `Value::Record` using the /// struct fields as keys. /// The specific keys are resolved by [`NameResolver`](NameResolver::resolve_ident). /// Each field value is converted using the `IntoValue::into_value` method. /// For structs with unnamed fields, this generates a `Value::List` with each field in the list. /// For unit structs, this generates `Value::Nothing`, because there is no data. /// /// This function provides the signature and prepares the call to the [`fields_return_value`] /// function which does the heavy lifting of creating the `Value` calls. /// /// # Examples /// /// These examples show what the macro would generate. /// /// Struct with named fields: /// ```rust /// #[derive(IntoValue)] /// struct Pet { /// name: String, /// age: u8, /// favorite_toy: Option<String>, /// } /// /// impl nu_protocol::IntoValue for Pet { /// fn into_value(self, span: nu_protocol::Span) -> nu_protocol::Value { /// nu_protocol::Value::record(nu_protocol::record! { /// "name" => nu_protocol::IntoValue::into_value(self.name, span), /// "age" => nu_protocol::IntoValue::into_value(self.age, span), /// "favorite_toy" => nu_protocol::IntoValue::into_value(self.favorite_toy, span), /// }, span) /// } /// } /// ``` /// /// Struct with unnamed fields: /// ```rust /// #[derive(IntoValue)] /// struct Color(u8, u8, u8); /// /// impl nu_protocol::IntoValue for Color { /// fn into_value(self, span: nu_protocol::Span) -> nu_protocol::Value { /// nu_protocol::Value::list(vec![ /// nu_protocol::IntoValue::into_value(self.0, span), /// nu_protocol::IntoValue::into_value(self.1, span), /// nu_protocol::IntoValue::into_value(self.2, span), /// ], span) /// } /// } /// ``` /// /// Unit struct: /// ```rust /// #[derive(IntoValue)] /// struct Unicorn; /// /// impl nu_protocol::IntoValue for Unicorn { /// fn into_value(self, span: nu_protocol::Span) -> nu_protocol::Value { /// nu_protocol::Value::nothing(span) /// } /// } /// ``` fn struct_into_value( ident: Ident, data: DataStruct, generics: Generics, attrs: Vec<Attribute>, ) -> Result { let container_attrs = ContainerAttributes::parse_attrs(attrs.iter())?; let record = match &data.fields { Fields::Named(fields) => { let accessor = fields .named .iter() .map(|field| field.ident.as_ref().expect("named has idents")) .map(|ident| quote!(self.#ident)); fields_return_value(&data.fields, accessor, &container_attrs)? } Fields::Unnamed(fields) => { let accessor = fields .unnamed .iter() .enumerate() .map(|(n, _)| Index::from(n)) .map(|index| quote!(self.#index)); fields_return_value(&data.fields, accessor, &container_attrs)? } Fields::Unit => quote!(nu_protocol::Value::nothing(span)), }; let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); Ok(quote! { #[automatically_derived] impl #impl_generics nu_protocol::IntoValue for #ident #ty_generics #where_clause { fn into_value(self, span: nu_protocol::Span) -> nu_protocol::Value { #record } } }) } /// Implements the `#[derive(IntoValue)]` macro for enums. /// /// This function implements the derive macro `IntoValue` for enums. /// Currently, only unit enum variants are supported as it is not clear how other types of enums /// should be represented in a `Value`. /// For simple enums, we represent the enum as a `Value::String`. /// For other types of variants, we return an error. /// /// The variant name used in the `Value::String` is resolved by the /// [`NameResolver`](NameResolver::resolve_ident) with the `default` being [`Case::Snake`]. /// The implementation matches over all variants, uses the appropriate variant name, and constructs /// a `Value::String`. /// /// This is how such a derived implementation looks: /// ```rust /// #[derive(IntoValue)] /// enum Weather { /// Sunny, /// Cloudy, /// #[nu_value(rename = "rain")] /// Raining /// } /// /// impl nu_protocol::IntoValue for Weather { /// fn into_value(self, span: nu_protocol::Span) -> nu_protocol::Value { /// match self { /// Self::Sunny => nu_protocol::Value::string("sunny", span), /// Self::Cloudy => nu_protocol::Value::string("cloudy", span), /// Self::Raining => nu_protocol::Value::string("rain", span), /// } /// } /// } /// ``` fn enum_into_value( ident: Ident, data: DataEnum, generics: Generics, attrs: Vec<Attribute>, ) -> Result { let container_attrs = ContainerAttributes::parse_attrs(attrs.iter())?; let mut name_resolver = NameResolver::new(); let arms: Vec<TokenStream2> = data .variants .into_iter() .map(|variant| { let member_attrs = MemberAttributes::parse_attrs(variant.attrs.iter())?; let ident = variant.ident; let ident_s = name_resolver.resolve_ident( &ident, &container_attrs, &member_attrs, Case::Snake, )?; match &variant.fields { // In the future we can implement more complex enums here. Fields::Named(fields) => Err(DeriveError::UnsupportedEnums { fields_span: fields.span(), }), Fields::Unnamed(fields) => Err(DeriveError::UnsupportedEnums { fields_span: fields.span(), }), Fields::Unit => { Ok(quote!(Self::#ident => nu_protocol::Value::string(#ident_s, span))) } } }) .collect::<Result<_>>()?; let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); Ok(quote! { impl #impl_generics nu_protocol::IntoValue for #ident #ty_generics #where_clause { fn into_value(self, span: nu_protocol::Span) -> nu_protocol::Value { match self { #(#arms,)* } } } }) } /// Constructs the final `Value` that the macro generates. /// /// This function handles the construction of the final `Value` that the macro generates, primarily /// for structs. /// It takes three parameters: `fields`, which allows iterating over each field of a data type, /// `accessor`, which generalizes data access, and `container_attrs`, which is used for the /// [`NameResolver`]. /// /// - **Field Keys**: /// The field key is field name of the input struct and resolved the /// [`NameResolver`](NameResolver::resolve_ident). /// /// - **Fields Type**: /// - Determines whether to generate a `Value::Record`, `Value::List`, or `Value::Nothing` based /// on the nature of the fields. /// - Named fields are directly used to generate the record key, as described above. /// /// - **Accessor**: /// - Generalizes how data is accessed for different data types. /// - For named fields in structs, this is typically `self.field_name`. /// - For unnamed fields (e.g., tuple structs), it should be an iterator similar to named fields /// but accessing fields like `self.0`. /// - For unit structs, this parameter is ignored. /// /// This design allows the same function to potentially handle both structs and enums with data /// variants in the future. fn fields_return_value( fields: &Fields, accessor: impl Iterator<Item = impl ToTokens>, container_attrs: &ContainerAttributes, ) -> Result { match fields { Fields::Named(fields) => { let mut name_resolver = NameResolver::new(); let mut items: Vec<TokenStream2> = Vec::with_capacity(fields.named.len()); for (field, accessor) in fields.named.iter().zip(accessor) { let member_attrs = MemberAttributes::parse_attrs(field.attrs.iter())?; let ident = field.ident.as_ref().expect("named has idents"); let field = name_resolver.resolve_ident(ident, container_attrs, &member_attrs, None)?; items.push(quote!(#field => nu_protocol::IntoValue::into_value(#accessor, span))); } Ok(quote! { nu_protocol::Value::record(nu_protocol::record! { #(#items),* }, span) }) } f @ Fields::Unnamed(fields) => { attributes::deny_fields(f)?; let items = fields.unnamed.iter().zip(accessor).map( |(_, accessor)| quote!(nu_protocol::IntoValue::into_value(#accessor, span)), ); Ok(quote!(nu_protocol::Value::list( std::vec![#(#items),*], span ))) } Fields::Unit => Ok(quote!(nu_protocol::Value::nothing(span))), } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-derive-value/src/attributes.rs
crates/nu-derive-value/src/attributes.rs
use syn::{Attribute, Fields, LitStr, meta::ParseNestedMeta, spanned::Spanned}; use crate::{HELPER_ATTRIBUTE, case::Case, error::DeriveError}; pub trait ParseAttrs: Default { fn parse_attrs<'a, M>( iter: impl IntoIterator<Item = &'a Attribute>, ) -> Result<Self, DeriveError<M>> { let mut attrs = Self::default(); for attr in filter(iter.into_iter()) { // This is a container to allow returning derive errors inside the parse_nested_meta fn. let mut err = Ok(()); let _ = attr.parse_nested_meta(|meta| { attrs.parse_attr(meta).or_else(|e| { err = Err(e); Ok(()) // parse_nested_meta requires another error type, so we escape it here }) }); err?; // Shortcircuit here if `err` is holding some error. } Ok(attrs) } fn parse_attr<M>(&mut self, attr_meta: ParseNestedMeta<'_>) -> Result<(), DeriveError<M>>; } #[derive(Debug, Default)] pub struct ContainerAttributes { pub rename_all: Option<Case>, pub type_name: Option<String>, } impl ParseAttrs for ContainerAttributes { fn parse_attr<M>(&mut self, attr_meta: ParseNestedMeta<'_>) -> Result<(), DeriveError<M>> { let ident = attr_meta.path.require_ident()?; match ident.to_string().as_str() { "rename_all" => { let case: LitStr = attr_meta.value()?.parse()?; let value_span = case.span(); let case = case.value(); match Case::from_str(&case) { Some(case) => self.rename_all = Some(case), None => { return Err(DeriveError::InvalidAttributeValue { value_span, value: Box::new(case), }); } } } "type_name" => { let type_name: LitStr = attr_meta.value()?.parse()?; let type_name = type_name.value(); self.type_name = Some(type_name); } ident => { return Err(DeriveError::UnexpectedAttribute { meta_span: ident.span(), }); } } Ok(()) } } #[derive(Debug, Default)] pub struct MemberAttributes { pub rename: Option<String>, pub default: bool, } impl ParseAttrs for MemberAttributes { fn parse_attr<M>(&mut self, attr_meta: ParseNestedMeta<'_>) -> Result<(), DeriveError<M>> { let ident = attr_meta.path.require_ident()?; match ident.to_string().as_str() { "rename" => { let rename: LitStr = attr_meta.value()?.parse()?; let rename = rename.value(); self.rename = Some(rename); } "default" => { self.default = true; } ident => { return Err(DeriveError::UnexpectedAttribute { meta_span: ident.span(), }); } } Ok(()) } } pub fn filter<'a>( iter: impl Iterator<Item = &'a Attribute>, ) -> impl Iterator<Item = &'a Attribute> { iter.filter(|attr| attr.path().is_ident(HELPER_ATTRIBUTE)) } // The deny functions are built to easily deny the use of the helper attribute if used incorrectly. // As the usage of it gets more complex, these functions might be discarded or replaced. /// Deny any attribute that uses the helper attribute. pub fn deny<M>(attrs: &[Attribute]) -> Result<(), DeriveError<M>> { match filter(attrs.iter()).next() { Some(attr) => Err(DeriveError::InvalidAttributePosition { attribute_span: attr.span(), }), None => Ok(()), } } /// Deny any attributes that uses the helper attribute on any field. pub fn deny_fields<M>(fields: &Fields) -> Result<(), DeriveError<M>> { match fields { Fields::Named(fields) => { for field in fields.named.iter() { deny(&field.attrs)?; } } Fields::Unnamed(fields) => { for field in fields.unnamed.iter() { deny(&field.attrs)?; } } Fields::Unit => (), } Ok(()) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/lib.rs
crates/nu-cmd-extra/src/lib.rs
#![doc = include_str!("../README.md")] mod example_test; pub mod extra; pub use extra::*; #[cfg(test)] pub use example_test::{test_examples, test_examples_with_commands};
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/example_test.rs
crates/nu-cmd-extra/src/example_test.rs
#[cfg(test)] use nu_protocol::engine::Command; #[cfg(test)] pub fn test_examples(cmd: impl Command + 'static) { test_examples::test_examples(cmd, &[]); } #[cfg(test)] pub fn test_examples_with_commands(cmd: impl Command + 'static, commands: &[&dyn Command]) { test_examples::test_examples(cmd, commands); } #[cfg(test)] mod test_examples { use nu_cmd_lang::example_support::{ check_all_signature_input_output_types_entries_have_examples, check_example_evaluates_to_expected_output, check_example_input_and_output_types_match_command_signature, }; use nu_protocol::{ Type, engine::{Command, EngineState, StateWorkingSet}, }; use std::collections::HashSet; pub fn test_examples(cmd: impl Command + 'static, commands: &[&dyn Command]) { let examples = cmd.examples(); let signature = cmd.signature(); let mut engine_state = make_engine_state(cmd.clone_box(), commands); let cwd = std::env::current_dir().expect("Could not get current working directory."); let mut witnessed_type_transformations = HashSet::<(Type, Type)>::new(); for example in examples { if example.result.is_none() { continue; } witnessed_type_transformations.extend( check_example_input_and_output_types_match_command_signature( &example, &cwd, &mut make_engine_state(cmd.clone_box(), commands), &signature.input_output_types, signature.operates_on_cell_paths(), ), ); check_example_evaluates_to_expected_output( cmd.name(), &example, cwd.as_path(), &mut engine_state, ); } check_all_signature_input_output_types_entries_have_examples( signature, witnessed_type_transformations, ); } fn make_engine_state(cmd: Box<dyn Command>, commands: &[&dyn Command]) -> Box<EngineState> { let mut engine_state = Box::new(EngineState::new()); let delta = { // Base functions that are needed for testing // Try to keep this working set small to keep tests running as fast as possible let mut working_set = StateWorkingSet::new(&engine_state); working_set.add_decl(Box::new(nu_command::Enumerate)); working_set.add_decl(Box::new(nu_cmd_lang::If)); working_set.add_decl(Box::new(nu_command::MathRound)); for command in commands { working_set.add_decl(command.clone_box()); } // Adding the command that is being tested to the working set working_set.add_decl(cmd); working_set.render() }; engine_state .merge_delta(delta) .expect("Error merging delta"); engine_state } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/mod.rs
crates/nu-cmd-extra/src/extra/mod.rs
mod bits; mod filters; mod formats; mod math; mod platform; mod strings; pub use bits::{Bits, BitsAnd, BitsNot, BitsOr, BitsRol, BitsRor, BitsShl, BitsShr, BitsXor}; pub use formats::ToHtml; pub use math::{MathArcCos, MathArcCosH, MathArcSin, MathArcSinH, MathArcTan, MathArcTanH}; pub use math::{MathCos, MathCosH, MathSin, MathSinH, MathTan, MathTanH}; pub use math::{MathExp, MathLn}; use nu_protocol::engine::{EngineState, StateWorkingSet}; pub fn add_extra_command_context(mut engine_state: EngineState) -> EngineState { let delta = { let mut working_set = StateWorkingSet::new(&engine_state); macro_rules! bind_command { ( $command:expr ) => { working_set.add_decl(Box::new($command)); }; ( $( $command:expr ),* ) => { $( working_set.add_decl(Box::new($command)); )* }; } bind_command!( filters::UpdateCells, filters::EachWhile, filters::Roll, filters::RollDown, filters::RollUp, filters::RollLeft, filters::RollRight, filters::Rotate ); bind_command!(platform::ansi::Gradient); bind_command!( strings::format::FormatPattern, strings::format::FormatBits, strings::format::FormatNumber, strings::str_::case::Str, strings::str_::case::StrCamelCase, strings::str_::case::StrKebabCase, strings::str_::case::StrPascalCase, strings::str_::case::StrScreamingSnakeCase, strings::str_::case::StrSnakeCase, strings::str_::case::StrTitleCase ); bind_command!(ToHtml, formats::FromUrl); // Bits bind_command! { Bits, BitsAnd, BitsNot, BitsOr, BitsRol, BitsRor, BitsShl, BitsShr, BitsXor } // Math bind_command! { MathArcSin, MathArcCos, MathArcTan, MathArcSinH, MathArcCosH, MathArcTanH, MathSin, MathCos, MathTan, MathSinH, MathCosH, MathTanH, MathExp, MathLn }; working_set.render() }; if let Err(err) = engine_state.merge_delta(delta) { eprintln!("Error creating extra 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-cmd-extra/src/extra/math/arccosh.rs
crates/nu-cmd-extra/src/extra/math/arccosh.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct MathArcCosH; impl Command for MathArcCosH { fn name(&self) -> &str { "math arccosh" } fn signature(&self) -> Signature { Signature::build("math arccosh") .input_output_types(vec![ (Type::Number, Type::Float), ( Type::List(Box::new(Type::Number)), Type::List(Box::new(Type::Float)), ), ]) .allow_variants_without_examples(true) .category(Category::Math) } fn description(&self) -> &str { "Returns the inverse of the hyperbolic cosine function." } fn search_terms(&self) -> Vec<&str> { vec!["trigonometry", "inverse", "hyperbolic"] } fn run( &self, engine_state: &EngineState, _stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; // This doesn't match explicit nulls if let PipelineData::Empty = input { return Err(ShellError::PipelineEmpty { dst_span: head }); } input.map(move |value| operate(value, head), engine_state.signals()) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Get the arccosh of 1", example: "1 | math arccosh", result: Some(Value::test_float(0.0f64)), }] } } fn operate(value: Value, head: Span) -> Value { match value { numeric @ (Value::Int { .. } | Value::Float { .. }) => { let span = numeric.span(); let (val, span) = match numeric { Value::Int { val, .. } => (val as f64, span), Value::Float { val, .. } => (val, span), _ => unreachable!(), }; if (1.0..).contains(&val) { let val = val.acosh(); Value::float(val, span) } else { Value::error( ShellError::UnsupportedInput { msg: "'arccosh' undefined for values below 1.".into(), input: "value originates from here".into(), msg_span: head, input_span: span, }, span, ) } } Value::Error { .. } => value, other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "numeric".into(), wrong_type: other.get_type().to_string(), dst_span: head, src_span: other.span(), }, head, ), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(MathArcCosH {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/math/sinh.rs
crates/nu-cmd-extra/src/extra/math/sinh.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct MathSinH; impl Command for MathSinH { fn name(&self) -> &str { "math sinh" } fn signature(&self) -> Signature { Signature::build("math sinh") .input_output_types(vec![ (Type::Number, Type::Float), ( Type::List(Box::new(Type::Number)), Type::List(Box::new(Type::Float)), ), ]) .allow_variants_without_examples(true) .category(Category::Math) } fn description(&self) -> &str { "Returns the hyperbolic sine of the number." } fn search_terms(&self) -> Vec<&str> { vec!["trigonometry", "hyperbolic"] } fn run( &self, engine_state: &EngineState, _stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; // This doesn't match explicit nulls if let PipelineData::Empty = input { return Err(ShellError::PipelineEmpty { dst_span: head }); } input.map(move |value| operate(value, head), engine_state.signals()) } fn examples(&self) -> Vec<Example<'_>> { let e = std::f64::consts::E; vec![Example { description: "Apply the hyperbolic sine to 1", example: "1 | math sinh", result: Some(Value::test_float((e * e - 1.0) / (2.0 * e))), }] } } fn operate(value: Value, head: Span) -> Value { match value { numeric @ (Value::Int { .. } | Value::Float { .. }) => { let span = numeric.span(); let (val, span) = match numeric { Value::Int { val, .. } => (val as f64, span), Value::Float { val, .. } => (val, span), _ => unreachable!(), }; Value::float(val.sinh(), span) } Value::Error { .. } => value, other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "numeric".into(), wrong_type: other.get_type().to_string(), dst_span: head, src_span: other.span(), }, head, ), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(MathSinH {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/math/arctan.rs
crates/nu-cmd-extra/src/extra/math/arctan.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct MathArcTan; impl Command for MathArcTan { fn name(&self) -> &str { "math arctan" } fn signature(&self) -> Signature { Signature::build("math arctan") .switch("degrees", "Return degrees instead of radians", Some('d')) .input_output_types(vec![ (Type::Number, Type::Float), ( Type::List(Box::new(Type::Number)), Type::List(Box::new(Type::Float)), ), ]) .allow_variants_without_examples(true) .category(Category::Math) } fn description(&self) -> &str { "Returns the arctangent of the number." } fn search_terms(&self) -> Vec<&str> { vec!["trigonometry", "inverse"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let use_degrees = call.has_flag(engine_state, stack, "degrees")?; // This doesn't match explicit nulls if let PipelineData::Empty = input { return Err(ShellError::PipelineEmpty { dst_span: head }); } input.map( move |value| operate(value, head, use_degrees), engine_state.signals(), ) } fn examples(&self) -> Vec<Example<'_>> { let pi = std::f64::consts::PI; vec![ Example { description: "Get the arctangent of 1", example: "1 | math arctan", result: Some(Value::test_float(pi / 4.0f64)), }, Example { description: "Get the arctangent of -1 in degrees", example: "-1 | math arctan --degrees", result: Some(Value::test_float(-45.0)), }, ] } } fn operate(value: Value, head: Span, use_degrees: bool) -> Value { match value { numeric @ (Value::Int { .. } | Value::Float { .. }) => { let span = numeric.span(); let (val, span) = match numeric { Value::Int { val, .. } => (val as f64, span), Value::Float { val, .. } => (val, span), _ => unreachable!(), }; let val = val.atan(); let val = if use_degrees { val.to_degrees() } else { val }; Value::float(val, span) } Value::Error { .. } => value, other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "numeric".into(), wrong_type: other.get_type().to_string(), dst_span: head, src_span: other.span(), }, head, ), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(MathArcTan {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/math/arccos.rs
crates/nu-cmd-extra/src/extra/math/arccos.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct MathArcCos; impl Command for MathArcCos { fn name(&self) -> &str { "math arccos" } fn signature(&self) -> Signature { Signature::build("math arccos") .switch("degrees", "Return degrees instead of radians", Some('d')) .input_output_types(vec![ (Type::Number, Type::Float), ( Type::List(Box::new(Type::Number)), Type::List(Box::new(Type::Float)), ), ]) .allow_variants_without_examples(true) .category(Category::Math) } fn description(&self) -> &str { "Returns the arccosine of the number." } fn search_terms(&self) -> Vec<&str> { vec!["trigonometry", "inverse"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let use_degrees = call.has_flag(engine_state, stack, "degrees")?; // This doesn't match explicit nulls if let PipelineData::Empty = input { return Err(ShellError::PipelineEmpty { dst_span: head }); } input.map( move |value| operate(value, head, use_degrees), engine_state.signals(), ) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Get the arccosine of 1", example: "1 | math arccos", result: Some(Value::test_float(0.0f64)), }, Example { description: "Get the arccosine of -1 in degrees", example: "-1 | math arccos --degrees", result: Some(Value::test_float(180.0)), }, ] } } fn operate(value: Value, head: Span, use_degrees: bool) -> Value { match value { numeric @ (Value::Int { .. } | Value::Float { .. }) => { let span = numeric.span(); let (val, span) = match numeric { Value::Int { val, .. } => (val as f64, span), Value::Float { val, .. } => (val, span), _ => unreachable!(), }; if (-1.0..=1.0).contains(&val) { let val = val.acos(); let val = if use_degrees { val.to_degrees() } else { val }; Value::float(val, span) } else { Value::error( ShellError::UnsupportedInput { msg: "'arccos' undefined for values outside the closed interval [-1, 1]." .into(), input: "value originates from here".into(), msg_span: head, input_span: span, }, span, ) } } Value::Error { .. } => value, other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "numeric".into(), wrong_type: other.get_type().to_string(), dst_span: head, src_span: other.span(), }, head, ), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(MathArcCos {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/math/cosh.rs
crates/nu-cmd-extra/src/extra/math/cosh.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct MathCosH; impl Command for MathCosH { fn name(&self) -> &str { "math cosh" } fn signature(&self) -> Signature { Signature::build("math cosh") .input_output_types(vec![ (Type::Number, Type::Float), ( Type::List(Box::new(Type::Number)), Type::List(Box::new(Type::Float)), ), ]) .allow_variants_without_examples(true) .category(Category::Math) } fn description(&self) -> &str { "Returns the hyperbolic cosine of the number." } fn search_terms(&self) -> Vec<&str> { vec!["trigonometry", "hyperbolic"] } fn run( &self, engine_state: &EngineState, _stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; // This doesn't match explicit nulls if let PipelineData::Empty = input { return Err(ShellError::PipelineEmpty { dst_span: head }); } input.map(move |value| operate(value, head), engine_state.signals()) } fn examples(&self) -> Vec<Example<'_>> { let e = std::f64::consts::E; vec![Example { description: "Apply the hyperbolic cosine to 1", example: "1 | math cosh", result: Some(Value::test_float(((e * e) + 1.0) / (2.0 * e))), }] } } fn operate(value: Value, head: Span) -> Value { match value { numeric @ (Value::Int { .. } | Value::Float { .. }) => { let span = numeric.span(); let (val, span) = match numeric { Value::Int { val, .. } => (val as f64, span), Value::Float { val, .. } => (val, span), _ => unreachable!(), }; Value::float(val.cosh(), span) } Value::Error { .. } => value, other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "numeric".into(), wrong_type: other.get_type().to_string(), dst_span: head, src_span: other.span(), }, head, ), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(MathCosH {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/math/tanh.rs
crates/nu-cmd-extra/src/extra/math/tanh.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct MathTanH; impl Command for MathTanH { fn name(&self) -> &str { "math tanh" } fn signature(&self) -> Signature { Signature::build("math tanh") .input_output_types(vec![ (Type::Number, Type::Float), ( Type::List(Box::new(Type::Number)), Type::List(Box::new(Type::Float)), ), ]) .allow_variants_without_examples(true) .category(Category::Math) } fn description(&self) -> &str { "Returns the hyperbolic tangent of the number." } fn search_terms(&self) -> Vec<&str> { vec!["trigonometry", "hyperbolic"] } fn run( &self, engine_state: &EngineState, _stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; // This doesn't match explicit nulls if let PipelineData::Empty = input { return Err(ShellError::PipelineEmpty { dst_span: head }); } input.map(move |value| operate(value, head), engine_state.signals()) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Apply the hyperbolic tangent to 10*π", example: "3.141592 * 10 | math tanh | math round --precision 4", result: Some(Value::test_float(1f64)), }] } } fn operate(value: Value, head: Span) -> Value { match value { numeric @ (Value::Int { .. } | Value::Float { .. }) => { let span = numeric.span(); let (val, span) = match numeric { Value::Int { val, .. } => (val as f64, span), Value::Float { val, .. } => (val, span), _ => unreachable!(), }; Value::float(val.tanh(), span) } Value::Error { .. } => value, other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "numeric".into(), wrong_type: other.get_type().to_string(), dst_span: head, src_span: other.span(), }, head, ), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(MathTanH {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/math/arctanh.rs
crates/nu-cmd-extra/src/extra/math/arctanh.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct MathArcTanH; impl Command for MathArcTanH { fn name(&self) -> &str { "math arctanh" } fn signature(&self) -> Signature { Signature::build("math arctanh") .input_output_types(vec![ (Type::Number, Type::Float), ( Type::List(Box::new(Type::Number)), Type::List(Box::new(Type::Float)), ), ]) .allow_variants_without_examples(true) .category(Category::Math) } fn description(&self) -> &str { "Returns the inverse of the hyperbolic tangent function." } fn search_terms(&self) -> Vec<&str> { vec!["trigonometry", "inverse", "hyperbolic"] } fn run( &self, engine_state: &EngineState, _stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; // This doesn't match explicit nulls if let PipelineData::Empty = input { return Err(ShellError::PipelineEmpty { dst_span: head }); } input.map(move |value| operate(value, head), engine_state.signals()) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Get the arctanh of 1", example: "1 | math arctanh", result: Some(Value::test_float(f64::INFINITY)), }] } } fn operate(value: Value, head: Span) -> Value { match value { numeric @ (Value::Int { .. } | Value::Float { .. }) => { let span = numeric.span(); let (val, span) = match numeric { Value::Int { val, .. } => (val as f64, span), Value::Float { val, .. } => (val, span), _ => unreachable!(), }; if (-1.0..=1.0).contains(&val) { let val = val.atanh(); Value::float(val, span) } else { Value::error( ShellError::UnsupportedInput { msg: "'arctanh' undefined for values outside the open interval (-1, 1)." .into(), input: "value originates from here".into(), msg_span: head, input_span: span, }, head, ) } } Value::Error { .. } => value, other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "numeric".into(), wrong_type: other.get_type().to_string(), dst_span: head, src_span: other.span(), }, head, ), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(MathArcTanH {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/math/mod.rs
crates/nu-cmd-extra/src/extra/math/mod.rs
mod cos; mod cosh; mod sin; mod sinh; mod tan; mod tanh; mod exp; mod ln; mod arccos; mod arccosh; mod arcsin; mod arcsinh; mod arctan; mod arctanh; pub use cos::MathCos; pub use cosh::MathCosH; pub use sin::MathSin; pub use sinh::MathSinH; pub use tan::MathTan; pub use tanh::MathTanH; pub use exp::MathExp; pub use ln::MathLn; pub use arccos::MathArcCos; pub use arccosh::MathArcCosH; pub use arcsin::MathArcSin; pub use arcsinh::MathArcSinH; pub use arctan::MathArcTan; pub use arctanh::MathArcTanH;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/math/ln.rs
crates/nu-cmd-extra/src/extra/math/ln.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct MathLn; impl Command for MathLn { fn name(&self) -> &str { "math ln" } fn signature(&self) -> Signature { Signature::build("math ln") .input_output_types(vec![ (Type::Number, Type::Float), ( Type::List(Box::new(Type::Number)), Type::List(Box::new(Type::Float)), ), ]) .allow_variants_without_examples(true) .category(Category::Math) } fn description(&self) -> &str { "Returns the natural logarithm. Base: (math e)." } fn search_terms(&self) -> Vec<&str> { vec!["natural", "logarithm", "inverse", "euler"] } fn run( &self, engine_state: &EngineState, _stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; // This doesn't match explicit nulls if let PipelineData::Empty = input { return Err(ShellError::PipelineEmpty { dst_span: head }); } input.map(move |value| operate(value, head), engine_state.signals()) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Get the natural logarithm of e", example: "2.7182818 | math ln | math round --precision 4", result: Some(Value::test_float(1.0f64)), }] } } fn operate(value: Value, head: Span) -> Value { match value { numeric @ (Value::Int { .. } | Value::Float { .. }) => { let span = numeric.span(); let (val, span) = match numeric { Value::Int { val, .. } => (val as f64, span), Value::Float { val, .. } => (val, span), _ => unreachable!(), }; if val > 0.0 { let val = val.ln(); Value::float(val, span) } else { Value::error( ShellError::UnsupportedInput { msg: "'ln' undefined for values outside the open interval (0, Inf).".into(), input: "value originates from here".into(), msg_span: head, input_span: span, }, span, ) } } Value::Error { .. } => value, other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "numeric".into(), wrong_type: other.get_type().to_string(), dst_span: head, src_span: other.span(), }, head, ), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(MathLn {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/math/sin.rs
crates/nu-cmd-extra/src/extra/math/sin.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct MathSin; impl Command for MathSin { fn name(&self) -> &str { "math sin" } fn signature(&self) -> Signature { Signature::build("math sin") .switch("degrees", "Use degrees instead of radians", Some('d')) .input_output_types(vec![ (Type::Number, Type::Float), ( Type::List(Box::new(Type::Number)), Type::List(Box::new(Type::Float)), ), ]) .category(Category::Math) } fn description(&self) -> &str { "Returns the sine of the number." } fn search_terms(&self) -> Vec<&str> { vec!["trigonometry"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let use_degrees = call.has_flag(engine_state, stack, "degrees")?; // This doesn't match explicit nulls if let PipelineData::Empty = input { return Err(ShellError::PipelineEmpty { dst_span: head }); } input.map( move |value| operate(value, head, use_degrees), engine_state.signals(), ) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Apply the sine to π/2", example: "3.141592 / 2 | math sin | math round --precision 4", result: Some(Value::test_float(1f64)), }, Example { description: "Apply the sine to a list of angles in degrees", example: "[0 90 180 270 360] | math sin -d | math round --precision 4", result: Some(Value::list( vec![ Value::test_float(0f64), Value::test_float(1f64), Value::test_float(0f64), Value::test_float(-1f64), Value::test_float(0f64), ], Span::test_data(), )), }, ] } } fn operate(value: Value, head: Span, use_degrees: bool) -> Value { match value { numeric @ (Value::Int { .. } | Value::Float { .. }) => { let span = numeric.span(); let (val, span) = match numeric { Value::Int { val, .. } => (val as f64, span), Value::Float { val, .. } => (val, span), _ => unreachable!(), }; let val = if use_degrees { val.to_radians() } else { val }; Value::float(val.sin(), span) } Value::Error { .. } => value, other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "numeric".into(), wrong_type: other.get_type().to_string(), dst_span: head, src_span: other.span(), }, head, ), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(MathSin {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/math/arcsinh.rs
crates/nu-cmd-extra/src/extra/math/arcsinh.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct MathArcSinH; impl Command for MathArcSinH { fn name(&self) -> &str { "math arcsinh" } fn signature(&self) -> Signature { Signature::build("math arcsinh") .input_output_types(vec![ (Type::Number, Type::Float), ( Type::List(Box::new(Type::Number)), Type::List(Box::new(Type::Float)), ), ]) .allow_variants_without_examples(true) .category(Category::Math) } fn description(&self) -> &str { "Returns the inverse of the hyperbolic sine function." } fn search_terms(&self) -> Vec<&str> { vec!["trigonometry", "inverse", "hyperbolic"] } fn run( &self, engine_state: &EngineState, _stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; // This doesn't match explicit nulls if let PipelineData::Empty = input { return Err(ShellError::PipelineEmpty { dst_span: head }); } input.map(move |value| operate(value, head), engine_state.signals()) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Get the arcsinh of 0", example: "0 | math arcsinh", result: Some(Value::test_float(0.0f64)), }] } } fn operate(value: Value, head: Span) -> Value { match value { numeric @ (Value::Int { .. } | Value::Float { .. }) => { let span = numeric.span(); let (val, span) = match numeric { Value::Int { val, .. } => (val as f64, span), Value::Float { val, .. } => (val, span), _ => unreachable!(), }; let val = val.asinh(); Value::float(val, span) } Value::Error { .. } => value, other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "numeric".into(), wrong_type: other.get_type().to_string(), dst_span: head, src_span: other.span(), }, head, ), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(MathArcSinH {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/math/cos.rs
crates/nu-cmd-extra/src/extra/math/cos.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct MathCos; impl Command for MathCos { fn name(&self) -> &str { "math cos" } fn signature(&self) -> Signature { Signature::build("math cos") .switch("degrees", "Use degrees instead of radians", Some('d')) .input_output_types(vec![ (Type::Number, Type::Float), ( Type::List(Box::new(Type::Number)), Type::List(Box::new(Type::Float)), ), ]) .category(Category::Math) } fn description(&self) -> &str { "Returns the cosine of the number." } fn search_terms(&self) -> Vec<&str> { vec!["trigonometry"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let use_degrees = call.has_flag(engine_state, stack, "degrees")?; // This doesn't match explicit nulls if let PipelineData::Empty = input { return Err(ShellError::PipelineEmpty { dst_span: head }); } input.map( move |value| operate(value, head, use_degrees), engine_state.signals(), ) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Apply the cosine to π", example: "3.141592 | math cos | math round --precision 4", result: Some(Value::test_float(-1f64)), }, Example { description: "Apply the cosine to a list of angles in degrees", example: "[0 90 180 270 360] | math cos --degrees", result: Some(Value::list( vec![ Value::test_float(1f64), Value::test_float(0f64), Value::test_float(-1f64), Value::test_float(0f64), Value::test_float(1f64), ], Span::test_data(), )), }, ] } } fn operate(value: Value, head: Span, use_degrees: bool) -> Value { match value { numeric @ (Value::Int { .. } | Value::Float { .. }) => { let span = numeric.span(); let (val, span) = match numeric { Value::Int { val, .. } => (val as f64, span), Value::Float { val, .. } => (val, span), _ => unreachable!(), }; let val = if use_degrees { val.to_radians() } else { val }; Value::float(val.cos(), span) } Value::Error { .. } => value, other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "numeric".into(), wrong_type: other.get_type().to_string(), dst_span: head, src_span: other.span(), }, head, ), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(MathCos {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/math/arcsin.rs
crates/nu-cmd-extra/src/extra/math/arcsin.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct MathArcSin; impl Command for MathArcSin { fn name(&self) -> &str { "math arcsin" } fn signature(&self) -> Signature { Signature::build("math arcsin") .switch("degrees", "Return degrees instead of radians", Some('d')) .input_output_types(vec![ (Type::Number, Type::Float), ( Type::List(Box::new(Type::Number)), Type::List(Box::new(Type::Float)), ), ]) .allow_variants_without_examples(true) .category(Category::Math) } fn description(&self) -> &str { "Returns the arcsine of the number." } fn search_terms(&self) -> Vec<&str> { vec!["trigonometry", "inverse"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let use_degrees = call.has_flag(engine_state, stack, "degrees")?; // This doesn't match explicit nulls if let PipelineData::Empty = input { return Err(ShellError::PipelineEmpty { dst_span: head }); } input.map( move |value| operate(value, head, use_degrees), engine_state.signals(), ) } fn examples(&self) -> Vec<Example<'_>> { let pi = std::f64::consts::PI; vec![ Example { description: "Get the arcsine of 1", example: "1 | math arcsin", result: Some(Value::test_float(pi / 2.0)), }, Example { description: "Get the arcsine of 1 in degrees", example: "1 | math arcsin --degrees", result: Some(Value::test_float(90.0)), }, ] } } fn operate(value: Value, head: Span, use_degrees: bool) -> Value { match value { numeric @ (Value::Int { .. } | Value::Float { .. }) => { let span = numeric.span(); let (val, span) = match numeric { Value::Int { val, .. } => (val as f64, span), Value::Float { val, .. } => (val, span), _ => unreachable!(), }; if (-1.0..=1.0).contains(&val) { let val = val.asin(); let val = if use_degrees { val.to_degrees() } else { val }; Value::float(val, span) } else { Value::error( ShellError::UnsupportedInput { msg: "'arcsin' undefined for values outside the closed interval [-1, 1]." .into(), input: "value originates from here".into(), msg_span: head, input_span: span, }, span, ) } } Value::Error { .. } => value, other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "numeric".into(), wrong_type: other.get_type().to_string(), dst_span: head, src_span: other.span(), }, head, ), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(MathArcSin {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/math/tan.rs
crates/nu-cmd-extra/src/extra/math/tan.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct MathTan; impl Command for MathTan { fn name(&self) -> &str { "math tan" } fn signature(&self) -> Signature { Signature::build("math tan") .switch("degrees", "Use degrees instead of radians", Some('d')) .input_output_types(vec![ (Type::Number, Type::Float), ( Type::List(Box::new(Type::Number)), Type::List(Box::new(Type::Float)), ), ]) .category(Category::Math) } fn description(&self) -> &str { "Returns the tangent of the number." } fn search_terms(&self) -> Vec<&str> { vec!["trigonometry"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let use_degrees = call.has_flag(engine_state, stack, "degrees")?; // This doesn't match explicit nulls if let PipelineData::Empty = input { return Err(ShellError::PipelineEmpty { dst_span: head }); } input.map( move |value| operate(value, head, use_degrees), engine_state.signals(), ) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Apply the tangent to π/4", example: "3.141592 / 4 | math tan | math round --precision 4", result: Some(Value::test_float(1f64)), }, Example { description: "Apply the tangent to a list of angles in degrees", example: "[-45 0 45] | math tan --degrees", result: Some(Value::list( vec![ Value::test_float(-1f64), Value::test_float(0f64), Value::test_float(1f64), ], Span::test_data(), )), }, ] } } fn operate(value: Value, head: Span, use_degrees: bool) -> Value { match value { numeric @ (Value::Int { .. } | Value::Float { .. }) => { let span = numeric.span(); let (val, span) = match numeric { Value::Int { val, .. } => (val as f64, span), Value::Float { val, .. } => (val, span), _ => unreachable!(), }; let val = if use_degrees { val.to_radians() } else { val }; Value::float(val.tan(), span) } Value::Error { .. } => value, other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "numeric".into(), wrong_type: other.get_type().to_string(), dst_span: head, src_span: other.span(), }, head, ), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(MathTan {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/math/exp.rs
crates/nu-cmd-extra/src/extra/math/exp.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct MathExp; impl Command for MathExp { fn name(&self) -> &str { "math exp" } fn signature(&self) -> Signature { Signature::build("math exp") .input_output_types(vec![ (Type::Number, Type::Float), ( Type::List(Box::new(Type::Number)), Type::List(Box::new(Type::Float)), ), ]) .allow_variants_without_examples(true) .category(Category::Math) } fn description(&self) -> &str { "Returns e raised to the power of x." } fn search_terms(&self) -> Vec<&str> { vec!["exponential", "exponentiation", "euler"] } fn run( &self, engine_state: &EngineState, _stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; // This doesn't match explicit nulls if let PipelineData::Empty = input { return Err(ShellError::PipelineEmpty { dst_span: head }); } input.map(move |value| operate(value, head), engine_state.signals()) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Get e raised to the power of zero", example: "0 | math exp", result: Some(Value::test_float(1.0f64)), }, Example { description: "Get e (same as 'math e')", example: "1 | math exp", result: Some(Value::test_float(1.0f64.exp())), }, ] } } fn operate(value: Value, head: Span) -> Value { match value { numeric @ (Value::Int { .. } | Value::Float { .. }) => { let span = numeric.span(); let (val, span) = match numeric { Value::Int { val, .. } => (val as f64, span), Value::Float { val, .. } => (val, span), _ => unreachable!(), }; Value::float(val.exp(), span) } Value::Error { .. } => value, other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "numeric".into(), wrong_type: other.get_type().to_string(), dst_span: head, src_span: other.span(), }, head, ), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(MathExp {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/strings/mod.rs
crates/nu-cmd-extra/src/extra/strings/mod.rs
pub(crate) mod format; pub(crate) mod str_;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/strings/str_/mod.rs
crates/nu-cmd-extra/src/extra/strings/str_/mod.rs
pub(crate) mod case;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/strings/str_/case/kebab_case.rs
crates/nu-cmd-extra/src/extra/strings/str_/case/kebab_case.rs
use super::operate; use heck::ToKebabCase; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct StrKebabCase; impl Command for StrKebabCase { fn name(&self) -> &str { "str kebab-case" } fn signature(&self) -> Signature { Signature::build("str kebab-case") .input_output_types(vec![ (Type::String, Type::String), (Type::table(), Type::table()), (Type::record(), Type::record()), ( Type::List(Box::new(Type::String)), Type::List(Box::new(Type::String)), ), ]) .allow_variants_without_examples(true) .rest( "rest", SyntaxShape::CellPath, "For a data structure input, convert strings at the given cell paths.", ) .category(Category::Strings) } fn description(&self) -> &str { "Convert a string to kebab-case." } fn search_terms(&self) -> Vec<&str> { vec!["convert", "style", "hyphens", "convention"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { operate( engine_state, stack, call, input, &ToKebabCase::to_kebab_case, ) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "convert a string to kebab-case", example: "'NuShell' | str kebab-case", result: Some(Value::test_string("nu-shell")), }, Example { description: "convert a string to kebab-case", example: "'thisIsTheFirstCase' | str kebab-case", result: Some(Value::test_string("this-is-the-first-case")), }, Example { description: "convert a string to kebab-case", example: "'THIS_IS_THE_SECOND_CASE' | str kebab-case", result: Some(Value::test_string("this-is-the-second-case")), }, Example { description: "convert a column from a table to kebab-case", example: r#"[[lang, gems]; [nuTest, 100]] | str kebab-case lang"#, result: Some(Value::test_list(vec![Value::test_record(record! { "lang" => Value::test_string("nu-test"), "gems" => Value::test_int(100), })])), }, ] } } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(StrKebabCase {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/strings/str_/case/pascal_case.rs
crates/nu-cmd-extra/src/extra/strings/str_/case/pascal_case.rs
use super::operate; use heck::ToUpperCamelCase; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct StrPascalCase; impl Command for StrPascalCase { fn name(&self) -> &str { "str pascal-case" } fn signature(&self) -> Signature { Signature::build("str pascal-case") .input_output_types(vec![ (Type::String, Type::String), (Type::table(), Type::table()), (Type::record(), Type::record()), ( Type::List(Box::new(Type::String)), Type::List(Box::new(Type::String)), ), ]) .allow_variants_without_examples(true) .rest( "rest", SyntaxShape::CellPath, "For a data structure input, convert strings at the given cell paths.", ) .category(Category::Strings) } fn description(&self) -> &str { "Convert a string to PascalCase." } fn search_terms(&self) -> Vec<&str> { vec!["convert", "style", "caps", "upper", "convention"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { operate( engine_state, stack, call, input, &ToUpperCamelCase::to_upper_camel_case, ) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "convert a string to PascalCase", example: "'nu-shell' | str pascal-case", result: Some(Value::test_string("NuShell")), }, Example { description: "convert a string to PascalCase", example: "'this-is-the-first-case' | str pascal-case", result: Some(Value::test_string("ThisIsTheFirstCase")), }, Example { description: "convert a string to PascalCase", example: "'this_is_the_second_case' | str pascal-case", result: Some(Value::test_string("ThisIsTheSecondCase")), }, Example { description: "convert a column from a table to PascalCase", example: r#"[[lang, gems]; [nu_test, 100]] | str pascal-case lang"#, result: Some(Value::test_list(vec![Value::test_record(record! { "lang" => Value::test_string("NuTest"), "gems" => Value::test_int(100), })])), }, ] } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(StrPascalCase {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/strings/str_/case/mod.rs
crates/nu-cmd-extra/src/extra/strings/str_/case/mod.rs
mod camel_case; mod kebab_case; mod pascal_case; mod screaming_snake_case; mod snake_case; mod str_; mod title_case; pub use camel_case::StrCamelCase; pub use kebab_case::StrKebabCase; pub use pascal_case::StrPascalCase; pub use screaming_snake_case::StrScreamingSnakeCase; pub use snake_case::StrSnakeCase; pub use str_::Str; pub use title_case::StrTitleCase; use nu_cmd_base::input_handler::{CmdArgument, operate as general_operate}; use nu_engine::command_prelude::*; struct Arguments<F: Fn(&str) -> String + Send + Sync + 'static> { case_operation: &'static F, cell_paths: Option<Vec<CellPath>>, } impl<F: Fn(&str) -> String + Send + Sync + 'static> CmdArgument for Arguments<F> { fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> { self.cell_paths.take() } } pub fn operate<F>( engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, case_operation: &'static F, ) -> Result<PipelineData, ShellError> where F: Fn(&str) -> String + Send + Sync + 'static, { let cell_paths: Vec<CellPath> = call.rest(engine_state, stack, 0)?; let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths); let args = Arguments { case_operation, cell_paths, }; general_operate(action, args, input, call.head, engine_state.signals()) } fn action<F>(input: &Value, args: &Arguments<F>, head: Span) -> Value where F: Fn(&str) -> String + Send + Sync + 'static, { let case_operation = args.case_operation; match input { Value::String { val, .. } => Value::string(case_operation(val), head), Value::Error { .. } => input.clone(), _ => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "string".into(), wrong_type: input.get_type().to_string(), dst_span: head, src_span: input.span(), }, head, ), } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/strings/str_/case/str_.rs
crates/nu-cmd-extra/src/extra/strings/str_/case/str_.rs
use nu_engine::{command_prelude::*, get_full_help}; #[derive(Clone)] pub struct Str; impl Command for Str { fn name(&self) -> &str { "str" } fn signature(&self) -> Signature { Signature::build("str") .category(Category::Strings) .input_output_types(vec![(Type::Nothing, Type::String)]) } fn description(&self) -> &str { "Various commands for working with string data." } fn extra_description(&self) -> &str { "You must use one of the following subcommands. Using this command as-is will only produce this help message." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { Ok(Value::string(get_full_help(self, engine_state, stack), call.head).into_pipeline_data()) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/strings/str_/case/camel_case.rs
crates/nu-cmd-extra/src/extra/strings/str_/case/camel_case.rs
use super::operate; use heck::ToLowerCamelCase; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct StrCamelCase; impl Command for StrCamelCase { fn name(&self) -> &str { "str camel-case" } fn signature(&self) -> Signature { Signature::build("str camel-case") .input_output_types(vec![ (Type::String, Type::String), ( Type::List(Box::new(Type::String)), Type::List(Box::new(Type::String)), ), (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .allow_variants_without_examples(true) .rest( "rest", SyntaxShape::CellPath, "For a data structure input, convert strings at the given cell paths.", ) .category(Category::Strings) } fn description(&self) -> &str { "Convert a string to camelCase." } fn search_terms(&self) -> Vec<&str> { vec!["convert", "style", "caps", "convention"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { operate( engine_state, stack, call, input, &ToLowerCamelCase::to_lower_camel_case, ) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "convert a string to camelCase", example: " 'NuShell' | str camel-case", result: Some(Value::test_string("nuShell")), }, Example { description: "convert a string to camelCase", example: "'this-is-the-first-case' | str camel-case", result: Some(Value::test_string("thisIsTheFirstCase")), }, Example { description: "convert a string to camelCase", example: " 'this_is_the_second_case' | str camel-case", result: Some(Value::test_string("thisIsTheSecondCase")), }, Example { description: "convert a column from a table to camelCase", example: r#"[[lang, gems]; [nu_test, 100]] | str camel-case lang"#, result: Some(Value::test_list(vec![Value::test_record(record! { "lang" => Value::test_string("nuTest"), "gems" => Value::test_int(100), })])), }, ] } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(StrCamelCase {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/strings/str_/case/screaming_snake_case.rs
crates/nu-cmd-extra/src/extra/strings/str_/case/screaming_snake_case.rs
use super::operate; use heck::ToShoutySnakeCase; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct StrScreamingSnakeCase; impl Command for StrScreamingSnakeCase { fn name(&self) -> &str { "str screaming-snake-case" } fn signature(&self) -> Signature { Signature::build("str screaming-snake-case") .input_output_types(vec![ (Type::String, Type::String), ( Type::List(Box::new(Type::String)), Type::List(Box::new(Type::String)), ), (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .allow_variants_without_examples(true) .rest( "rest", SyntaxShape::CellPath, "For a data structure input, convert strings at the given cell paths.", ) .category(Category::Strings) } fn description(&self) -> &str { "Convert a string to SCREAMING_SNAKE_CASE." } fn search_terms(&self) -> Vec<&str> { vec!["convert", "style", "underscore", "convention"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { operate( engine_state, stack, call, input, &ToShoutySnakeCase::to_shouty_snake_case, ) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "convert a string to SCREAMING_SNAKE_CASE", example: r#" "NuShell" | str screaming-snake-case"#, result: Some(Value::test_string("NU_SHELL")), }, Example { description: "convert a string to SCREAMING_SNAKE_CASE", example: r#" "this_is_the_second_case" | str screaming-snake-case"#, result: Some(Value::test_string("THIS_IS_THE_SECOND_CASE")), }, Example { description: "convert a string to SCREAMING_SNAKE_CASE", example: r#""this-is-the-first-case" | str screaming-snake-case"#, result: Some(Value::test_string("THIS_IS_THE_FIRST_CASE")), }, Example { description: "convert a column from a table to SCREAMING_SNAKE_CASE", example: r#"[[lang, gems]; [nu_test, 100]] | str screaming-snake-case lang"#, result: Some(Value::test_list(vec![Value::test_record(record! { "lang" => Value::test_string("NU_TEST"), "gems" => Value::test_int(100), })])), }, ] } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(StrScreamingSnakeCase {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/strings/str_/case/title_case.rs
crates/nu-cmd-extra/src/extra/strings/str_/case/title_case.rs
use super::operate; use heck::ToTitleCase; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct StrTitleCase; impl Command for StrTitleCase { fn name(&self) -> &str { "str title-case" } fn signature(&self) -> Signature { Signature::build("str title-case") .input_output_types(vec![ (Type::String, Type::String), ( Type::List(Box::new(Type::String)), Type::List(Box::new(Type::String)), ), (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .allow_variants_without_examples(true) .rest( "rest", SyntaxShape::CellPath, "For a data structure input, convert strings at the given cell paths.", ) .category(Category::Strings) } fn description(&self) -> &str { "Convert a string to Title Case." } fn search_terms(&self) -> Vec<&str> { vec!["convert", "style", "convention"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { operate( engine_state, stack, call, input, &ToTitleCase::to_title_case, ) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "convert a string to Title Case", example: "'nu-shell' | str title-case", result: Some(Value::test_string("Nu Shell")), }, Example { description: "convert a string to Title Case", example: "'this is a test case' | str title-case", result: Some(Value::test_string("This Is A Test Case")), }, Example { description: "convert a column from a table to Title Case", example: r#"[[title, count]; ['nu test', 100]] | str title-case title"#, result: Some(Value::test_list(vec![Value::test_record(record! { "title" => Value::test_string("Nu Test"), "count" => Value::test_int(100), })])), }, ] } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(StrTitleCase {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/strings/str_/case/snake_case.rs
crates/nu-cmd-extra/src/extra/strings/str_/case/snake_case.rs
use super::operate; use heck::ToSnakeCase; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct StrSnakeCase; impl Command for StrSnakeCase { fn name(&self) -> &str { "str snake-case" } fn signature(&self) -> Signature { Signature::build("str snake-case") .input_output_types(vec![ (Type::String, Type::String), ( Type::List(Box::new(Type::String)), Type::List(Box::new(Type::String)), ), (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .allow_variants_without_examples(true) .rest( "rest", SyntaxShape::CellPath, "For a data structure input, convert strings at the given cell paths.", ) .category(Category::Strings) } fn description(&self) -> &str { "Convert a string to snake_case." } fn search_terms(&self) -> Vec<&str> { vec!["convert", "style", "underscore", "lower", "convention"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { operate( engine_state, stack, call, input, &ToSnakeCase::to_snake_case, ) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "convert a string to snake_case", example: r#" "NuShell" | str snake-case"#, result: Some(Value::test_string("nu_shell")), }, Example { description: "convert a string to snake_case", example: r#" "this_is_the_second_case" | str snake-case"#, result: Some(Value::test_string("this_is_the_second_case")), }, Example { description: "convert a string to snake_case", example: r#""this-is-the-first-case" | str snake-case"#, result: Some(Value::test_string("this_is_the_first_case")), }, Example { description: "convert a column from a table to snake_case", example: r#"[[lang, gems]; [nuTest, 100]] | str snake-case lang"#, result: Some(Value::test_list(vec![Value::test_record(record! { "lang" => Value::test_string("nu_test"), "gems" => Value::test_int(100), })])), }, ] } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(StrSnakeCase {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/strings/encode_decode/decode_hex.rs
crates/nu-cmd-extra/src/extra/strings/encode_decode/decode_hex.rs
use super::hex::{ActionType, operate}; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct DecodeHex; impl Command for DecodeHex { fn name(&self) -> &str { "decode hex" } fn signature(&self) -> Signature { Signature::build("decode hex") .input_output_types(vec![ (Type::String, Type::Binary), ( Type::List(Box::new(Type::String)), Type::List(Box::new(Type::Binary)), ), (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .allow_variants_without_examples(true) .rest( "rest", SyntaxShape::CellPath, "For a data structure input, decode data at the given cell paths", ) .category(Category::Formats) } fn description(&self) -> &str { "Hex decode a value." } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Hex decode a value and output as binary", example: "'0102030A0a0B' | decode hex", result: Some(Value::binary( [0x01, 0x02, 0x03, 0x0A, 0x0A, 0x0B], Span::test_data(), )), }, Example { description: "Whitespaces are allowed to be between hex digits", example: "'01 02 03 0A 0a 0B' | decode hex", result: Some(Value::binary( [0x01, 0x02, 0x03, 0x0A, 0x0A, 0x0B], Span::test_data(), )), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { operate(ActionType::Decode, engine_state, stack, call, input) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { crate::test_examples(DecodeHex) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/strings/encode_decode/encode_hex.rs
crates/nu-cmd-extra/src/extra/strings/encode_decode/encode_hex.rs
use super::hex::{ActionType, operate}; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct EncodeHex; impl Command for EncodeHex { fn name(&self) -> &str { "encode hex" } fn signature(&self) -> Signature { Signature::build("encode hex") .input_output_types(vec![ (Type::Binary, Type::String), ( Type::List(Box::new(Type::Binary)), Type::List(Box::new(Type::String)), ), (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .allow_variants_without_examples(true) .rest( "rest", SyntaxShape::CellPath, "For a data structure input, encode data at the given cell paths", ) .category(Category::Formats) } fn description(&self) -> &str { "Encode a binary value using hex." } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Encode binary data", example: "0x[09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0] | encode hex", result: Some(Value::test_string("09F911029D74E35BD84156C5635688C0")), }] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { operate(ActionType::Encode, engine_state, stack, call, input) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { crate::test_examples(EncodeHex) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/strings/format/command.rs
crates/nu-cmd-extra/src/extra/strings/format/command.rs
use itertools::Itertools; use nu_engine::command_prelude::*; use nu_protocol::{Config, ListStream, ast::PathMember, casing::Casing}; #[derive(Clone)] pub struct FormatPattern; impl Command for FormatPattern { fn name(&self) -> &str { "format pattern" } fn signature(&self) -> Signature { Signature::build("format pattern") .input_output_types(vec![ (Type::table(), Type::List(Box::new(Type::String))), (Type::record(), Type::Any), ]) .required( "pattern", SyntaxShape::String, "The pattern to output. e.g.) \"{foo}: {bar}\".", ) .allow_variants_without_examples(true) .category(Category::Strings) } fn description(&self) -> &str { "Format columns into a string using a simple pattern." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let pattern: Spanned<String> = call.req(engine_state, stack, 0)?; let input_val = input.into_value(call.head)?; let ops = extract_formatting_operations(pattern, call.head)?; let config = stack.get_config(engine_state); format(input_val, &ops, engine_state, &config, call.head) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Print filenames with their sizes", example: "ls | format pattern '{name}: {size}'", result: None, }, Example { description: "Print elements from some columns of a table", example: "[[col1, col2]; [v1, v2] [v3, v4]] | format pattern '{col2}'", result: Some(Value::test_list(vec![ Value::test_string("v2"), Value::test_string("v4"), ])), }, Example { description: "Escape braces by repeating them", example: r#"{start: 3, end: 5} | format pattern 'if {start} < {end} {{ "correct" }} else {{ "incorrect" }}'"#, result: Some(Value::test_string( r#"if 3 < 5 { "correct" } else { "incorrect" }"#, )), }, ] } } // NOTE: The reason to split {column1.column2} and {$it.column1.column2}: // for {column1.column2}, we just need to follow given record or list. // for {$it.column1.column2} or {$variable}, we need to manually evaluate the expression. // // Have thought about converting from {column1.column2} to {$it.column1.column2}, but that // will extend input relative span, finally make `nu` panic out with message: span missing in file // contents cache. #[derive(Debug)] enum FormatOperation { FixedText(String), // raw input is something like {column1.column2} ValueFromColumn { content: String, span: Option<Span> }, } impl FormatOperation { fn update_span(mut self, f: impl FnOnce(Option<Span>) -> Option<Span>) -> Self { if let FormatOperation::ValueFromColumn { span, .. } = &mut self { *span = f(*span); } self } } /// Given a pattern that is fed into the Format command, we can process it and subdivide it /// in two kind of operations. /// FormatOperation::FixedText contains a portion of the pattern that has to be placed /// there without any further processing. /// FormatOperation::ValueFromColumn contains the name of a column whose values will be /// formatted according to the input pattern. /// "$it.column1.column2" or "$variable" fn extract_formatting_operations( input: Spanned<String>, call_head: Span, ) -> Result<Vec<FormatOperation>, ShellError> { let Spanned { item: pattern, span: pattern_span, } = input; // To have proper spans for the extracted operations, we need the span of the pattern string. // Specifically we need the *string content*, without any surrounding quotes. // // NOTE: This implementation can't accurately derive spans for strings containing escape // sequences ("\n", "\t", "\u{3bd}", ...). I don't think we can without parser support. // NOTE: Pattern strings provided with variables are also problematic. The spans we get for // arguments are from the call site, we can't get the original span of a value passed as a // variable. let pattern_span = { // // .----------span len: 21 // | .--string len: 12 // | | delta: 9 // .-+-----|-----------. // | .--+-------. | // r###'hello {user}'### // let delta = pattern_span.len() - pattern.len(); // might be `r'foo'` or `$'foo'` // either 1 or 0 let str_prefix_len = delta % 2; // // r###'hello {user}'### // ^^^^ let span_str_start_delta = delta / 2 + str_prefix_len; pattern_span.subspan(span_str_start_delta, span_str_start_delta + pattern.len()) }; let mut is_fixed = true; let ops = pattern.char_indices().peekable().batching(move |it| { let start_index = it.peek()?.0; let mut buf = String::new(); while let Some((index, ch)) = it.next() { match ch { '{' if is_fixed => { if it.next_if(|(_, next_ch)| *next_ch == '{').is_some() { buf.push(ch); } else { is_fixed = false; return Some(Ok(FormatOperation::FixedText(buf))); }; } '}' => { if is_fixed { if it.next_if(|(_, next_ch)| *next_ch == '}').is_some() { buf.push(ch); } else { return Some(Err(())); } } else { is_fixed = true; return Some(Ok(FormatOperation::ValueFromColumn { content: buf, // span is relative to `pattern` span: Some(Span::new(start_index, index)), })); } } _ => { buf.push(ch); } } } if is_fixed { Some(std::mem::take(&mut buf)) .filter(|buf| !buf.is_empty()) .map(FormatOperation::FixedText) .map(Ok) } else { Some(Err(())) } }); let adjust_span = move |col_span: Span| -> Option<Span> { pattern_span?.subspan(col_span.start, col_span.end) }; let make_delimiter_error = move |_| ShellError::DelimiterError { msg: "there are unmatched curly braces".to_string(), span: call_head, }; let make_removed_functionality_error = |span: Span| ShellError::GenericError { error: "Removed functionality".into(), msg: "The ability to use variables ($it) in `format pattern` has been removed.".into(), span: Some(span), help: Some("You can use other formatting options, such as string interpolation.".into()), inner: vec![], }; ops.map(|res_op| { res_op .map(|op| op.update_span(|col_span| col_span.and_then(adjust_span))) .map_err(make_delimiter_error) .and_then(|op| match op { FormatOperation::ValueFromColumn { content, span } if content.starts_with('$') => { Err(make_removed_functionality_error(span.unwrap_or(call_head))) } op => Ok(op), }) }) .collect() } /// Format the incoming PipelineData according to the pattern fn format( input_data: Value, format_operations: &[FormatOperation], engine_state: &EngineState, config: &Config, head_span: Span, ) -> Result<PipelineData, ShellError> { let data_as_value = input_data; // We can only handle a Record or a List of Records match data_as_value { Value::Record { .. } => { match format_record(format_operations, &data_as_value, config, head_span) { Ok(value) => Ok(PipelineData::value(Value::string(value, head_span), None)), Err(value) => Err(value), } } Value::List { vals, .. } => { let mut list = vec![]; for val in vals.iter() { match val { Value::Record { .. } => { match format_record(format_operations, val, config, head_span) { Ok(value) => { list.push(Value::string(value, head_span)); } Err(value) => { return Err(value); } } } Value::Error { error, .. } => return Err(*error.clone()), _ => { return Err(ShellError::OnlySupportsThisInputType { exp_input_type: "record".to_string(), wrong_type: val.get_type().to_string(), dst_span: head_span, src_span: val.span(), }); } } } Ok(ListStream::new(list.into_iter(), head_span, engine_state.signals().clone()).into()) } // Unwrapping this ShellError is a bit unfortunate. // Ideally, its Span would be preserved. Value::Error { error, .. } => Err(*error), _ => Err(ShellError::OnlySupportsThisInputType { exp_input_type: "record".to_string(), wrong_type: data_as_value.get_type().to_string(), dst_span: head_span, src_span: data_as_value.span(), }), } } fn format_record( format_operations: &[FormatOperation], data_as_value: &Value, config: &Config, head_span: Span, ) -> Result<String, ShellError> { let mut output = String::new(); for op in format_operations { match op { FormatOperation::FixedText(s) => output.push_str(s.as_str()), FormatOperation::ValueFromColumn { content: col_name, span, } => { // path member should split by '.' to handle for nested structure. let path_members: Vec<PathMember> = col_name .split('.') .map(|path| PathMember::String { val: path.to_string(), span: span.unwrap_or(head_span), optional: false, casing: Casing::Sensitive, }) .collect(); let expanded_string = data_as_value .follow_cell_path(&path_members)? .to_expanded_string(", ", config); output.push_str(expanded_string.as_str()) } } } Ok(output) } #[cfg(test)] mod test { #[test] fn test_examples() { use super::FormatPattern; use crate::test_examples; test_examples(FormatPattern {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/strings/format/number.rs
crates/nu-cmd-extra/src/extra/strings/format/number.rs
use nu_cmd_base::input_handler::{CellPathOnlyArgs, operate}; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct FormatNumber; impl Command for FormatNumber { fn name(&self) -> &str { "format number" } fn description(&self) -> &str { "Format a number." } fn signature(&self) -> nu_protocol::Signature { Signature::build("format number") .input_output_types(vec![(Type::Number, Type::record())]) .switch( "no-prefix", "don't include the binary, hex or octal prefixes", Some('n'), ) .category(Category::Conversions) } fn search_terms(&self) -> Vec<&str> { vec!["display", "render", "fmt"] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Get a record containing multiple formats for the number 42", example: "42 | format number", result: Some(Value::test_record(record! { "debug" => Value::test_string("42"), "display" => Value::test_string("42"), "binary" => Value::test_string("0b101010"), "lowerexp" => Value::test_string("4.2e1"), "upperexp" => Value::test_string("4.2E1"), "lowerhex" => Value::test_string("0x2a"), "upperhex" => Value::test_string("0x2A"), "octal" => Value::test_string("0o52"), })), }, Example { description: "Format float without prefixes", example: "3.14 | format number --no-prefix", result: Some(Value::test_record(record! { "debug" => Value::test_string("3.14"), "display" => Value::test_string("3.14"), "binary" => Value::test_string("100000000001001000111101011100001010001111010111000010100011111"), "lowerexp" => Value::test_string("3.14e0"), "upperexp" => Value::test_string("3.14E0"), "lowerhex" => Value::test_string("40091eb851eb851f"), "upperhex" => Value::test_string("40091EB851EB851F"), "octal" => Value::test_string("400110753412172702437"), })), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { format_number(engine_state, stack, call, input) } } pub(crate) fn format_number( engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let cell_paths: Vec<CellPath> = call.rest(engine_state, stack, 0)?; let args = CellPathOnlyArgs::from(cell_paths); if call.has_flag(engine_state, stack, "no-prefix")? { operate( action_no_prefix, args, input, call.head, engine_state.signals(), ) } else { operate(action, args, input, call.head, engine_state.signals()) } } fn action(input: &Value, _args: &CellPathOnlyArgs, span: Span) -> Value { match input { Value::Float { val, .. } => format_f64(*val, false, span), Value::Int { val, .. } => format_i64(*val, false, span), Value::Filesize { val, .. } => format_i64(val.get(), false, span), // Propagate errors by explicitly matching them before the final case. Value::Error { .. } => input.clone(), other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "float, int, or filesize".into(), wrong_type: other.get_type().to_string(), dst_span: span, src_span: other.span(), }, span, ), } } fn action_no_prefix(input: &Value, _args: &CellPathOnlyArgs, span: Span) -> Value { match input { Value::Float { val, .. } => format_f64(*val, true, span), Value::Int { val, .. } => format_i64(*val, true, span), Value::Filesize { val, .. } => format_i64(val.get(), true, span), // Propagate errors by explicitly matching them before the final case. Value::Error { .. } => input.clone(), other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "float, int, or filesize".into(), wrong_type: other.get_type().to_string(), dst_span: span, src_span: other.span(), }, span, ), } } fn format_i64(num: i64, no_prefix: bool, span: Span) -> Value { Value::record( record! { "debug" => Value::string(format!("{num:#?}"), span), "display" => Value::string(format!("{num}"), span), "binary" => Value::string( if no_prefix { format!("{num:b}") } else { format!("{num:#b}") }, span, ), "lowerexp" => Value::string(format!("{num:#e}"), span), "upperexp" => Value::string(format!("{num:#E}"), span), "lowerhex" => Value::string( if no_prefix { format!("{num:x}") } else { format!("{num:#x}") }, span, ), "upperhex" => Value::string( if no_prefix { format!("{num:X}") } else { format!("{num:#X}") }, span, ), "octal" => Value::string( if no_prefix { format!("{num:o}") } else { format!("{num:#o}") }, span, ) }, span, ) } fn format_f64(num: f64, no_prefix: bool, span: Span) -> Value { Value::record( record! { "debug" => Value::string(format!("{num:#?}"), span), "display" => Value::string(format!("{num}"), span), "binary" => Value::string( if no_prefix { format!("{:b}", num.to_bits()) } else { format!("{:#b}", num.to_bits()) }, span, ), "lowerexp" => Value::string(format!("{num:#e}"), span), "upperexp" => Value::string(format!("{num:#E}"), span), "lowerhex" => Value::string( if no_prefix { format!("{:x}", num.to_bits()) } else { format!("{:#x}", num.to_bits()) }, span, ), "upperhex" => Value::string( if no_prefix { format!("{:X}", num.to_bits()) } else { format!("{:#X}", num.to_bits()) }, span, ), "octal" => Value::string( if no_prefix { format!("{:o}", num.to_bits()) } else { format!("{:#o}", num.to_bits()) }, span, ) }, span, ) } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(FormatNumber {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/strings/format/bits.rs
crates/nu-cmd-extra/src/extra/strings/format/bits.rs
use std::io::{self, Read, Write}; use nu_cmd_base::input_handler::{CmdArgument, operate}; use nu_engine::command_prelude::*; use nu_protocol::{Signals, shell_error::io::IoError}; use num_traits::ToPrimitive; struct Arguments { cell_paths: Option<Vec<CellPath>>, little_endian: bool, } impl CmdArgument for Arguments { fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> { self.cell_paths.take() } } #[derive(Clone)] pub struct FormatBits; impl Command for FormatBits { fn name(&self) -> &str { "format bits" } fn signature(&self) -> Signature { Signature::build("format bits") .input_output_types(vec![ (Type::Binary, Type::String), (Type::Int, Type::String), (Type::Filesize, Type::String), (Type::Duration, Type::String), (Type::String, Type::String), (Type::Bool, Type::String), (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .allow_variants_without_examples(true) // TODO: supply exhaustive examples .named( "endian", SyntaxShape::String, "Byte encode endian. Only applies to int, filesize, duration and bool, as well as tables and records of those. Available options: native, little, big(default)", Some('e'), ) .rest( "rest", SyntaxShape::CellPath, "For a data structure input, convert data at the given cell paths.", ) .category(Category::Conversions) } fn description(&self) -> &str { "Convert value to a string of binary data represented by 0 and 1." } fn search_terms(&self) -> Vec<&str> { vec!["convert", "cast", "binary"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { format_bits(engine_state, stack, call, input) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "convert a binary value into a string, padded to 8 places with 0s", example: "0x[1] | format bits", result: Some(Value::string("00000001", Span::test_data())), }, Example { description: "convert an int into a string, padded to 8 places with 0s", example: "1 | format bits", result: Some(Value::string("00000001", Span::test_data())), }, Example { description: "convert an int into a string, padded to 8 places with 0s (big endian)", example: "258 | format bits", result: Some(Value::string("00000001 00000010", Span::test_data())), }, Example { description: "convert an int into a string, padded to 8 places with 0s (little endian)", example: "258 | format bits --endian little", result: Some(Value::string("00000010 00000001", Span::test_data())), }, Example { description: "convert a filesize value into a string, padded to 8 places with 0s", example: "1b | format bits", result: Some(Value::string("00000001", Span::test_data())), }, Example { description: "convert a duration value into a string, padded to 8 places with 0s", example: "1ns | format bits", result: Some(Value::string("00000001", Span::test_data())), }, Example { description: "convert a boolean value into a string, padded to 8 places with 0s", example: "true | format bits", result: Some(Value::string("00000001", Span::test_data())), }, Example { description: "convert a string into a raw binary string, padded with 0s to 8 places", example: "'nushell.sh' | format bits", result: Some(Value::string( "01101110 01110101 01110011 01101000 01100101 01101100 01101100 00101110 01110011 01101000", Span::test_data(), )), }, ] } } fn format_bits( engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let cell_paths = call.rest(engine_state, stack, 0)?; let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths); if let PipelineData::ByteStream(stream, metadata) = input { Ok(PipelineData::byte_stream( byte_stream_to_bits(stream, head), metadata, )) } else { let endian = call.get_flag::<Spanned<String>>(engine_state, stack, "endian")?; let little_endian = if let Some(endian) = endian { match endian.item.as_str() { "native" => cfg!(target_endian = "little"), "little" => true, "big" => false, _ => { return Err(ShellError::TypeMismatch { err_message: "Endian must be one of native, little, big".to_string(), span: endian.span, }); } } } else { false }; let args = Arguments { cell_paths, little_endian, }; operate(action, args, input, call.head, engine_state.signals()) } } fn byte_stream_to_bits(stream: ByteStream, head: Span) -> ByteStream { if let Some(mut reader) = stream.reader() { let mut is_first = true; ByteStream::from_fn( head, Signals::empty(), ByteStreamType::String, move |buffer| { let mut byte = [0]; if reader .read(&mut byte[..]) .map_err(|err| IoError::new(err, head, None))? > 0 { // Format the byte as bits if is_first { is_first = false; } else { buffer.push(b' '); } write!(buffer, "{:08b}", byte[0]).expect("format failed"); Ok(true) } else { // EOF Ok(false) } }, ) } else { ByteStream::read(io::empty(), head, Signals::empty(), ByteStreamType::String) } } fn convert_to_smallest_number_type(num: i64, span: Span, little_endian: bool) -> Value { if let Some(v) = num.to_i8() { let bytes = v.to_ne_bytes(); // Endianness does not affect `i8` let mut raw_string = "".to_string(); for ch in bytes { raw_string.push_str(&format!("{ch:08b} ")); } Value::string(raw_string.trim(), span) } else if let Some(v) = num.to_i16() { let bytes = if little_endian { v.to_le_bytes() } else { v.to_be_bytes() }; let mut raw_string = "".to_string(); for ch in bytes { raw_string.push_str(&format!("{ch:08b} ")); } Value::string(raw_string.trim(), span) } else if let Some(v) = num.to_i32() { let bytes = if little_endian { v.to_le_bytes() } else { v.to_be_bytes() }; let mut raw_string = "".to_string(); for ch in bytes { raw_string.push_str(&format!("{ch:08b} ")); } Value::string(raw_string.trim(), span) } else { let bytes = if little_endian { num.to_le_bytes() } else { num.to_be_bytes() }; let mut raw_string = "".to_string(); for ch in bytes { raw_string.push_str(&format!("{ch:08b} ")); } Value::string(raw_string.trim(), span) } } fn action(input: &Value, args: &Arguments, span: Span) -> Value { match input { Value::Binary { val, .. } => { let mut raw_string = "".to_string(); for ch in val { raw_string.push_str(&format!("{ch:08b} ")); } Value::string(raw_string.trim(), span) } Value::Int { val, .. } => convert_to_smallest_number_type(*val, span, args.little_endian), Value::Filesize { val, .. } => { convert_to_smallest_number_type(val.get(), span, args.little_endian) } Value::Duration { val, .. } => { convert_to_smallest_number_type(*val, span, args.little_endian) } Value::String { val, .. } => { let raw_bytes = val.as_bytes(); let mut raw_string = "".to_string(); for ch in raw_bytes { raw_string.push_str(&format!("{ch:08b} ")); } Value::string(raw_string.trim(), span) } Value::Bool { val, .. } => { let v = <i64 as From<bool>>::from(*val); convert_to_smallest_number_type(v, span, args.little_endian) } // Propagate errors by explicitly matching them before the final case. Value::Error { .. } => input.clone(), other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "int, filesize, string, duration, binary, or bool".into(), wrong_type: other.get_type().to_string(), dst_span: span, src_span: other.span(), }, span, ), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(FormatBits {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/strings/format/mod.rs
crates/nu-cmd-extra/src/extra/strings/format/mod.rs
mod bits; mod command; mod number; pub(crate) use bits::FormatBits; pub(crate) use command::FormatPattern; pub(crate) use number::FormatNumber;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/formats/mod.rs
crates/nu-cmd-extra/src/extra/formats/mod.rs
mod from; mod to; pub(crate) use from::url::FromUrl; pub use to::html::ToHtml;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/formats/from/url.rs
crates/nu-cmd-extra/src/extra/formats/from/url.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct FromUrl; impl Command for FromUrl { fn name(&self) -> &str { "from url" } fn signature(&self) -> Signature { Signature::build("from url") .input_output_types(vec![(Type::String, Type::record())]) .category(Category::Formats) } fn description(&self) -> &str { "Parse url-encoded string as a record." } fn run( &self, _engine_state: &EngineState, _stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; from_url(input, head) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { example: "'bread=baguette&cheese=comt%C3%A9&meat=ham&fat=butter' | from url", description: "Convert url encoded string into a record", result: Some(Value::test_record(record! { "bread" => Value::test_string("baguette"), "cheese" => Value::test_string("comté"), "meat" => Value::test_string("ham"), "fat" => Value::test_string("butter"), })), }] } } fn from_url(input: PipelineData, head: Span) -> Result<PipelineData, ShellError> { let (concat_string, span, metadata) = input.collect_string_strict(head)?; let result = serde_urlencoded::from_str::<Vec<(String, String)>>(&concat_string); match result { Ok(result) => { let record = result .into_iter() .map(|(k, v)| (k, Value::string(v, head))) .collect(); Ok(PipelineData::value(Value::record(record, head), metadata)) } _ => Err(ShellError::UnsupportedInput { msg: "String not compatible with URL encoding".to_string(), input: "value originates from here".into(), msg_span: head, input_span: span, }), } } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(FromUrl {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/formats/from/mod.rs
crates/nu-cmd-extra/src/extra/formats/from/mod.rs
pub(crate) mod url;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/formats/to/html.rs
crates/nu-cmd-extra/src/extra/formats/to/html.rs
use fancy_regex::Regex; use nu_cmd_base::formats::to::delimited::merge_descriptors; use nu_engine::command_prelude::*; use nu_protocol::{Config, DataSource, PipelineMetadata}; use nu_utils::IgnoreCaseExt; use rust_embed::RustEmbed; use serde::{Deserialize, Serialize}; use std::{collections::HashMap, error::Error, fmt::Write}; #[derive(Serialize, Deserialize, Debug)] pub struct HtmlThemes { themes: Vec<HtmlTheme>, } #[allow(non_snake_case)] #[derive(Serialize, Deserialize, Debug)] pub struct HtmlTheme { name: String, black: String, red: String, green: String, yellow: String, blue: String, purple: String, cyan: String, white: String, brightBlack: String, brightRed: String, brightGreen: String, brightYellow: String, brightBlue: String, brightPurple: String, brightCyan: String, brightWhite: String, background: String, foreground: String, } impl Default for HtmlThemes { fn default() -> Self { HtmlThemes { themes: vec![HtmlTheme::default()], } } } impl Default for HtmlTheme { fn default() -> Self { HtmlTheme { name: "nu_default".to_string(), black: "black".to_string(), red: "red".to_string(), green: "green".to_string(), yellow: "#717100".to_string(), blue: "blue".to_string(), purple: "#c800c8".to_string(), cyan: "#037979".to_string(), white: "white".to_string(), brightBlack: "black".to_string(), brightRed: "red".to_string(), brightGreen: "green".to_string(), brightYellow: "#717100".to_string(), brightBlue: "blue".to_string(), brightPurple: "#c800c8".to_string(), brightCyan: "#037979".to_string(), brightWhite: "white".to_string(), background: "white".to_string(), foreground: "black".to_string(), } } } #[derive(RustEmbed)] #[folder = "assets/"] struct Assets; #[derive(Clone)] pub struct ToHtml; impl Command for ToHtml { fn name(&self) -> &str { "to html" } fn signature(&self) -> Signature { Signature::build("to html") .input_output_types(vec![(Type::Nothing, Type::Any), (Type::Any, Type::String)]) .allow_variants_without_examples(true) .switch("html-color", "change ansi colors to html colors", Some('c')) .switch("no-color", "remove all ansi colors in output", Some('n')) .switch( "dark", "indicate your background color is a darker color", Some('d'), ) .switch( "partial", "only output the html for the content itself", Some('p'), ) .named( "theme", SyntaxShape::String, "the name of the theme to use (github, blulocolight, ...); case-insensitive", Some('t'), ) .switch( "list", "produce a color table of all available themes", Some('l'), ) .switch("raw", "do not escape html tags", Some('r')) .category(Category::Formats) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Outputs an HTML string representing the contents of this table", example: "[[foo bar]; [1 2]] | to html", result: Some(Value::test_string( r#"<html><style>body { background-color:white;color:black; }</style><body><table><thead><tr><th>foo</th><th>bar</th></tr></thead><tbody><tr><td>1</td><td>2</td></tr></tbody></table></body></html>"#, )), }, Example { description: "Outputs an HTML string using a record of xml data", example: r#"{tag: a attributes: { style: "color: red" } content: ["hello!"] } | to xml | to html --raw"#, result: Some(Value::test_string( r#"<html><style>body { background-color:white;color:black; }</style><body><a style="color: red">hello!</a></body></html>"#, )), }, Example { description: "Optionally, only output the html for the content itself", example: "[[foo bar]; [1 2]] | to html --partial", result: Some(Value::test_string( r#"<div style="background-color:white;color:black;"><table><thead><tr><th>foo</th><th>bar</th></tr></thead><tbody><tr><td>1</td><td>2</td></tr></tbody></table></div>"#, )), }, Example { description: "Optionally, output the string with a dark background", example: "[[foo bar]; [1 2]] | to html --dark", result: Some(Value::test_string( r#"<html><style>body { background-color:black;color:white; }</style><body><table><thead><tr><th>foo</th><th>bar</th></tr></thead><tbody><tr><td>1</td><td>2</td></tr></tbody></table></body></html>"#, )), }, ] } fn description(&self) -> &str { "Convert table into simple HTML." } fn extra_description(&self) -> &str { "Screenshots of the themes can be browsed here: https://github.com/mbadolato/iTerm2-Color-Schemes." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { to_html(input, call, engine_state, stack) } } fn get_theme_from_asset_file( is_dark: bool, theme: Option<&Spanned<String>>, ) -> Result<HashMap<&'static str, String>, ShellError> { let theme_name = match theme { Some(s) => &s.item, None => { return Ok(convert_html_theme_to_hash_map( is_dark, &HtmlTheme::default(), )); } }; let theme_span = theme.map(|s| s.span).unwrap_or(Span::unknown()); // 228 themes come from // https://github.com/mbadolato/iTerm2-Color-Schemes/tree/master/windowsterminal // we should find a hit on any name in there let asset = get_html_themes("228_themes.json").unwrap_or_default(); // Find the theme by theme name let th = asset .themes .into_iter() .find(|n| n.name.eq_ignore_case(theme_name)); // case insensitive search let th = match th { Some(t) => t, None => { return Err(ShellError::TypeMismatch { err_message: format!("Unknown HTML theme '{theme_name}'"), span: theme_span, }); } }; Ok(convert_html_theme_to_hash_map(is_dark, &th)) } fn convert_html_theme_to_hash_map( is_dark: bool, theme: &HtmlTheme, ) -> HashMap<&'static str, String> { let mut hm: HashMap<&str, String> = HashMap::with_capacity(18); hm.insert("bold_black", theme.brightBlack[..].to_string()); hm.insert("bold_red", theme.brightRed[..].to_string()); hm.insert("bold_green", theme.brightGreen[..].to_string()); hm.insert("bold_yellow", theme.brightYellow[..].to_string()); hm.insert("bold_blue", theme.brightBlue[..].to_string()); hm.insert("bold_magenta", theme.brightPurple[..].to_string()); hm.insert("bold_cyan", theme.brightCyan[..].to_string()); hm.insert("bold_white", theme.brightWhite[..].to_string()); hm.insert("black", theme.black[..].to_string()); hm.insert("red", theme.red[..].to_string()); hm.insert("green", theme.green[..].to_string()); hm.insert("yellow", theme.yellow[..].to_string()); hm.insert("blue", theme.blue[..].to_string()); hm.insert("magenta", theme.purple[..].to_string()); hm.insert("cyan", theme.cyan[..].to_string()); hm.insert("white", theme.white[..].to_string()); // Try to make theme work with light or dark but // flipping the foreground and background but leave // the other colors the same. if is_dark { hm.insert("background", theme.black[..].to_string()); hm.insert("foreground", theme.white[..].to_string()); } else { hm.insert("background", theme.white[..].to_string()); hm.insert("foreground", theme.black[..].to_string()); } hm } fn get_html_themes(json_name: &str) -> Result<HtmlThemes, Box<dyn Error>> { match Assets::get(json_name) { Some(content) => Ok(nu_json::from_slice(&content.data)?), None => Ok(HtmlThemes::default()), } } fn to_html( input: PipelineData, call: &Call, engine_state: &EngineState, stack: &mut Stack, ) -> Result<PipelineData, ShellError> { let head = call.head; let html_color = call.has_flag(engine_state, stack, "html-color")?; let no_color = call.has_flag(engine_state, stack, "no-color")?; let dark = call.has_flag(engine_state, stack, "dark")?; let partial = call.has_flag(engine_state, stack, "partial")?; let list = call.has_flag(engine_state, stack, "list")?; let raw = call.has_flag(engine_state, stack, "raw")?; let theme: Option<Spanned<String>> = call.get_flag(engine_state, stack, "theme")?; let config = &stack.get_config(engine_state); let vec_of_values = input.into_iter().collect::<Vec<Value>>(); let headers = merge_descriptors(&vec_of_values); let headers = Some(headers) .filter(|headers| !headers.is_empty() && (headers.len() > 1 || !headers[0].is_empty())); let mut output_string = String::new(); let mut regex_hm: HashMap<u32, (&str, String)> = HashMap::with_capacity(17); if list { // Being essentially a 'help' option, this can afford to be relatively unoptimised return Ok(theme_demo(head)); } let theme_span = match &theme { Some(v) => v.span, None => head, }; let color_hm = match get_theme_from_asset_file(dark, theme.as_ref()) { Ok(c) => c, Err(e) => match e { ShellError::TypeMismatch { err_message, span: _, } => { return Err(ShellError::TypeMismatch { err_message, span: theme_span, }); } _ => return Err(e), }, }; // change the color of the page if !partial { write!( &mut output_string, r"<html><style>body {{ background-color:{};color:{}; }}</style><body>", color_hm .get("background") .expect("Error getting background color"), color_hm .get("foreground") .expect("Error getting foreground color") ) .ok(); } else { write!( &mut output_string, "<div style=\"background-color:{};color:{};\">", color_hm .get("background") .expect("Error getting background color"), color_hm .get("foreground") .expect("Error getting foreground color") ) .ok(); } let inner_value = match vec_of_values.len() { 0 => String::default(), 1 => match headers { Some(headers) => html_table(vec_of_values, headers, raw, config), None => { let value = &vec_of_values[0]; html_value(value.clone(), raw, config) } }, _ => match headers { Some(headers) => html_table(vec_of_values, headers, raw, config), None => html_list(vec_of_values, raw, config), }, }; output_string.push_str(&inner_value); if !partial { output_string.push_str("</body></html>"); } else { output_string.push_str("</div>") } // Check to see if we want to remove all color or change ansi to html colors if html_color { setup_html_color_regexes(&mut regex_hm, &color_hm); output_string = run_regexes(&regex_hm, &output_string); } else if no_color { setup_no_color_regexes(&mut regex_hm); output_string = run_regexes(&regex_hm, &output_string); } let metadata = PipelineMetadata { data_source: nu_protocol::DataSource::None, content_type: Some(mime::TEXT_HTML_UTF_8.to_string()), ..Default::default() }; Ok(Value::string(output_string, head).into_pipeline_data_with_metadata(metadata)) } fn theme_demo(span: Span) -> PipelineData { // If asset doesn't work, make sure to return the default theme let html_themes = get_html_themes("228_themes.json").unwrap_or_default(); let result: Vec<Value> = html_themes .themes .into_iter() .map(|n| { Value::record( record! { "name" => Value::string(n.name, span), "black" => Value::string(n.black, span), "red" => Value::string(n.red, span), "green" => Value::string(n.green, span), "yellow" => Value::string(n.yellow, span), "blue" => Value::string(n.blue, span), "purple" => Value::string(n.purple, span), "cyan" => Value::string(n.cyan, span), "white" => Value::string(n.white, span), "brightBlack" => Value::string(n.brightBlack, span), "brightRed" => Value::string(n.brightRed, span), "brightGreen" => Value::string(n.brightGreen, span), "brightYellow" => Value::string(n.brightYellow, span), "brightBlue" => Value::string(n.brightBlue, span), "brightPurple" => Value::string(n.brightPurple, span), "brightCyan" => Value::string(n.brightCyan, span), "brightWhite" => Value::string(n.brightWhite, span), "background" => Value::string(n.background, span), "foreground" => Value::string(n.foreground, span), }, span, ) }) .collect(); Value::list(result, span).into_pipeline_data_with_metadata(PipelineMetadata { data_source: DataSource::HtmlThemes, ..Default::default() }) } fn html_list(list: Vec<Value>, raw: bool, config: &Config) -> String { let mut output_string = String::new(); output_string.push_str("<ol>"); for value in list { output_string.push_str("<li>"); output_string.push_str(&html_value(value, raw, config)); output_string.push_str("</li>"); } output_string.push_str("</ol>"); output_string } fn html_table(table: Vec<Value>, headers: Vec<String>, raw: bool, config: &Config) -> String { let mut output_string = String::new(); output_string.push_str("<table>"); output_string.push_str("<thead><tr>"); for header in &headers { output_string.push_str("<th>"); output_string.push_str(&v_htmlescape::escape(header).to_string()); output_string.push_str("</th>"); } output_string.push_str("</tr></thead><tbody>"); for row in table { let span = row.span(); if let Value::Record { val: row, .. } = row { output_string.push_str("<tr>"); for header in &headers { let data = row .get(header) .cloned() .unwrap_or_else(|| Value::nothing(span)); output_string.push_str("<td>"); output_string.push_str(&html_value(data, raw, config)); output_string.push_str("</td>"); } output_string.push_str("</tr>"); } } output_string.push_str("</tbody></table>"); output_string } fn html_value(value: Value, raw: bool, config: &Config) -> String { let mut output_string = String::new(); match value { Value::Binary { val, .. } => { let output = nu_pretty_hex::pretty_hex(&val); output_string.push_str("<pre>"); output_string.push_str(&output); output_string.push_str("</pre>"); } other => { if raw { output_string.push_str( &other .to_abbreviated_string(config) .to_string() .replace('\n', "<br>"), ) } else { output_string.push_str( &v_htmlescape::escape(&other.to_abbreviated_string(config)) .to_string() .replace('\n', "<br>"), ) } } } output_string } fn setup_html_color_regexes( hash: &mut HashMap<u32, (&'static str, String)>, color_hm: &HashMap<&str, String>, ) { // All the bold colors hash.insert( 0, ( r"(?P<reset>\[0m)(?P<word>[[:alnum:][:space:][:punct:]]*)", // Reset the text color, normal weight font format!( r"<span style='color:{};font-weight:normal;'>$word</span>", color_hm .get("foreground") .expect("Error getting reset text color") ), ), ); hash.insert( 1, ( // Bold Black r"(?P<bb>\[1;30m)(?P<word>[[:alnum:][:space:][:punct:]]*)", format!( r"<span style='color:{};font-weight:bold;'>$word</span>", color_hm .get("foreground") .expect("Error getting bold black text color") ), ), ); hash.insert( 2, ( // Bold Red r"(?P<br>\[1;31m)(?P<word>[[:alnum:][:space:][:punct:]]*)", format!( r"<span style='color:{};font-weight:bold;'>$word</span>", color_hm .get("bold_red") .expect("Error getting bold red text color"), ), ), ); hash.insert( 3, ( // Bold Green r"(?P<bg>\[1;32m)(?P<word>[[:alnum:][:space:][:punct:]]*)", format!( r"<span style='color:{};font-weight:bold;'>$word</span>", color_hm .get("bold_green") .expect("Error getting bold green text color"), ), ), ); hash.insert( 4, ( // Bold Yellow r"(?P<by>\[1;33m)(?P<word>[[:alnum:][:space:][:punct:]]*)", format!( r"<span style='color:{};font-weight:bold;'>$word</span>", color_hm .get("bold_yellow") .expect("Error getting bold yellow text color"), ), ), ); hash.insert( 5, ( // Bold Blue r"(?P<bu>\[1;34m)(?P<word>[[:alnum:][:space:][:punct:]]*)", format!( r"<span style='color:{};font-weight:bold;'>$word</span>", color_hm .get("bold_blue") .expect("Error getting bold blue text color"), ), ), ); hash.insert( 6, ( // Bold Magenta r"(?P<bm>\[1;35m)(?P<word>[[:alnum:][:space:][:punct:]]*)", format!( r"<span style='color:{};font-weight:bold;'>$word</span>", color_hm .get("bold_magenta") .expect("Error getting bold magenta text color"), ), ), ); hash.insert( 7, ( // Bold Cyan r"(?P<bc>\[1;36m)(?P<word>[[:alnum:][:space:][:punct:]]*)", format!( r"<span style='color:{};font-weight:bold;'>$word</span>", color_hm .get("bold_cyan") .expect("Error getting bold cyan text color"), ), ), ); hash.insert( 8, ( // Bold White // Let's change this to black since the html background // is white. White on white = no bueno. r"(?P<bw>\[1;37m)(?P<word>[[:alnum:][:space:][:punct:]]*)", format!( r"<span style='color:{};font-weight:bold;'>$word</span>", color_hm .get("foreground") .expect("Error getting bold bold white text color"), ), ), ); // All the normal colors hash.insert( 9, ( // Black r"(?P<b>\[30m)(?P<word>[[:alnum:][:space:][:punct:]]*)", format!( r"<span style='color:{};'>$word</span>", color_hm .get("foreground") .expect("Error getting black text color"), ), ), ); hash.insert( 10, ( // Red r"(?P<r>\[31m)(?P<word>[[:alnum:][:space:][:punct:]]*)", format!( r"<span style='color:{};'>$word</span>", color_hm.get("red").expect("Error getting red text color"), ), ), ); hash.insert( 11, ( // Green r"(?P<g>\[32m)(?P<word>[[:alnum:][:space:][:punct:]]*)", format!( r"<span style='color:{};'>$word</span>", color_hm .get("green") .expect("Error getting green text color"), ), ), ); hash.insert( 12, ( // Yellow r"(?P<y>\[33m)(?P<word>[[:alnum:][:space:][:punct:]]*)", format!( r"<span style='color:{};'>$word</span>", color_hm .get("yellow") .expect("Error getting yellow text color"), ), ), ); hash.insert( 13, ( // Blue r"(?P<u>\[34m)(?P<word>[[:alnum:][:space:][:punct:]]*)", format!( r"<span style='color:{};'>$word</span>", color_hm.get("blue").expect("Error getting blue text color"), ), ), ); hash.insert( 14, ( // Magenta r"(?P<m>\[35m)(?P<word>[[:alnum:][:space:][:punct:]]*)", format!( r"<span style='color:{};'>$word</span>", color_hm .get("magenta") .expect("Error getting magenta text color"), ), ), ); hash.insert( 15, ( // Cyan r"(?P<c>\[36m)(?P<word>[[:alnum:][:space:][:punct:]]*)", format!( r"<span style='color:{};'>$word</span>", color_hm.get("cyan").expect("Error getting cyan text color"), ), ), ); hash.insert( 16, ( // White // Let's change this to black since the html background // is white. White on white = no bueno. r"(?P<w>\[37m)(?P<word>[[:alnum:][:space:][:punct:]]*)", format!( r"<span style='color:{};'>$word</span>", color_hm .get("foreground") .expect("Error getting white text color"), ), ), ); } fn setup_no_color_regexes(hash: &mut HashMap<u32, (&'static str, String)>) { // We can just use one regex here because we're just removing ansi sequences // and not replacing them with html colors. // attribution: https://stackoverflow.com/questions/14693701/how-can-i-remove-the-ansi-escape-sequences-from-a-string-in-python hash.insert( 0, ( r"(?:\x1B[@-Z\\-_]|[\x80-\x9A\x9C-\x9F]|(?:\x1B\[|\x9B)[0-?]*[ -/]*[@-~])", r"$name_group_doesnt_exist".to_string(), ), ); } fn run_regexes(hash: &HashMap<u32, (&'static str, String)>, contents: &str) -> String { let mut working_string = contents.to_owned(); let hash_count: u32 = hash.len() as u32; for n in 0..hash_count { let value = hash.get(&n).expect("error getting hash at index"); let re = Regex::new(value.0).expect("problem with color regex"); let after = re.replace_all(&working_string, &value.1[..]).to_string(); working_string = after; } working_string } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { use crate::test_examples_with_commands; use nu_command::ToXml; test_examples_with_commands(ToHtml {}, &[&ToXml]) } #[test] fn get_theme_from_asset_file_returns_default() { let result = super::get_theme_from_asset_file(false, None); assert!(result.is_ok(), "Expected Ok result for None theme"); let theme_map = result.unwrap(); assert_eq!( theme_map.get("background").map(String::as_str), Some("white"), "Expected default background color to be white" ); assert_eq!( theme_map.get("foreground").map(String::as_str), Some("black"), "Expected default foreground color to be black" ); assert!( theme_map.contains_key("red"), "Expected default theme to have a 'red' color" ); assert!( theme_map.contains_key("bold_green"), "Expected default theme to have a 'bold_green' color" ); } #[test] fn returns_a_valid_theme() { let theme_name = "Dracula".to_string().into_spanned(Span::new(0, 7)); let result = super::get_theme_from_asset_file(false, Some(&theme_name)); assert!(result.is_ok(), "Expected Ok result for valid theme"); let theme_map = result.unwrap(); let required_keys = [ "background", "foreground", "red", "green", "blue", "bold_red", "bold_green", "bold_blue", ]; for key in required_keys { assert!( theme_map.contains_key(key), "Expected theme to contain key '{key}'" ); } } #[test] fn fails_with_unknown_theme_name() { let result = super::get_theme_from_asset_file( false, Some(&"doesnt-exist".to_string().into_spanned(Span::new(0, 13))), ); assert!(result.is_err(), "Expected error for invalid theme name"); if let Err(err) = result { assert!( matches!(err, ShellError::TypeMismatch { .. }), "Expected TypeMismatch error, got: {err:?}" ); if let ShellError::TypeMismatch { err_message, span } = err { assert!( err_message.contains("doesnt-exist"), "Error message should mention theme name, got: {err_message}" ); assert_eq!(span.start, 0); assert_eq!(span.end, 13); } } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/formats/to/mod.rs
crates/nu-cmd-extra/src/extra/formats/to/mod.rs
pub(crate) mod html;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/filters/each_while.rs
crates/nu-cmd-extra/src/extra/filters/each_while.rs
use nu_engine::{ClosureEval, ClosureEvalOnce, command_prelude::*}; use nu_protocol::engine::Closure; #[derive(Clone)] pub struct EachWhile; impl Command for EachWhile { fn name(&self) -> &str { "each while" } fn description(&self) -> &str { "Run a closure on each row of the input list until a null is found, then create a new list with the results." } fn search_terms(&self) -> Vec<&str> { vec!["for", "loop", "iterate"] } fn signature(&self) -> nu_protocol::Signature { Signature::build(self.name()) .input_output_types(vec![( Type::List(Box::new(Type::Any)), Type::List(Box::new(Type::Any)), )]) .required( "closure", SyntaxShape::Closure(Some(vec![SyntaxShape::Any])), "The closure to run.", ) .category(Category::Filters) } fn examples(&self) -> Vec<Example<'_>> { let stream_test_1 = vec![Value::test_int(2), Value::test_int(4)]; let stream_test_2 = vec![ Value::test_string("Output: 1"), Value::test_string("Output: 2"), ]; vec![ Example { example: "[1 2 3 2 1] | each while {|e| if $e < 3 { $e * 2 } }", description: "Produces a list of each element before the 3, doubled", result: Some(Value::list(stream_test_1, Span::test_data())), }, Example { example: r#"[1 2 stop 3 4] | each while {|e| if $e != 'stop' { $"Output: ($e)" } }"#, description: "Output elements until reaching 'stop'", result: Some(Value::list(stream_test_2, Span::test_data())), }, Example { example: r#"[1 2 3] | enumerate | each while {|e| if $e.item < 2 { $"value ($e.item) at ($e.index)!"} }"#, description: "Iterate over each element, printing the matching value and its index", result: Some(Value::list( vec![Value::test_string("value 1 at 0!")], Span::test_data(), )), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let closure: Closure = call.req(engine_state, stack, 0)?; let metadata = input.metadata(); match input { PipelineData::Empty => Ok(PipelineData::empty()), PipelineData::Value(Value::Range { .. }, ..) | PipelineData::Value(Value::List { .. }, ..) | PipelineData::ListStream(..) => { let mut closure = ClosureEval::new(engine_state, stack, closure); Ok(input .into_iter() .map_while(move |value| { match closure .run_with_value(value) .and_then(|data| data.into_value(head)) { Ok(value) => (!value.is_nothing()).then_some(value), Err(_) => None, } }) .fuse() .into_pipeline_data(head, engine_state.signals().clone())) } PipelineData::ByteStream(stream, ..) => { let span = stream.span(); if let Some(chunks) = stream.chunks() { let mut closure = ClosureEval::new(engine_state, stack, closure); Ok(chunks .map_while(move |value| { let value = value.ok()?; match closure .run_with_value(value) .and_then(|data| data.into_value(span)) { Ok(value) => (!value.is_nothing()).then_some(value), Err(_) => None, } }) .fuse() .into_pipeline_data(head, engine_state.signals().clone())) } else { Ok(PipelineData::empty()) } } // This match allows non-iterables to be accepted, // which is currently considered undesirable (Nov 2022). PipelineData::Value(value, ..) => { ClosureEvalOnce::new(engine_state, stack, closure).run_with_value(value) } } .map(|data| data.set_metadata(metadata)) } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(EachWhile {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/filters/update_cells.rs
crates/nu-cmd-extra/src/extra/filters/update_cells.rs
use nu_engine::{ClosureEval, command_prelude::*}; use nu_protocol::{PipelineIterator, engine::Closure}; use std::collections::HashSet; #[derive(Clone)] pub struct UpdateCells; impl Command for UpdateCells { fn name(&self) -> &str { "update cells" } fn signature(&self) -> Signature { Signature::build("update cells") .input_output_types(vec![ (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .required( "closure", SyntaxShape::Closure(Some(vec![SyntaxShape::Any])), "The closure to run an update for each cell.", ) .named( "columns", SyntaxShape::List(Box::new(SyntaxShape::Any)), "list of columns to update", Some('c'), ) .category(Category::Filters) } fn description(&self) -> &str { "Update the table cells." } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Update the zero value cells to empty strings.", example: r#"[ ["2021-04-16", "2021-06-10", "2021-09-18", "2021-10-15", "2021-11-16", "2021-11-17", "2021-11-18"]; [ 37, 0, 0, 0, 37, 0, 0] ] | update cells { |value| if $value == 0 { "" } else { $value } }"#, result: Some(Value::test_list(vec![Value::test_record(record! { "2021-04-16" => Value::test_int(37), "2021-06-10" => Value::test_string(""), "2021-09-18" => Value::test_string(""), "2021-10-15" => Value::test_string(""), "2021-11-16" => Value::test_int(37), "2021-11-17" => Value::test_string(""), "2021-11-18" => Value::test_string(""), })])), }, Example { description: "Update the zero value cells to empty strings in 2 last columns.", example: r#"[ ["2021-04-16", "2021-06-10", "2021-09-18", "2021-10-15", "2021-11-16", "2021-11-17", "2021-11-18"]; [ 37, 0, 0, 0, 37, 0, 0] ] | update cells -c ["2021-11-18", "2021-11-17"] { |value| if $value == 0 { "" } else { $value } }"#, result: Some(Value::test_list(vec![Value::test_record(record! { "2021-04-16" => Value::test_int(37), "2021-06-10" => Value::test_int(0), "2021-09-18" => Value::test_int(0), "2021-10-15" => Value::test_int(0), "2021-11-16" => Value::test_int(37), "2021-11-17" => Value::test_string(""), "2021-11-18" => Value::test_string(""), })])), }, Example { example: r#"{a: 1, b: 2, c: 3} | update cells { $in + 10 }"#, description: "Update each value in a record.", result: Some(Value::test_record(record! { "a" => Value::test_int(11), "b" => Value::test_int(12), "c" => Value::test_int(13), })), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, mut input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let closure: Closure = call.req(engine_state, stack, 0)?; let columns: Option<Value> = call.get_flag(engine_state, stack, "columns")?; let columns: Option<HashSet<String>> = match columns { Some(val) => Some( val.into_list()? .into_iter() .map(Value::coerce_into_string) .collect::<Result<HashSet<String>, ShellError>>()?, ), None => None, }; let metadata = input.metadata(); let span = input.span(); match input { PipelineData::Value(Value::Record { ref mut val, .. }, ..) => { // SAFETY: we have a value in the input, so we must have a span let span = span.expect("value had no span"); let val = val.to_mut(); update_record( val, &mut ClosureEval::new(engine_state, stack, closure), span, columns.as_ref(), ); Ok(input) } _ => Ok(UpdateCellIterator { iter: input.into_iter(), closure: ClosureEval::new(engine_state, stack, closure), columns, span: head, } .into_pipeline_data(head, engine_state.signals().clone()) .set_metadata(metadata)), } } } fn update_record( record: &mut Record, closure: &mut ClosureEval, span: Span, cols: Option<&HashSet<String>>, ) { if let Some(columns) = cols { for (col, val) in record.iter_mut() { if columns.contains(col) { *val = eval_value(closure, span, std::mem::take(val)); } } } else { for (_, val) in record.iter_mut() { *val = eval_value(closure, span, std::mem::take(val)) } } } struct UpdateCellIterator { iter: PipelineIterator, closure: ClosureEval, columns: Option<HashSet<String>>, span: Span, } impl Iterator for UpdateCellIterator { type Item = Value; fn next(&mut self) -> Option<Self::Item> { let mut value = self.iter.next()?; let value = if let Value::Record { val, .. } = &mut value { let val = val.to_mut(); update_record(val, &mut self.closure, self.span, self.columns.as_ref()); value } else { eval_value(&mut self.closure, self.span, value) }; Some(value) } } fn eval_value(closure: &mut ClosureEval, span: Span, value: Value) -> Value { closure .run_with_value(value) .and_then(|data| data.into_value(span)) .unwrap_or_else(|err| Value::error(err, span)) } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(UpdateCells {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/filters/mod.rs
crates/nu-cmd-extra/src/extra/filters/mod.rs
mod each_while; mod roll; mod rotate; mod update_cells; pub(crate) use each_while::EachWhile; pub(crate) use roll::*; pub(crate) use rotate::Rotate; pub(crate) use update_cells::UpdateCells;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/filters/rotate.rs
crates/nu-cmd-extra/src/extra/filters/rotate.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct Rotate; impl Command for Rotate { fn name(&self) -> &str { "rotate" } fn signature(&self) -> Signature { Signature::build("rotate") .input_output_types(vec![ (Type::record(), Type::table()), (Type::table(), Type::table()), (Type::list(Type::Any), Type::table()), (Type::String, Type::table()), ]) .switch("ccw", "rotate counter clockwise", None) .rest( "rest", SyntaxShape::String, "The names to give columns once rotated.", ) .category(Category::Filters) .allow_variants_without_examples(true) } fn description(&self) -> &str { "Rotates a table or record clockwise (default) or counter-clockwise (use --ccw flag)." } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Rotate a record clockwise, producing a table (like `transpose` but with column order reversed)", example: "{a:1, b:2} | rotate", result: Some(Value::test_list(vec![ Value::test_record(record! { "column0" => Value::test_int(1), "column1" => Value::test_string("a"), }), Value::test_record(record! { "column0" => Value::test_int(2), "column1" => Value::test_string("b"), }), ])), }, Example { description: "Rotate 2x3 table clockwise", example: "[[a b]; [1 2] [3 4] [5 6]] | rotate", result: Some(Value::test_list(vec![ Value::test_record(record! { "column0" => Value::test_int(5), "column1" => Value::test_int(3), "column2" => Value::test_int(1), "column3" => Value::test_string("a"), }), Value::test_record(record! { "column0" => Value::test_int(6), "column1" => Value::test_int(4), "column2" => Value::test_int(2), "column3" => Value::test_string("b"), }), ])), }, Example { description: "Rotate table clockwise and change columns names", example: "[[a b]; [1 2]] | rotate col_a col_b", result: Some(Value::test_list(vec![ Value::test_record(record! { "col_a" => Value::test_int(1), "col_b" => Value::test_string("a"), }), Value::test_record(record! { "col_a" => Value::test_int(2), "col_b" => Value::test_string("b"), }), ])), }, Example { description: "Rotate table counter clockwise", example: "[[a b]; [1 2]] | rotate --ccw", result: Some(Value::test_list(vec![ Value::test_record(record! { "column0" => Value::test_string("b"), "column1" => Value::test_int(2), }), Value::test_record(record! { "column0" => Value::test_string("a"), "column1" => Value::test_int(1), }), ])), }, Example { description: "Rotate table counter-clockwise", example: "[[a b]; [1 2] [3 4] [5 6]] | rotate --ccw", result: Some(Value::test_list(vec![ Value::test_record(record! { "column0" => Value::test_string("b"), "column1" => Value::test_int(2), "column2" => Value::test_int(4), "column3" => Value::test_int(6), }), Value::test_record(record! { "column0" => Value::test_string("a"), "column1" => Value::test_int(1), "column2" => Value::test_int(3), "column3" => Value::test_int(5), }), ])), }, Example { description: "Rotate table counter-clockwise and change columns names", example: "[[a b]; [1 2]] | rotate --ccw col_a col_b", result: Some(Value::test_list(vec![ Value::test_record(record! { "col_a" => Value::test_string("b"), "col_b" => Value::test_int(2), }), Value::test_record(record! { "col_a" => Value::test_string("a"), "col_b" => Value::test_int(1), }), ])), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { rotate(engine_state, stack, call, input) } } pub fn rotate( engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let metadata = input.metadata(); let col_given_names: Vec<String> = call.rest(engine_state, stack, 0)?; let input_span = input.span().unwrap_or(call.head); let mut values = input.into_iter().collect::<Vec<_>>(); let mut old_column_names = vec![]; let mut new_values = vec![]; let mut not_a_record = false; let mut total_rows = values.len(); let ccw: bool = call.has_flag(engine_state, stack, "ccw")?; if !ccw { values.reverse(); } if !values.is_empty() { for val in values.into_iter() { let span = val.span(); match val { Value::Record { val: record, .. } => { let (cols, vals): (Vec<_>, Vec<_>) = record.into_owned().into_iter().unzip(); old_column_names = cols; new_values.extend_from_slice(&vals); } Value::List { vals, .. } => { not_a_record = true; for v in vals { new_values.push(v); } } Value::String { val, .. } => { not_a_record = true; new_values.push(Value::string(val, span)) } x => { not_a_record = true; new_values.push(x) } } } } else { return Err(ShellError::UnsupportedInput { msg: "list input is empty".to_string(), input: "value originates from here".into(), msg_span: call.head, input_span, }); } let total_columns = old_column_names.len(); // we use this for building columns names, but for non-records we get an extra row so we remove it if total_columns == 0 { total_rows -= 1; } // holder for the new column names, particularly if none are provided by the user we create names as column0, column1, etc. let mut new_column_names = { let mut res = vec![]; for idx in 0..(total_rows + 1) { res.push(format!("column{idx}")); } res.to_vec() }; // we got new names for columns from the input, so we need to swap those we already made if !col_given_names.is_empty() { for (idx, val) in col_given_names.into_iter().enumerate() { if idx > new_column_names.len() - 1 { break; } new_column_names[idx] = val; } } if not_a_record { let record = Record::from_raw_cols_vals(new_column_names, new_values, input_span, call.head)?; return Ok( Value::list(vec![Value::record(record, call.head)], call.head) .into_pipeline_data() .set_metadata(metadata), ); } // holder for the new records let mut final_values = vec![]; // the number of initial columns will be our number of rows, so we iterate through that to get the new number of rows that we need to make // for counter clockwise, we're iterating from right to left and have a pair of (index, value) let columns_iter = if ccw { old_column_names .iter() .enumerate() .rev() .collect::<Vec<_>>() } else { // as we're rotating clockwise, we're iterating from left to right and have a pair of (index, value) old_column_names.iter().enumerate().collect::<Vec<_>>() }; for (idx, val) in columns_iter { // when rotating counter clockwise, the old columns names become the first column's values let mut res = if ccw { vec![Value::string(val, call.head)] } else { vec![] }; let new_vals = { // move through the array with a step, which is every new_values size / total rows, starting from our old column's index // so if initial data was like this [[a b]; [1 2] [3 4]] - we basically iterate on this [3 4 1 2] array, so we pick 3, then 1, and then when idx increases, we pick 4 and 2 for i in (idx..new_values.len()).step_by(new_values.len() / total_rows) { res.push(new_values[i].clone()); } // when rotating clockwise, the old column names become the last column's values if !ccw { res.push(Value::string(val, call.head)); } res.to_vec() }; let record = Record::from_raw_cols_vals(new_column_names.clone(), new_vals, input_span, call.head)?; final_values.push(Value::record(record, call.head)) } Ok(Value::list(final_values, call.head) .into_pipeline_data() .set_metadata(metadata)) } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Rotate) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/filters/roll/roll_left.rs
crates/nu-cmd-extra/src/extra/filters/roll/roll_left.rs
use super::{HorizontalDirection, horizontal_rotate_value}; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct RollLeft; impl Command for RollLeft { fn name(&self) -> &str { "roll left" } fn search_terms(&self) -> Vec<&str> { vec!["rotate", "shift", "move", "column"] } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ (Type::record(), Type::record()), (Type::table(), Type::table()), ]) .named( "by", SyntaxShape::Int, "Number of columns to roll", Some('b'), ) .switch( "cells-only", "rotates columns leaving headers fixed", Some('c'), ) .category(Category::Filters) } fn description(&self) -> &str { "Roll record or table columns left." } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Rolls columns of a record to the left", example: "{a:1 b:2 c:3} | roll left", result: Some(Value::test_record(record! { "b" => Value::test_int(2), "c" => Value::test_int(3), "a" => Value::test_int(1), })), }, Example { description: "Rolls columns of a table to the left", example: "[[a b c]; [1 2 3] [4 5 6]] | roll left", result: Some(Value::test_list(vec![ Value::test_record(record! { "b" => Value::test_int(2), "c" => Value::test_int(3), "a" => Value::test_int(1), }), Value::test_record(record! { "b" => Value::test_int(5), "c" => Value::test_int(6), "a" => Value::test_int(4), }), ])), }, Example { description: "Rolls columns to the left without changing column names", example: "[[a b c]; [1 2 3] [4 5 6]] | roll left --cells-only", result: Some(Value::test_list(vec![ Value::test_record(record! { "a" => Value::test_int(2), "b" => Value::test_int(3), "c" => Value::test_int(1), }), Value::test_record(record! { "a" => Value::test_int(5), "b" => Value::test_int(6), "c" => Value::test_int(4), }), ])), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let by: Option<usize> = call.get_flag(engine_state, stack, "by")?; let metadata = input.metadata(); let cells_only = call.has_flag(engine_state, stack, "cells-only")?; let value = input.into_value(call.head)?; let rotated_value = horizontal_rotate_value(value, by, cells_only, &HorizontalDirection::Left)?; Ok(rotated_value.into_pipeline_data().set_metadata(metadata)) } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(RollLeft {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/filters/roll/roll_right.rs
crates/nu-cmd-extra/src/extra/filters/roll/roll_right.rs
use super::{HorizontalDirection, horizontal_rotate_value}; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct RollRight; impl Command for RollRight { fn name(&self) -> &str { "roll right" } fn search_terms(&self) -> Vec<&str> { vec!["rotate", "shift", "move", "column"] } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ (Type::record(), Type::record()), (Type::table(), Type::table()), ]) .named( "by", SyntaxShape::Int, "Number of columns to roll", Some('b'), ) .switch( "cells-only", "rotates columns leaving headers fixed", Some('c'), ) .category(Category::Filters) } fn description(&self) -> &str { "Roll table columns right." } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Rolls columns of a record to the right", example: "{a:1 b:2 c:3} | roll right", result: Some(Value::test_record(record! { "c" => Value::test_int(3), "a" => Value::test_int(1), "b" => Value::test_int(2), })), }, Example { description: "Rolls columns to the right", example: "[[a b c]; [1 2 3] [4 5 6]] | roll right", result: Some(Value::test_list(vec![ Value::test_record(record! { "c" => Value::test_int(3), "a" => Value::test_int(1), "b" => Value::test_int(2), }), Value::test_record(record! { "c" => Value::test_int(6), "a" => Value::test_int(4), "b" => Value::test_int(5), }), ])), }, Example { description: "Rolls columns to the right with fixed headers", example: "[[a b c]; [1 2 3] [4 5 6]] | roll right --cells-only", result: Some(Value::test_list(vec![ Value::test_record(record! { "a" => Value::test_int(3), "b" => Value::test_int(1), "c" => Value::test_int(2), }), Value::test_record(record! { "a" => Value::test_int(6), "b" => Value::test_int(4), "c" => Value::test_int(5), }), ])), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let by: Option<usize> = call.get_flag(engine_state, stack, "by")?; let metadata = input.metadata(); let cells_only = call.has_flag(engine_state, stack, "cells-only")?; let value = input.into_value(call.head)?; let rotated_value = horizontal_rotate_value(value, by, cells_only, &HorizontalDirection::Right)?; Ok(rotated_value.into_pipeline_data().set_metadata(metadata)) } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(RollRight {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/filters/roll/roll_up.rs
crates/nu-cmd-extra/src/extra/filters/roll/roll_up.rs
use super::{VerticalDirection, vertical_rotate_value}; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct RollUp; impl Command for RollUp { fn name(&self) -> &str { "roll up" } fn search_terms(&self) -> Vec<&str> { vec!["rotate", "shift", "move", "row"] } fn signature(&self) -> Signature { Signature::build(self.name()) // TODO: It also operates on List .input_output_types(vec![(Type::table(), Type::table())]) .named("by", SyntaxShape::Int, "Number of rows to roll", Some('b')) .category(Category::Filters) } fn description(&self) -> &str { "Roll table rows up." } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Rolls rows up", example: "[[a b]; [1 2] [3 4] [5 6]] | roll up", result: Some(Value::test_list(vec![ Value::test_record(record! { "a" => Value::test_int(3), "b" => Value::test_int(4), }), Value::test_record(record! { "a" => Value::test_int(5), "b" => Value::test_int(6), }), Value::test_record(record! { "a" => Value::test_int(1), "b" => Value::test_int(2), }), ])), }] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let by: Option<usize> = call.get_flag(engine_state, stack, "by")?; let metadata = input.metadata(); let value = input.into_value(call.head)?; let rotated_value = vertical_rotate_value(value, by, VerticalDirection::Up)?; Ok(rotated_value.into_pipeline_data().set_metadata(metadata)) } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(RollUp {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/filters/roll/roll_down.rs
crates/nu-cmd-extra/src/extra/filters/roll/roll_down.rs
use super::{VerticalDirection, vertical_rotate_value}; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct RollDown; impl Command for RollDown { fn name(&self) -> &str { "roll down" } fn search_terms(&self) -> Vec<&str> { vec!["rotate", "shift", "move", "row"] } fn signature(&self) -> Signature { Signature::build(self.name()) // TODO: It also operates on List .input_output_types(vec![(Type::table(), Type::table())]) .named("by", SyntaxShape::Int, "Number of rows to roll", Some('b')) .category(Category::Filters) } fn description(&self) -> &str { "Roll table rows down." } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Rolls rows down of a table", example: "[[a b]; [1 2] [3 4] [5 6]] | roll down", result: Some(Value::test_list(vec![ Value::test_record(record! { "a" => Value::test_int(5), "b" => Value::test_int(6), }), Value::test_record(record! { "a" => Value::test_int(1), "b" => Value::test_int(2), }), Value::test_record(record! { "a" => Value::test_int(3), "b" => Value::test_int(4), }), ])), }] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let by: Option<usize> = call.get_flag(engine_state, stack, "by")?; let metadata = input.metadata(); let value = input.into_value(call.head)?; let rotated_value = vertical_rotate_value(value, by, VerticalDirection::Down)?; Ok(rotated_value.into_pipeline_data().set_metadata(metadata)) } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(RollDown {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/filters/roll/mod.rs
crates/nu-cmd-extra/src/extra/filters/roll/mod.rs
mod roll_; mod roll_down; mod roll_left; mod roll_right; mod roll_up; use nu_protocol::{ShellError, Value}; pub use roll_::Roll; pub use roll_down::RollDown; pub use roll_left::RollLeft; pub use roll_right::RollRight; pub use roll_up::RollUp; enum VerticalDirection { Up, Down, } fn vertical_rotate_value( value: Value, by: Option<usize>, direction: VerticalDirection, ) -> Result<Value, ShellError> { let span = value.span(); match value { Value::List { mut vals, .. } => { let rotations = by.map(|n| n % vals.len()).unwrap_or(1); let values = vals.as_mut_slice(); match direction { VerticalDirection::Up => values.rotate_left(rotations), VerticalDirection::Down => values.rotate_right(rotations), } Ok(Value::list(values.to_owned(), span)) } _ => Err(ShellError::TypeMismatch { err_message: "list".to_string(), span: value.span(), }), } } enum HorizontalDirection { Left, Right, } fn horizontal_rotate_value( value: Value, by: Option<usize>, cells_only: bool, direction: &HorizontalDirection, ) -> Result<Value, ShellError> { let span = value.span(); match value { Value::Record { val: record, .. } => { let rotations = by.map(|n| n % record.len()).unwrap_or(1); let (mut cols, mut vals): (Vec<_>, Vec<_>) = record.into_owned().into_iter().unzip(); if !cells_only { match direction { HorizontalDirection::Right => cols.rotate_right(rotations), HorizontalDirection::Left => cols.rotate_left(rotations), } }; match direction { HorizontalDirection::Right => vals.rotate_right(rotations), HorizontalDirection::Left => vals.rotate_left(rotations), } let record = cols.into_iter().zip(vals).collect(); Ok(Value::record(record, span)) } Value::List { vals, .. } => { let values = vals .into_iter() .map(|value| horizontal_rotate_value(value, by, cells_only, direction)) .collect::<Result<Vec<Value>, ShellError>>()?; Ok(Value::list(values, span)) } _ => Err(ShellError::TypeMismatch { err_message: "record".to_string(), span: value.span(), }), } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/filters/roll/roll_.rs
crates/nu-cmd-extra/src/extra/filters/roll/roll_.rs
use nu_engine::{command_prelude::*, get_full_help}; #[derive(Clone)] pub struct Roll; impl Command for Roll { fn name(&self) -> &str { "roll" } fn search_terms(&self) -> Vec<&str> { vec!["rotate", "shift", "move"] } fn signature(&self) -> Signature { Signature::build(self.name()) .category(Category::Filters) .input_output_types(vec![(Type::Nothing, Type::String)]) } fn description(&self) -> &str { "Rolling commands for tables." } fn extra_description(&self) -> &str { "You must use one of the following subcommands. Using this command as-is will only produce this help message." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { Ok(Value::string(get_full_help(self, engine_state, stack), call.head).into_pipeline_data()) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/platform/mod.rs
crates/nu-cmd-extra/src/extra/platform/mod.rs
pub(crate) mod ansi;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/platform/ansi/mod.rs
crates/nu-cmd-extra/src/extra/platform/ansi/mod.rs
mod gradient; pub(crate) use gradient::SubCommand as Gradient;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/platform/ansi/gradient.rs
crates/nu-cmd-extra/src/extra/platform/ansi/gradient.rs
use nu_ansi_term::{Gradient, Rgb, build_all_gradient_text, gradient::TargetGround}; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct SubCommand; impl Command for SubCommand { fn name(&self) -> &str { "ansi gradient" } fn signature(&self) -> Signature { Signature::build("ansi gradient") .named( "fgstart", SyntaxShape::String, "foreground gradient start color in hex (0x123456)", Some('a'), ) .named( "fgend", SyntaxShape::String, "foreground gradient end color in hex", Some('b'), ) .named( "bgstart", SyntaxShape::String, "background gradient start color in hex", Some('c'), ) .named( "bgend", SyntaxShape::String, "background gradient end color in hex", Some('d'), ) .rest( "cell path", SyntaxShape::CellPath, "For a data structure input, add a gradient to strings at the given cell paths.", ) .input_output_types(vec![ (Type::String, Type::String), ( Type::List(Box::new(Type::String)), Type::List(Box::new(Type::String)), ), (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .allow_variants_without_examples(true) .category(Category::Platform) } fn description(&self) -> &str { "Add a color gradient (using ANSI color codes) to the given string." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { operate(engine_state, stack, call, input) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "draw text in a gradient with foreground start and end colors", example: "'Hello, Nushell! This is a gradient.' | ansi gradient --fgstart '0x40c9ff' --fgend '0xe81cff'", result: None, }, Example { description: "draw text in a gradient with foreground start and end colors and background start and end colors", example: "'Hello, Nushell! This is a gradient.' | ansi gradient --fgstart '0x40c9ff' --fgend '0xe81cff' --bgstart '0xe81cff' --bgend '0x40c9ff'", result: None, }, Example { description: "draw text in a gradient by specifying foreground start color - end color is assumed to be black", example: "'Hello, Nushell! This is a gradient.' | ansi gradient --fgstart '0x40c9ff'", result: None, }, Example { description: "draw text in a gradient by specifying foreground end color - start color is assumed to be black", example: "'Hello, Nushell! This is a gradient.' | ansi gradient --fgend '0xe81cff'", result: None, }, ] } } fn value_to_color(v: Option<Value>) -> Result<Option<Rgb>, ShellError> { let s = match v { None => return Ok(None), Some(x) => x.coerce_into_string()?, }; Ok(Some(Rgb::from_hex_string(s))) } fn operate( engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let fgstart: Option<Value> = call.get_flag(engine_state, stack, "fgstart")?; let fgend: Option<Value> = call.get_flag(engine_state, stack, "fgend")?; let bgstart: Option<Value> = call.get_flag(engine_state, stack, "bgstart")?; let bgend: Option<Value> = call.get_flag(engine_state, stack, "bgend")?; let column_paths: Vec<CellPath> = call.rest(engine_state, stack, 0)?; let fgs_hex = value_to_color(fgstart)?; let fge_hex = value_to_color(fgend)?; let bgs_hex = value_to_color(bgstart)?; let bge_hex = value_to_color(bgend)?; let head = call.head; input.map( move |v| { if column_paths.is_empty() { action(&v, fgs_hex, fge_hex, bgs_hex, bge_hex, head) } else { let mut ret = v; for path in &column_paths { let r = ret.update_cell_path( &path.members, Box::new(move |old| action(old, fgs_hex, fge_hex, bgs_hex, bge_hex, head)), ); if let Err(error) = r { return Value::error(error, head); } } ret } }, engine_state.signals(), ) } fn action( input: &Value, fg_start: Option<Rgb>, fg_end: Option<Rgb>, bg_start: Option<Rgb>, bg_end: Option<Rgb>, command_span: Span, ) -> Value { let span = input.span(); match input { Value::String { val, .. } => { match (fg_start, fg_end, bg_start, bg_end) { (None, None, None, None) => { // Error - no colors Value::error( ShellError::MissingParameter { param_name: "please supply foreground and/or background color parameters".into(), span: command_span, }, span, ) } (None, None, None, Some(bg_end)) => { // Error - missing bg_start, so assume black let bg_start = Rgb::new(0, 0, 0); let gradient = Gradient::new(bg_start, bg_end); let gradient_string = gradient.build(val, TargetGround::Background); Value::string(gradient_string, span) } (None, None, Some(bg_start), None) => { // Error - missing bg_end, so assume black let bg_end = Rgb::new(0, 0, 0); let gradient = Gradient::new(bg_start, bg_end); let gradient_string = gradient.build(val, TargetGround::Background); Value::string(gradient_string, span) } (None, None, Some(bg_start), Some(bg_end)) => { // Background Only let gradient = Gradient::new(bg_start, bg_end); let gradient_string = gradient.build(val, TargetGround::Background); Value::string(gradient_string, span) } (None, Some(fg_end), None, None) => { // Error - missing fg_start, so assume black let fg_start = Rgb::new(0, 0, 0); let gradient = Gradient::new(fg_start, fg_end); let gradient_string = gradient.build(val, TargetGround::Foreground); Value::string(gradient_string, span) } (None, Some(fg_end), None, Some(bg_end)) => { // missing fg_start and bg_start, so assume black let fg_start = Rgb::new(0, 0, 0); let bg_start = Rgb::new(0, 0, 0); let fg_gradient = Gradient::new(fg_start, fg_end); let bg_gradient = Gradient::new(bg_start, bg_end); let gradient_string = build_all_gradient_text(val, fg_gradient, bg_gradient); Value::string(gradient_string, span) } (None, Some(fg_end), Some(bg_start), None) => { // Error - missing fg_start and bg_end let fg_start = Rgb::new(0, 0, 0); let bg_end = Rgb::new(0, 0, 0); let fg_gradient = Gradient::new(fg_start, fg_end); let bg_gradient = Gradient::new(bg_start, bg_end); let gradient_string = build_all_gradient_text(val, fg_gradient, bg_gradient); Value::string(gradient_string, span) } (None, Some(fg_end), Some(bg_start), Some(bg_end)) => { // Error - missing fg_start, so assume black let fg_start = Rgb::new(0, 0, 0); let fg_gradient = Gradient::new(fg_start, fg_end); let bg_gradient = Gradient::new(bg_start, bg_end); let gradient_string = build_all_gradient_text(val, fg_gradient, bg_gradient); Value::string(gradient_string, span) } (Some(fg_start), None, None, None) => { // Error - missing fg_end, so assume black let fg_end = Rgb::new(0, 0, 0); let gradient = Gradient::new(fg_start, fg_end); let gradient_string = gradient.build(val, TargetGround::Foreground); Value::string(gradient_string, span) } (Some(fg_start), None, None, Some(bg_end)) => { // Error - missing fg_end, bg_start, so assume black let fg_end = Rgb::new(0, 0, 0); let bg_start = Rgb::new(0, 0, 0); let fg_gradient = Gradient::new(fg_start, fg_end); let bg_gradient = Gradient::new(bg_start, bg_end); let gradient_string = build_all_gradient_text(val, fg_gradient, bg_gradient); Value::string(gradient_string, span) } (Some(fg_start), None, Some(bg_start), None) => { // Error - missing fg_end, bg_end, so assume black let fg_end = Rgb::new(0, 0, 0); let bg_end = Rgb::new(0, 0, 0); let fg_gradient = Gradient::new(fg_start, fg_end); let bg_gradient = Gradient::new(bg_start, bg_end); let gradient_string = build_all_gradient_text(val, fg_gradient, bg_gradient); Value::string(gradient_string, span) } (Some(fg_start), None, Some(bg_start), Some(bg_end)) => { // Error - missing fg_end, so assume black let fg_end = Rgb::new(0, 0, 0); let fg_gradient = Gradient::new(fg_start, fg_end); let bg_gradient = Gradient::new(bg_start, bg_end); let gradient_string = build_all_gradient_text(val, fg_gradient, bg_gradient); Value::string(gradient_string, span) } (Some(fg_start), Some(fg_end), None, None) => { // Foreground Only let gradient = Gradient::new(fg_start, fg_end); let gradient_string = gradient.build(val, TargetGround::Foreground); Value::string(gradient_string, span) } (Some(fg_start), Some(fg_end), None, Some(bg_end)) => { // Error - missing bg_start, so assume black let bg_start = Rgb::new(0, 0, 0); let fg_gradient = Gradient::new(fg_start, fg_end); let bg_gradient = Gradient::new(bg_start, bg_end); let gradient_string = build_all_gradient_text(val, fg_gradient, bg_gradient); Value::string(gradient_string, span) } (Some(fg_start), Some(fg_end), Some(bg_start), None) => { // Error - missing bg_end, so assume black let bg_end = Rgb::new(0, 0, 0); let fg_gradient = Gradient::new(fg_start, fg_end); let bg_gradient = Gradient::new(bg_start, bg_end); let gradient_string = build_all_gradient_text(val, fg_gradient, bg_gradient); Value::string(gradient_string, span) } (Some(fg_start), Some(fg_end), Some(bg_start), Some(bg_end)) => { // Foreground and Background Gradient let fg_gradient = Gradient::new(fg_start, fg_end); let bg_gradient = Gradient::new(bg_start, bg_end); let gradient_string = build_all_gradient_text(val, fg_gradient, bg_gradient); Value::string(gradient_string, span) } } } other => { let got = format!("value is {}, not string", other.get_type()); Value::error( ShellError::TypeMismatch { err_message: got, span: other.span(), }, other.span(), ) } } } #[cfg(test)] mod tests { use super::{SubCommand, action}; use nu_ansi_term::Rgb; use nu_protocol::{Span, Value}; #[test] fn examples_work_as_expected() { use crate::test_examples; test_examples(SubCommand {}) } #[test] fn test_fg_gradient() { let input_string = Value::test_string("Hello, World!"); let expected = Value::test_string( "\u{1b}[38;2;64;201;255mH\u{1b}[38;2;76;187;254me\u{1b}[38;2;89;174;254ml\u{1b}[38;2;102;160;254ml\u{1b}[38;2;115;147;254mo\u{1b}[38;2;128;133;254m,\u{1b}[38;2;141;120;254m \u{1b}[38;2;153;107;254mW\u{1b}[38;2;166;94;254mo\u{1b}[38;2;179;80;254mr\u{1b}[38;2;192;67;254ml\u{1b}[38;2;205;53;254md\u{1b}[38;2;218;40;254m!\u{1b}[0m", ); let fg_start = Rgb::from_hex_string("0x40c9ff".to_string()); let fg_end = Rgb::from_hex_string("0xe81cff".to_string()); let actual = action( &input_string, Some(fg_start), Some(fg_end), None, None, Span::test_data(), ); assert_eq!(actual, expected); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/bits/xor.rs
crates/nu-cmd-extra/src/extra/bits/xor.rs
use super::binary_op; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct BitsXor; impl Command for BitsXor { fn name(&self) -> &str { "bits xor" } fn signature(&self) -> Signature { Signature::build("bits xor") .input_output_types(vec![ (Type::Int, Type::Int), (Type::Binary, Type::Binary), ( Type::List(Box::new(Type::Int)), Type::List(Box::new(Type::Int)), ), ( Type::List(Box::new(Type::Binary)), Type::List(Box::new(Type::Binary)), ), ]) .allow_variants_without_examples(true) .required( "target", SyntaxShape::OneOf(vec![SyntaxShape::Binary, SyntaxShape::Int]), "Right-hand side of the operation.", ) .named( "endian", SyntaxShape::String, "byte encode endian, available options: native(default), little, big", Some('e'), ) .category(Category::Bits) } fn description(&self) -> &str { "Performs bitwise xor for ints or binary values." } fn search_terms(&self) -> Vec<&str> { vec!["logic xor"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let target: Value = call.req(engine_state, stack, 0)?; let endian = call.get_flag::<Spanned<String>>(engine_state, stack, "endian")?; let little_endian = if let Some(endian) = endian { match endian.item.as_str() { "native" => cfg!(target_endian = "little"), "little" => true, "big" => false, _ => { return Err(ShellError::TypeMismatch { err_message: "Endian must be one of native, little, big".to_string(), span: endian.span, }); } } } else { cfg!(target_endian = "little") }; // This doesn't match explicit nulls if let PipelineData::Empty = input { return Err(ShellError::PipelineEmpty { dst_span: head }); } input.map( move |value| binary_op(&value, &target, little_endian, |(l, r)| l ^ r, head), engine_state.signals(), ) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Apply bits xor to two numbers", example: "2 | bits xor 2", result: Some(Value::test_int(0)), }, Example { description: "Apply bitwise xor to a list of numbers", example: "[8 3 2] | bits xor 2", result: Some(Value::test_list(vec![ Value::test_int(10), Value::test_int(1), Value::test_int(0), ])), }, Example { description: "Apply bitwise xor to binary data", example: "0x[ca fe] | bits xor 0x[ba be]", result: Some(Value::test_binary(vec![0x70, 0x40])), }, Example { description: "Apply bitwise xor to binary data of varying lengths with specified endianness", example: "0x[ca fe] | bits xor 0x[aa] --endian big", result: Some(Value::test_binary(vec![0xca, 0x54])), }, Example { description: "Apply bitwise xor to input binary data smaller than the operand", example: "0x[ff] | bits xor 0x[12 34 56] --endian little", result: Some(Value::test_binary(vec![0xed, 0x34, 0x56])), }, ] } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(BitsXor {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/bits/or.rs
crates/nu-cmd-extra/src/extra/bits/or.rs
use super::binary_op; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct BitsOr; impl Command for BitsOr { fn name(&self) -> &str { "bits or" } fn signature(&self) -> Signature { Signature::build("bits or") .input_output_types(vec![ (Type::Int, Type::Int), (Type::Binary, Type::Binary), ( Type::List(Box::new(Type::Int)), Type::List(Box::new(Type::Int)), ), ( Type::List(Box::new(Type::Binary)), Type::List(Box::new(Type::Binary)), ), ]) .allow_variants_without_examples(true) .required( "target", SyntaxShape::OneOf(vec![SyntaxShape::Binary, SyntaxShape::Int]), "Right-hand side of the operation.", ) .named( "endian", SyntaxShape::String, "byte encode endian, available options: native(default), little, big", Some('e'), ) .category(Category::Bits) } fn description(&self) -> &str { "Performs bitwise or for ints or binary values." } fn search_terms(&self) -> Vec<&str> { vec!["logic or"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let target: Value = call.req(engine_state, stack, 0)?; let endian = call.get_flag::<Spanned<String>>(engine_state, stack, "endian")?; let little_endian = if let Some(endian) = endian { match endian.item.as_str() { "native" => cfg!(target_endian = "little"), "little" => true, "big" => false, _ => { return Err(ShellError::TypeMismatch { err_message: "Endian must be one of native, little, big".to_string(), span: endian.span, }); } } } else { cfg!(target_endian = "little") }; // This doesn't match explicit nulls if let PipelineData::Empty = input { return Err(ShellError::PipelineEmpty { dst_span: head }); } input.map( move |value| binary_op(&value, &target, little_endian, |(l, r)| l | r, head), engine_state.signals(), ) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Apply bits or to two numbers", example: "2 | bits or 6", result: Some(Value::test_int(6)), }, Example { description: "Apply bitwise or to a list of numbers", example: "[8 3 2] | bits or 2", result: Some(Value::test_list(vec![ Value::test_int(10), Value::test_int(3), Value::test_int(2), ])), }, Example { description: "Apply bitwise or to binary data", example: "0x[88 cc] | bits or 0x[42 32]", result: Some(Value::test_binary(vec![0xca, 0xfe])), }, Example { description: "Apply bitwise or to binary data of varying lengths with specified endianness", example: "0x[c0 ff ee] | bits or 0x[ff] --endian big", result: Some(Value::test_binary(vec![0xc0, 0xff, 0xff])), }, Example { description: "Apply bitwise or to input binary data smaller than the operor", example: "0x[ff] | bits or 0x[12 34 56] --endian little", result: Some(Value::test_binary(vec![0xff, 0x34, 0x56])), }, ] } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(BitsOr {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/bits/rotate_right.rs
crates/nu-cmd-extra/src/extra/bits/rotate_right.rs
use super::{InputNumType, NumberBytes, get_input_num_type, get_number_bytes}; use nu_cmd_base::input_handler::{CmdArgument, operate}; use nu_engine::command_prelude::*; struct Arguments { signed: bool, bits: Spanned<usize>, number_size: NumberBytes, } impl CmdArgument for Arguments { fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> { None } } #[derive(Clone)] pub struct BitsRor; impl Command for BitsRor { fn name(&self) -> &str { "bits ror" } fn signature(&self) -> Signature { Signature::build("bits ror") .input_output_types(vec![ (Type::Int, Type::Int), (Type::Binary, Type::Binary), ( Type::List(Box::new(Type::Int)), Type::List(Box::new(Type::Int)), ), ( Type::List(Box::new(Type::Binary)), Type::List(Box::new(Type::Binary)), ), ]) .allow_variants_without_examples(true) .required("bits", SyntaxShape::Int, "Number of bits to rotate right.") .switch( "signed", "always treat input number as a signed number", Some('s'), ) .named( "number-bytes", SyntaxShape::Int, "the word size in number of bytes. Must be `1`, `2`, `4`, or `8` (defaults to the smallest of those that fits the input number)", Some('n'), ) .category(Category::Bits) } fn description(&self) -> &str { "Bitwise rotate right for ints or binary values." } fn search_terms(&self) -> Vec<&str> { vec!["rotate right"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let bits = call.req(engine_state, stack, 0)?; let signed = call.has_flag(engine_state, stack, "signed")?; let number_bytes: Option<Spanned<usize>> = call.get_flag(engine_state, stack, "number-bytes")?; let number_size = get_number_bytes(number_bytes, head)?; // This doesn't match explicit nulls if let PipelineData::Empty = input { return Err(ShellError::PipelineEmpty { dst_span: head }); } let args = Arguments { signed, number_size, bits, }; operate(action, args, input, head, engine_state.signals()) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "rotate right a number with 2 bits", example: "17 | bits ror 2", result: Some(Value::test_int(68)), }, Example { description: "rotate right a list of numbers of two bytes", example: "[15 33 92] | bits ror 2 --number-bytes 2", result: Some(Value::list( vec![ Value::test_int(49155), Value::test_int(16392), Value::test_int(23), ], Span::test_data(), )), }, Example { description: "rotate right binary data", example: "0x[ff bb 03] | bits ror 10", result: Some(Value::binary(vec![0xc0, 0xff, 0xee], Span::test_data())), }, ] } } fn action(input: &Value, args: &Arguments, span: Span) -> Value { let Arguments { signed, number_size, bits, } = *args; let bits_span = bits.span; let bits = bits.item; match input { Value::Int { val, .. } => { use InputNumType::*; let val = *val; let bits = bits as u32; let input_num_type = get_input_num_type(val, signed, number_size); if bits > input_num_type.num_bits() { return Value::error( ShellError::IncorrectValue { msg: format!( "Trying to rotate by more than the available bits ({})", input_num_type.num_bits() ), val_span: bits_span, call_span: span, }, span, ); } let int = match input_num_type { One => (val as u8).rotate_right(bits) as i64, Two => (val as u16).rotate_right(bits) as i64, Four => (val as u32).rotate_right(bits) as i64, Eight => { let Ok(i) = i64::try_from((val as u64).rotate_right(bits)) else { return Value::error( ShellError::GenericError { error: "result out of range for specified number".into(), msg: format!( "rotating right by {bits} is out of range for the value {val}" ), span: Some(span), help: None, inner: vec![], }, span, ); }; i } SignedOne => (val as i8).rotate_right(bits) as i64, SignedTwo => (val as i16).rotate_right(bits) as i64, SignedFour => (val as i32).rotate_right(bits) as i64, SignedEight => val.rotate_right(bits), }; Value::int(int, span) } Value::Binary { val, .. } => { let len = val.len(); if bits > len * 8 { return Value::error( ShellError::IncorrectValue { msg: format!( "Trying to rotate by more than the available bits ({})", len * 8 ), val_span: bits_span, call_span: span, }, span, ); } let byte_shift = bits / 8; let bit_rotate = bits % 8; let bytes = if bit_rotate == 0 { rotate_bytes_right(val, byte_shift) } else { rotate_bytes_and_bits_right(val, byte_shift, bit_rotate) }; Value::binary(bytes, span) } // Propagate errors by explicitly matching them before the final case. Value::Error { .. } => input.clone(), other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "int or binary".into(), wrong_type: other.get_type().to_string(), dst_span: span, src_span: other.span(), }, span, ), } } fn rotate_bytes_right(data: &[u8], byte_shift: usize) -> Vec<u8> { let len = data.len(); let mut output = vec![0; len]; output[byte_shift..].copy_from_slice(&data[..len - byte_shift]); output[..byte_shift].copy_from_slice(&data[len - byte_shift..]); output } fn rotate_bytes_and_bits_right(data: &[u8], byte_shift: usize, bit_shift: usize) -> Vec<u8> { debug_assert!(byte_shift < data.len()); debug_assert!( (1..8).contains(&bit_shift), "Bit shifts of 0 can't be handled by this impl and everything else should be part of the byteshift" ); let mut bytes = Vec::with_capacity(data.len()); let mut previous_index = data.len() - byte_shift - 1; for _ in 0..data.len() { let previous_byte = data[previous_index]; previous_index += 1; if previous_index == data.len() { previous_index = 0; } let curr_byte = data[previous_index]; let rotated_byte = (curr_byte >> bit_shift) | (previous_byte << (8 - bit_shift)); bytes.push(rotated_byte); } bytes } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(BitsRor {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/bits/shift_right.rs
crates/nu-cmd-extra/src/extra/bits/shift_right.rs
use super::{InputNumType, NumberBytes, get_input_num_type, get_number_bytes}; use nu_cmd_base::input_handler::{CmdArgument, operate}; use nu_engine::command_prelude::*; struct Arguments { signed: bool, bits: Spanned<usize>, number_size: NumberBytes, } impl CmdArgument for Arguments { fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> { None } } #[derive(Clone)] pub struct BitsShr; impl Command for BitsShr { fn name(&self) -> &str { "bits shr" } fn signature(&self) -> Signature { Signature::build("bits shr") .input_output_types(vec![ (Type::Int, Type::Int), (Type::Binary, Type::Binary), ( Type::List(Box::new(Type::Int)), Type::List(Box::new(Type::Int)), ), ( Type::List(Box::new(Type::Binary)), Type::List(Box::new(Type::Binary)), ), ]) .allow_variants_without_examples(true) .required("bits", SyntaxShape::Int, "Number of bits to shift right.") .switch( "signed", "always treat input number as a signed number", Some('s'), ) .named( "number-bytes", SyntaxShape::Int, "the word size in number of bytes. Must be `1`, `2`, `4`, or `8` (defaults to the smallest of those that fits the input number)", Some('n'), ) .category(Category::Bits) } fn description(&self) -> &str { "Bitwise shift right for ints or binary values." } fn search_terms(&self) -> Vec<&str> { vec!["shift right"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; // This restricts to a positive shift value (our underlying operations do not // permit them) let bits: Spanned<usize> = call.req(engine_state, stack, 0)?; let signed = call.has_flag(engine_state, stack, "signed")?; let number_bytes: Option<Spanned<usize>> = call.get_flag(engine_state, stack, "number-bytes")?; let number_size = get_number_bytes(number_bytes, head)?; // This doesn't match explicit nulls if let PipelineData::Empty = input { return Err(ShellError::PipelineEmpty { dst_span: head }); } let args = Arguments { signed, number_size, bits, }; operate(action, args, input, head, engine_state.signals()) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Shift right a number with 2 bits", example: "8 | bits shr 2", result: Some(Value::test_int(2)), }, Example { description: "Shift right a list of numbers", example: "[15 35 2] | bits shr 2", result: Some(Value::list( vec![Value::test_int(3), Value::test_int(8), Value::test_int(0)], Span::test_data(), )), }, Example { description: "Shift right a binary value", example: "0x[4f f4] | bits shr 4", result: Some(Value::binary(vec![0x04, 0xff], Span::test_data())), }, ] } } fn action(input: &Value, args: &Arguments, span: Span) -> Value { let Arguments { signed, number_size, bits, } = *args; let bits_span = bits.span; let bits = bits.item; match input { Value::Int { val, .. } => { use InputNumType::*; let val = *val; let bits = bits as u32; let input_num_type = get_input_num_type(val, signed, number_size); if !input_num_type.is_permitted_bit_shift(bits) { return Value::error( ShellError::IncorrectValue { msg: format!( "Trying to shift by more than the available bits (permitted < {})", input_num_type.num_bits() ), val_span: bits_span, call_span: span, }, span, ); } let int = match input_num_type { One => ((val as u8) >> bits) as i64, Two => ((val as u16) >> bits) as i64, Four => ((val as u32) >> bits) as i64, Eight => ((val as u64) >> bits) as i64, SignedOne => ((val as i8) >> bits) as i64, SignedTwo => ((val as i16) >> bits) as i64, SignedFour => ((val as i32) >> bits) as i64, SignedEight => val >> bits, }; Value::int(int, span) } Value::Binary { val, .. } => { let byte_shift = bits / 8; let bit_shift = bits % 8; let len = val.len(); // This check is done for symmetry with the int case and the previous // implementation would overflow byte indices leading to unexpected output // lengths if bits > len * 8 { return Value::error( ShellError::IncorrectValue { msg: format!( "Trying to shift by more than the available bits ({})", len * 8 ), val_span: bits_span, call_span: span, }, span, ); } let bytes = if bit_shift == 0 { shift_bytes_right(val, byte_shift) } else { shift_bytes_and_bits_right(val, byte_shift, bit_shift) }; Value::binary(bytes, span) } // Propagate errors by explicitly matching them before the final case. Value::Error { .. } => input.clone(), other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "int or binary".into(), wrong_type: other.get_type().to_string(), dst_span: span, src_span: other.span(), }, span, ), } } fn shift_bytes_right(data: &[u8], byte_shift: usize) -> Vec<u8> { let len = data.len(); let mut output = vec![0; len]; output[byte_shift..].copy_from_slice(&data[..len - byte_shift]); output } fn shift_bytes_and_bits_right(data: &[u8], byte_shift: usize, bit_shift: usize) -> Vec<u8> { debug_assert!( bit_shift > 0 && bit_shift < 8, "bit_shift should be in the range (0, 8)" ); let len = data.len(); let mut output = vec![0; len]; for i in byte_shift..len { let shifted_bits = data[i - byte_shift] >> bit_shift; let carried_bits = if i > byte_shift { data[i - byte_shift - 1] << (8 - bit_shift) } else { 0 }; let shifted_byte = shifted_bits | carried_bits; output[i] = shifted_byte; } output } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(BitsShr {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/bits/not.rs
crates/nu-cmd-extra/src/extra/bits/not.rs
use super::{NumberBytes, get_number_bytes}; use nu_cmd_base::input_handler::{CmdArgument, operate}; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct BitsNot; #[derive(Clone, Copy)] struct Arguments { signed: bool, number_size: NumberBytes, } impl CmdArgument for Arguments { fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> { None } } impl Command for BitsNot { fn name(&self) -> &str { "bits not" } fn signature(&self) -> Signature { Signature::build("bits not") .input_output_types(vec![ (Type::Int, Type::Int), (Type::Binary, Type::Binary), ( Type::List(Box::new(Type::Int)), Type::List(Box::new(Type::Int)), ), ( Type::List(Box::new(Type::Binary)), Type::List(Box::new(Type::Binary)), ), ]) .allow_variants_without_examples(true) .switch( "signed", "always treat input number as a signed number", Some('s'), ) .named( "number-bytes", SyntaxShape::Int, "the size of unsigned number in bytes, it can be 1, 2, 4, 8, auto", Some('n'), ) .category(Category::Bits) } fn description(&self) -> &str { "Performs logical negation on each bit." } fn search_terms(&self) -> Vec<&str> { vec!["negation"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let signed = call.has_flag(engine_state, stack, "signed")?; let number_bytes: Option<Spanned<usize>> = call.get_flag(engine_state, stack, "number-bytes")?; let number_size = get_number_bytes(number_bytes, head)?; // This doesn't match explicit nulls if let PipelineData::Empty = input { return Err(ShellError::PipelineEmpty { dst_span: head }); } let args = Arguments { signed, number_size, }; operate(action, args, input, head, engine_state.signals()) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Apply logical negation to a list of numbers", example: "[4 3 2] | bits not", result: Some(Value::list( vec![ Value::test_int(251), Value::test_int(252), Value::test_int(253), ], Span::test_data(), )), }, Example { description: "Apply logical negation to a list of numbers, treat input as 2 bytes number", example: "[4 3 2] | bits not --number-bytes 2", result: Some(Value::list( vec![ Value::test_int(65531), Value::test_int(65532), Value::test_int(65533), ], Span::test_data(), )), }, Example { description: "Apply logical negation to a list of numbers, treat input as signed number", example: "[4 3 2] | bits not --signed", result: Some(Value::list( vec![ Value::test_int(-5), Value::test_int(-4), Value::test_int(-3), ], Span::test_data(), )), }, Example { description: "Apply logical negation to binary data", example: "0x[ff 00 7f] | bits not", result: Some(Value::binary(vec![0x00, 0xff, 0x80], Span::test_data())), }, ] } } fn action(input: &Value, args: &Arguments, span: Span) -> Value { let Arguments { signed, number_size, } = *args; match input { Value::Int { val, .. } => { let val = *val; if signed || val < 0 { Value::int(!val, span) } else { use NumberBytes::*; let out_val = match number_size { One => !val & 0x00_00_00_00_00_FF, Two => !val & 0x00_00_00_00_FF_FF, Four => !val & 0x00_00_FF_FF_FF_FF, Eight => !val & 0x7F_FF_FF_FF_FF_FF, Auto => { if val <= 0xFF { !val & 0x00_00_00_00_00_FF } else if val <= 0xFF_FF { !val & 0x00_00_00_00_FF_FF } else if val <= 0xFF_FF_FF_FF { !val & 0x00_00_FF_FF_FF_FF } else { !val & 0x7F_FF_FF_FF_FF_FF } } }; Value::int(out_val, span) } } Value::Binary { val, .. } => { Value::binary(val.iter().copied().map(|b| !b).collect::<Vec<_>>(), span) } // Propagate errors by explicitly matching them before the final case. Value::Error { .. } => input.clone(), other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "int or binary".into(), wrong_type: other.get_type().to_string(), dst_span: other.span(), src_span: span, }, span, ), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(BitsNot {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/bits/rotate_left.rs
crates/nu-cmd-extra/src/extra/bits/rotate_left.rs
use super::{InputNumType, NumberBytes, get_input_num_type, get_number_bytes}; use nu_cmd_base::input_handler::{CmdArgument, operate}; use nu_engine::command_prelude::*; struct Arguments { signed: bool, bits: Spanned<usize>, number_size: NumberBytes, } impl CmdArgument for Arguments { fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> { None } } #[derive(Clone)] pub struct BitsRol; impl Command for BitsRol { fn name(&self) -> &str { "bits rol" } fn signature(&self) -> Signature { Signature::build("bits rol") .input_output_types(vec![ (Type::Int, Type::Int), (Type::Binary, Type::Binary), ( Type::List(Box::new(Type::Int)), Type::List(Box::new(Type::Int)), ), ( Type::List(Box::new(Type::Binary)), Type::List(Box::new(Type::Binary)), ), ]) .allow_variants_without_examples(true) .required("bits", SyntaxShape::Int, "Number of bits to rotate left.") .switch( "signed", "always treat input number as a signed number", Some('s'), ) .named( "number-bytes", SyntaxShape::Int, "the word size in number of bytes. Must be `1`, `2`, `4`, or `8` (defaults to the smallest of those that fits the input number)", Some('n'), ) .category(Category::Bits) } fn description(&self) -> &str { "Bitwise rotate left for ints or binary values." } fn search_terms(&self) -> Vec<&str> { vec!["rotate left"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let bits = call.req(engine_state, stack, 0)?; let signed = call.has_flag(engine_state, stack, "signed")?; let number_bytes: Option<Spanned<usize>> = call.get_flag(engine_state, stack, "number-bytes")?; let number_size = get_number_bytes(number_bytes, head)?; // This doesn't match explicit nulls if let PipelineData::Empty = input { return Err(ShellError::PipelineEmpty { dst_span: head }); } let args = Arguments { signed, number_size, bits, }; operate(action, args, input, head, engine_state.signals()) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Rotate left a number with 2 bits", example: "17 | bits rol 2", result: Some(Value::test_int(68)), }, Example { description: "Rotate left a list of numbers with 2 bits", example: "[5 3 2] | bits rol 2", result: Some(Value::list( vec![Value::test_int(20), Value::test_int(12), Value::test_int(8)], Span::test_data(), )), }, Example { description: "rotate left binary data", example: "0x[c0 ff ee] | bits rol 10", result: Some(Value::binary(vec![0xff, 0xbb, 0x03], Span::test_data())), }, ] } } fn action(input: &Value, args: &Arguments, span: Span) -> Value { let Arguments { signed, number_size, bits, } = *args; let bits_span = bits.span; let bits = bits.item; match input { Value::Int { val, .. } => { use InputNumType::*; let val = *val; let bits = bits as u32; let input_num_type = get_input_num_type(val, signed, number_size); if bits > input_num_type.num_bits() { return Value::error( ShellError::IncorrectValue { msg: format!( "Trying to rotate by more than the available bits ({})", input_num_type.num_bits() ), val_span: bits_span, call_span: span, }, span, ); } let int = match input_num_type { One => (val as u8).rotate_left(bits) as i64, Two => (val as u16).rotate_left(bits) as i64, Four => (val as u32).rotate_left(bits) as i64, Eight => { let Ok(i) = i64::try_from((val as u64).rotate_left(bits)) else { return Value::error( ShellError::GenericError { error: "result out of range for specified number".into(), msg: format!( "rotating left by {bits} is out of range for the value {val}" ), span: Some(span), help: None, inner: vec![], }, span, ); }; i } SignedOne => (val as i8).rotate_left(bits) as i64, SignedTwo => (val as i16).rotate_left(bits) as i64, SignedFour => (val as i32).rotate_left(bits) as i64, SignedEight => val.rotate_left(bits), }; Value::int(int, span) } Value::Binary { val, .. } => { let len = val.len(); if bits > len * 8 { return Value::error( ShellError::IncorrectValue { msg: format!( "Trying to rotate by more than the available bits ({})", len * 8 ), val_span: bits_span, call_span: span, }, span, ); } let byte_shift = bits / 8; let bit_rotate = bits % 8; let bytes = if bit_rotate == 0 { rotate_bytes_left(val, byte_shift) } else { rotate_bytes_and_bits_left(val, byte_shift, bit_rotate) }; Value::binary(bytes, span) } // Propagate errors by explicitly matching them before the final case. Value::Error { .. } => input.clone(), other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "int or binary".into(), wrong_type: other.get_type().to_string(), dst_span: span, src_span: other.span(), }, span, ), } } fn rotate_bytes_left(data: &[u8], byte_shift: usize) -> Vec<u8> { let len = data.len(); let mut output = vec![0; len]; output[..len - byte_shift].copy_from_slice(&data[byte_shift..]); output[len - byte_shift..].copy_from_slice(&data[..byte_shift]); output } fn rotate_bytes_and_bits_left(data: &[u8], byte_shift: usize, bit_shift: usize) -> Vec<u8> { debug_assert!(byte_shift < data.len()); debug_assert!( (1..8).contains(&bit_shift), "Bit shifts of 0 can't be handled by this impl and everything else should be part of the byteshift" ); let mut bytes = Vec::with_capacity(data.len()); let mut next_index = byte_shift; for _ in 0..data.len() { let curr_byte = data[next_index]; next_index += 1; if next_index == data.len() { next_index = 0; } let next_byte = data[next_index]; let new_byte = (curr_byte << bit_shift) | (next_byte >> (8 - bit_shift)); bytes.push(new_byte); } bytes } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(BitsRol {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/bits/mod.rs
crates/nu-cmd-extra/src/extra/bits/mod.rs
mod and; mod bits_; mod not; mod or; mod rotate_left; mod rotate_right; mod shift_left; mod shift_right; mod xor; pub use and::BitsAnd; pub use bits_::Bits; pub use not::BitsNot; pub use or::BitsOr; pub use rotate_left::BitsRol; pub use rotate_right::BitsRor; pub use shift_left::BitsShl; pub use shift_right::BitsShr; pub use xor::BitsXor; use nu_protocol::{ShellError, Span, Spanned, Value}; use std::iter; #[derive(Clone, Copy)] enum NumberBytes { One, Two, Four, Eight, Auto, } #[derive(Clone, Copy)] enum InputNumType { One, Two, Four, Eight, SignedOne, SignedTwo, SignedFour, SignedEight, } impl InputNumType { fn num_bits(self) -> u32 { match self { InputNumType::One => 8, InputNumType::Two => 16, InputNumType::Four => 32, InputNumType::Eight => 64, InputNumType::SignedOne => 8, InputNumType::SignedTwo => 16, InputNumType::SignedFour => 32, InputNumType::SignedEight => 64, } } fn is_permitted_bit_shift(self, bits: u32) -> bool { bits < self.num_bits() } } fn get_number_bytes( number_bytes: Option<Spanned<usize>>, head: Span, ) -> Result<NumberBytes, ShellError> { match number_bytes { None => Ok(NumberBytes::Auto), Some(Spanned { item: 1, .. }) => Ok(NumberBytes::One), Some(Spanned { item: 2, .. }) => Ok(NumberBytes::Two), Some(Spanned { item: 4, .. }) => Ok(NumberBytes::Four), Some(Spanned { item: 8, .. }) => Ok(NumberBytes::Eight), Some(Spanned { span, .. }) => Err(ShellError::UnsupportedInput { msg: "Only 1, 2, 4, or 8 bytes are supported as word sizes".to_string(), input: "value originates from here".to_string(), msg_span: head, input_span: span, }), } } fn get_input_num_type(val: i64, signed: bool, number_size: NumberBytes) -> InputNumType { if signed || val < 0 { match number_size { NumberBytes::One => InputNumType::SignedOne, NumberBytes::Two => InputNumType::SignedTwo, NumberBytes::Four => InputNumType::SignedFour, NumberBytes::Eight => InputNumType::SignedEight, NumberBytes::Auto => { if val <= 0x7F && val >= -(2i64.pow(7)) { InputNumType::SignedOne } else if val <= 0x7FFF && val >= -(2i64.pow(15)) { InputNumType::SignedTwo } else if val <= 0x7FFFFFFF && val >= -(2i64.pow(31)) { InputNumType::SignedFour } else { InputNumType::SignedEight } } } } else { match number_size { NumberBytes::One => InputNumType::One, NumberBytes::Two => InputNumType::Two, NumberBytes::Four => InputNumType::Four, NumberBytes::Eight => InputNumType::Eight, NumberBytes::Auto => { if val <= 0xFF { InputNumType::One } else if val <= 0xFFFF { InputNumType::Two } else if val <= 0xFFFFFFFF { InputNumType::Four } else { InputNumType::Eight } } } } } fn binary_op<F>(lhs: &Value, rhs: &Value, little_endian: bool, f: F, head: Span) -> Value where F: Fn((i64, i64)) -> i64, { let span = lhs.span(); match (lhs, rhs) { (Value::Int { val: lhs, .. }, Value::Int { val: rhs, .. }) => { Value::int(f((*lhs, *rhs)), span) } (Value::Binary { val: lhs, .. }, Value::Binary { val: rhs, .. }) => { let (lhs, rhs, max_len, min_len) = match (lhs.len(), rhs.len()) { (max, min) if max > min => (lhs, rhs, max, min), (min, max) => (rhs, lhs, max, min), }; let pad = iter::repeat_n(0, max_len - min_len); let mut a; let mut b; let padded: &mut dyn Iterator<Item = u8> = if little_endian { a = rhs.iter().copied().chain(pad); &mut a } else { b = pad.chain(rhs.iter().copied()); &mut b }; let bytes: Vec<u8> = lhs .iter() .copied() .zip(padded) .map(|(lhs, rhs)| f((lhs as i64, rhs as i64)) as u8) .collect(); Value::binary(bytes, span) } (Value::Binary { .. }, Value::Int { .. }) | (Value::Int { .. }, Value::Binary { .. }) => { Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "input, and argument, to be both int or both binary" .to_string(), wrong_type: "int and binary".to_string(), dst_span: rhs.span(), src_span: span, }, span, ) } // Propagate errors by explicitly matching them before the final case. (e @ Value::Error { .. }, _) | (_, e @ Value::Error { .. }) => e.clone(), (other, Value::Int { .. } | Value::Binary { .. }) | (_, other) => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "int or binary".into(), wrong_type: other.get_type().to_string(), dst_span: head, src_span: other.span(), }, span, ), } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/bits/bits_.rs
crates/nu-cmd-extra/src/extra/bits/bits_.rs
use nu_engine::{command_prelude::*, get_full_help}; #[derive(Clone)] pub struct Bits; impl Command for Bits { fn name(&self) -> &str { "bits" } fn signature(&self) -> Signature { Signature::build("bits") .category(Category::Bits) .input_output_types(vec![(Type::Nothing, Type::String)]) } fn description(&self) -> &str { "Various commands for working with bits." } fn extra_description(&self) -> &str { "You must use one of the following subcommands. Using this command as-is will only produce this help message." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { Ok(Value::string(get_full_help(self, engine_state, stack), call.head).into_pipeline_data()) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/bits/shift_left.rs
crates/nu-cmd-extra/src/extra/bits/shift_left.rs
use super::{InputNumType, NumberBytes, get_input_num_type, get_number_bytes}; use itertools::Itertools; use nu_cmd_base::input_handler::{CmdArgument, operate}; use nu_engine::command_prelude::*; use std::iter; struct Arguments { signed: bool, bits: Spanned<usize>, number_size: NumberBytes, } impl CmdArgument for Arguments { fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> { None } } #[derive(Clone)] pub struct BitsShl; impl Command for BitsShl { fn name(&self) -> &str { "bits shl" } fn signature(&self) -> Signature { Signature::build("bits shl") .input_output_types(vec![ (Type::Int, Type::Int), (Type::Binary, Type::Binary), ( Type::List(Box::new(Type::Int)), Type::List(Box::new(Type::Int)), ), ( Type::List(Box::new(Type::Binary)), Type::List(Box::new(Type::Binary)), ), ]) .allow_variants_without_examples(true) .required("bits", SyntaxShape::Int, "Number of bits to shift left.") .switch( "signed", "always treat input number as a signed number", Some('s'), ) .named( "number-bytes", SyntaxShape::Int, "the word size in number of bytes. Must be `1`, `2`, `4`, or `8` (defaults to the smallest of those that fits the input number)", Some('n'), ) .category(Category::Bits) } fn description(&self) -> &str { "Bitwise shift left for ints or binary values." } fn search_terms(&self) -> Vec<&str> { vec!["shift left"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; // This restricts to a positive shift value (our underlying operations do not // permit them) let bits: Spanned<usize> = call.req(engine_state, stack, 0)?; let signed = call.has_flag(engine_state, stack, "signed")?; let number_bytes: Option<Spanned<usize>> = call.get_flag(engine_state, stack, "number-bytes")?; let number_size = get_number_bytes(number_bytes, head)?; // This doesn't match explicit nulls if let PipelineData::Empty = input { return Err(ShellError::PipelineEmpty { dst_span: head }); } let args = Arguments { signed, number_size, bits, }; operate(action, args, input, head, engine_state.signals()) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Shift left a number by 7 bits", example: "2 | bits shl 7", result: Some(Value::test_int(0)), }, Example { description: "Shift left a number with 2 byte by 7 bits", example: "2 | bits shl 7 --number-bytes 2", result: Some(Value::test_int(256)), }, Example { description: "Shift left a signed number by 1 bit", example: "0x7F | bits shl 1 --signed", result: Some(Value::test_int(-2)), }, Example { description: "Shift left a list of numbers", example: "[5 3 2] | bits shl 2", result: Some(Value::list( vec![Value::test_int(20), Value::test_int(12), Value::test_int(8)], Span::test_data(), )), }, Example { description: "Shift left a binary value", example: "0x[4f f4] | bits shl 4", result: Some(Value::binary(vec![0xff, 0x40], Span::test_data())), }, ] } } fn action(input: &Value, args: &Arguments, span: Span) -> Value { let Arguments { signed, number_size, bits, } = *args; let bits_span = bits.span; let bits = bits.item; match input { Value::Int { val, .. } => { use InputNumType::*; let val = *val; let bits = bits as u32; let input_num_type = get_input_num_type(val, signed, number_size); if !input_num_type.is_permitted_bit_shift(bits) { return Value::error( ShellError::IncorrectValue { msg: format!( "Trying to shift by more than the available bits (permitted < {})", input_num_type.num_bits() ), val_span: bits_span, call_span: span, }, span, ); } let int = match input_num_type { One => ((val as u8) << bits) as i64, Two => ((val as u16) << bits) as i64, Four => ((val as u32) << bits) as i64, Eight => { let Ok(i) = i64::try_from((val as u64) << bits) else { return Value::error( ShellError::GenericError { error: "result out of range for int".into(), msg: format!( "shifting left by {bits} is out of range for the value {val}" ), span: Some(span), help: Some( "Ensure the result fits in a 64-bit signed integer.".into(), ), inner: vec![], }, span, ); }; i } SignedOne => ((val as i8) << bits) as i64, SignedTwo => ((val as i16) << bits) as i64, SignedFour => ((val as i32) << bits) as i64, SignedEight => val << bits, }; Value::int(int, span) } Value::Binary { val, .. } => { let byte_shift = bits / 8; let bit_shift = bits % 8; // This is purely for symmetry with the int case and the fact that the // shift right implementation in its current form panicked with an overflow if bits > val.len() * 8 { return Value::error( ShellError::IncorrectValue { msg: format!( "Trying to shift by more than the available bits ({})", val.len() * 8 ), val_span: bits_span, call_span: span, }, span, ); } let bytes = if bit_shift == 0 { shift_bytes_left(val, byte_shift) } else { shift_bytes_and_bits_left(val, byte_shift, bit_shift) }; Value::binary(bytes, span) } // Propagate errors by explicitly matching them before the final case. Value::Error { .. } => input.clone(), other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "int or binary".into(), wrong_type: other.get_type().to_string(), dst_span: span, src_span: other.span(), }, span, ), } } fn shift_bytes_left(data: &[u8], byte_shift: usize) -> Vec<u8> { let len = data.len(); let mut output = vec![0; len]; output[..len - byte_shift].copy_from_slice(&data[byte_shift..]); output } fn shift_bytes_and_bits_left(data: &[u8], byte_shift: usize, bit_shift: usize) -> Vec<u8> { use itertools::Position::*; debug_assert!( (1..8).contains(&bit_shift), "Bit shifts of 0 can't be handled by this impl and everything else should be part of the byteshift" ); data.iter() .copied() .skip(byte_shift) .circular_tuple_windows::<(u8, u8)>() .with_position() .map(|(pos, (lhs, rhs))| match pos { Last | Only => lhs << bit_shift, _ => (lhs << bit_shift) | (rhs >> (8 - bit_shift)), }) .chain(iter::repeat_n(0, byte_shift)) .collect::<Vec<u8>>() } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(BitsShl {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/src/extra/bits/and.rs
crates/nu-cmd-extra/src/extra/bits/and.rs
use super::binary_op; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct BitsAnd; impl Command for BitsAnd { fn name(&self) -> &str { "bits and" } fn signature(&self) -> Signature { Signature::build("bits and") .input_output_types(vec![ (Type::Int, Type::Int), (Type::Binary, Type::Binary), ( Type::List(Box::new(Type::Int)), Type::List(Box::new(Type::Int)), ), ( Type::List(Box::new(Type::Binary)), Type::List(Box::new(Type::Binary)), ), ]) .required( "target", SyntaxShape::OneOf(vec![SyntaxShape::Binary, SyntaxShape::Int]), "Right-hand side of the operation.", ) .named( "endian", SyntaxShape::String, "byte encode endian, available options: native(default), little, big", Some('e'), ) .category(Category::Bits) } fn description(&self) -> &str { "Performs bitwise and for ints or binary values." } fn search_terms(&self) -> Vec<&str> { vec!["logic and"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let target: Value = call.req(engine_state, stack, 0)?; let endian = call.get_flag::<Spanned<String>>(engine_state, stack, "endian")?; let little_endian = if let Some(endian) = endian { match endian.item.as_str() { "native" => cfg!(target_endian = "little"), "little" => true, "big" => false, _ => { return Err(ShellError::TypeMismatch { err_message: "Endian must be one of native, little, big".to_string(), span: endian.span, }); } } } else { cfg!(target_endian = "little") }; // This doesn't match explicit nulls if let PipelineData::Empty = input { return Err(ShellError::PipelineEmpty { dst_span: head }); } input.map( move |value| binary_op(&value, &target, little_endian, |(l, r)| l & r, head), engine_state.signals(), ) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Apply bitwise and to two numbers", example: "2 | bits and 2", result: Some(Value::test_int(2)), }, Example { description: "Apply bitwise and to two binary values", example: "0x[ab cd] | bits and 0x[99 99]", result: Some(Value::test_binary([0x89, 0x89])), }, Example { description: "Apply bitwise and to a list of numbers", example: "[4 3 2] | bits and 2", result: Some(Value::test_list(vec![ Value::test_int(0), Value::test_int(2), Value::test_int(2), ])), }, Example { description: "Apply bitwise and to a list of binary data", example: "[0x[7f ff] 0x[ff f0]] | bits and 0x[99 99]", result: Some(Value::test_list(vec![ Value::test_binary([0x19, 0x99]), Value::test_binary([0x99, 0x90]), ])), }, Example { description: "Apply bitwise and to binary data of varying lengths with specified endianness", example: "0x[c0 ff ee] | bits and 0x[ff] --endian big", result: Some(Value::test_binary(vec![0x00, 0x00, 0xee])), }, Example { description: "Apply bitwise and to input binary data smaller than the operand", example: "0x[ff] | bits and 0x[12 34 56] --endian little", result: Some(Value::test_binary(vec![0x12, 0x00, 0x00])), }, ] } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(BitsAnd {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/tests/main.rs
crates/nu-cmd-extra/tests/main.rs
mod commands;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/tests/commands/mod.rs
crates/nu-cmd-extra/tests/commands/mod.rs
mod bits; mod bytes;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/tests/commands/bytes/starts_with.rs
crates/nu-cmd-extra/tests/commands/bytes/starts_with.rs
use nu_test_support::nu; #[test] fn basic_binary_starts_with() { let actual = nu!(r#" "hello world" | into binary | bytes starts-with 0x[68 65 6c 6c 6f] "#); assert_eq!(actual.out, "true"); } #[test] fn basic_string_fails() { let actual = nu!(r#" "hello world" | bytes starts-with 0x[68 65 6c 6c 6f] "#); assert!(actual.err.contains("command doesn't support")); assert_eq!(actual.out, ""); } #[test] fn short_stream_binary() { let actual = nu!(r#" nu --testbin repeater (0x[01]) 5 | bytes starts-with 0x[010101] "#); assert_eq!(actual.out, "true"); } #[test] fn short_stream_mismatch() { let actual = nu!(r#" nu --testbin repeater (0x[010203]) 5 | bytes starts-with 0x[010204] "#); assert_eq!(actual.out, "false"); } #[test] fn short_stream_binary_overflow() { let actual = nu!(r#" nu --testbin repeater (0x[01]) 5 | bytes starts-with 0x[010101010101] "#); assert_eq!(actual.out, "false"); } #[test] fn long_stream_binary() { let actual = nu!(r#" nu --testbin repeater (0x[01]) 32768 | bytes starts-with 0x[010101] "#); assert_eq!(actual.out, "true"); } #[test] fn long_stream_binary_overflow() { // .. ranges are inclusive..inclusive, so we don't need to +1 to check for an overflow let actual = nu!(r#" nu --testbin repeater (0x[01]) 32768 | bytes starts-with (0..32768 | each {|| 0x[01] } | bytes collect) "#); assert_eq!(actual.out, "false"); } #[test] fn long_stream_binary_exact() { // ranges are inclusive..inclusive, so we don't need to +1 to check for an overflow let actual = nu!(r#" nu --testbin repeater (0x[01020304]) 8192 | bytes starts-with (0..<8192 | each {|| 0x[01020304] } | bytes collect) "#); assert_eq!(actual.out, "true"); } #[test] fn long_stream_string_exact() { // ranges are inclusive..inclusive, so we don't need to +1 to check for an overflow let actual = nu!(r#" nu --testbin repeater hell 8192 | bytes starts-with (0..<8192 | each {|| "hell" | into binary } | bytes collect) "#); assert_eq!(actual.out, "true"); } #[test] fn long_stream_mixed_exact() { // ranges are inclusive..inclusive, so we don't need to +1 to check for an overflow let actual = nu!(r#" let binseg = (0..<2048 | each {|| 0x[003d9fbf] } | bytes collect) let strseg = (0..<2048 | each {|| "hell" | into binary } | bytes collect) nu --testbin repeat_bytes 003d9fbf 2048 68656c6c 2048 | bytes starts-with (bytes build $binseg $strseg) "#); assert_eq!( actual.err, "", "invocation failed. command line limit likely reached" ); assert_eq!(actual.out, "true"); } #[test] fn long_stream_mixed_overflow() { // ranges are inclusive..inclusive, so we don't need to +1 to check for an overflow let actual = nu!(r#" let binseg = (0..<2048 | each {|| 0x[003d9fbf] } | bytes collect) let strseg = (0..<2048 | each {|| "hell" | into binary } | bytes collect) nu --testbin repeat_bytes 003d9fbf 2048 68656c6c 2048 | bytes starts-with (bytes build $binseg $strseg 0x[01]) "#); assert_eq!( actual.err, "", "invocation failed. command line limit likely reached" ); assert_eq!(actual.out, "false"); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/tests/commands/bytes/mod.rs
crates/nu-cmd-extra/tests/commands/bytes/mod.rs
mod ends_with; mod starts_with;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/tests/commands/bytes/ends_with.rs
crates/nu-cmd-extra/tests/commands/bytes/ends_with.rs
use nu_test_support::nu; #[test] fn basic_binary_end_with() { let actual = nu!(r#" "hello world" | into binary | bytes ends-with 0x[77 6f 72 6c 64] "#); assert_eq!(actual.out, "true"); } #[test] fn basic_string_fails() { let actual = nu!(r#" "hello world" | bytes ends-with 0x[77 6f 72 6c 64] "#); assert!(actual.err.contains("command doesn't support")); assert_eq!(actual.out, ""); } #[test] fn short_stream_binary() { let actual = nu!(r#" nu --testbin repeater (0x[01]) 5 | bytes ends-with 0x[010101] "#); assert_eq!(actual.out, "true"); } #[test] fn short_stream_mismatch() { let actual = nu!(r#" nu --testbin repeater (0x[010203]) 5 | bytes ends-with 0x[010204] "#); assert_eq!(actual.out, "false"); } #[test] fn short_stream_binary_overflow() { let actual = nu!(r#" nu --testbin repeater (0x[01]) 5 | bytes ends-with 0x[010101010101] "#); assert_eq!(actual.out, "false"); } #[test] fn long_stream_binary() { let actual = nu!(r#" nu --testbin repeater (0x[01]) 32768 | bytes ends-with 0x[010101] "#); assert_eq!(actual.out, "true"); } #[test] fn long_stream_binary_overflow() { // .. ranges are inclusive..inclusive, so we don't need to +1 to check for an overflow let actual = nu!(r#" nu --testbin repeater (0x[01]) 32768 | bytes ends-with (0..32768 | each {|| 0x[01] } | bytes collect) "#); assert_eq!(actual.out, "false"); } #[test] fn long_stream_binary_exact() { // ranges are inclusive..inclusive, so we don't need to +1 to check for an overflow let actual = nu!(r#" nu --testbin repeater (0x[01020304]) 8192 | bytes ends-with (0..<8192 | each {|| 0x[01020304] } | bytes collect) "#); assert_eq!(actual.out, "true"); } #[test] fn long_stream_string_exact() { // ranges are inclusive..inclusive, so we don't need to +1 to check for an overflow let actual = nu!(r#" nu --testbin repeater hell 8192 | bytes ends-with (0..<8192 | each {|| "hell" | into binary } | bytes collect) "#); assert_eq!(actual.out, "true"); } #[test] fn long_stream_mixed_exact() { // ranges are inclusive..inclusive, so we don't need to +1 to check for an overflow let actual = nu!(r#" let binseg = (0..<2048 | each {|| 0x[003d9fbf] } | bytes collect) let strseg = (0..<2048 | each {|| "hell" | into binary } | bytes collect) nu --testbin repeat_bytes 003d9fbf 2048 68656c6c 2048 | bytes ends-with (bytes build $binseg $strseg) "#); assert_eq!( actual.err, "", "invocation failed. command line limit likely reached" ); assert_eq!(actual.out, "true"); } #[test] fn long_stream_mixed_overflow() { // ranges are inclusive..inclusive, so we don't need to +1 to check for an overflow let actual = nu!(r#" let binseg = (0..<2048 | each {|| 0x[003d9fbf] } | bytes collect) let strseg = (0..<2048 | each {|| "hell" | into binary } | bytes collect) nu --testbin repeat_bytes 003d9fbf 2048 68656c6c 2048 | bytes ends-with (bytes build 0x[01] $binseg $strseg) "#); assert_eq!( actual.err, "", "invocation failed. command line limit likely reached" ); assert_eq!(actual.out, "false"); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/tests/commands/bits/mod.rs
crates/nu-cmd-extra/tests/commands/bits/mod.rs
mod format;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-extra/tests/commands/bits/format.rs
crates/nu-cmd-extra/tests/commands/bits/format.rs
use nu_test_support::nu; #[test] fn byte_stream_into_bits() { let result = nu!("[0x[01] 0x[02 03]] | bytes collect | format bits"); assert_eq!("00000001 00000010 00000011", result.out); } #[test] fn byte_stream_into_bits_is_stream() { let result = nu!("[0x[01] 0x[02 03]] | bytes collect | format bits | describe"); assert_eq!("string (stream)", result.out); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nuon/src/from.rs
crates/nuon/src/from.rs
use nu_protocol::{ Filesize, IntoValue, Range, Record, ShellError, Span, Type, Unit, Value, ast::{Expr, Expression, ListItem, RecordItem}, engine::{EngineState, StateWorkingSet}, }; use std::sync::Arc; /// convert a raw string representation of NUON data to an actual Nushell [`Value`] /// // WARNING: please leave the following two trailing spaces, they matter for the documentation // formatting /// > **Note** /// > [`Span`] can be passed to [`from_nuon`] if there is context available to the caller, e.g. when /// > using this function in a command implementation such as /// > [`from nuon`](https://www.nushell.sh/commands/docs/from_nuon.html). /// /// also see [`super::to_nuon`] for the inverse operation pub fn from_nuon(input: &str, span: Option<Span>) -> Result<Value, ShellError> { let mut engine_state = EngineState::default(); // NOTE: the parser needs `$env.PWD` to be set, that's a know _API issue_ with the // [`EngineState`] engine_state.add_env_var("PWD".to_string(), Value::string("", Span::unknown())); let mut working_set = StateWorkingSet::new(&engine_state); let mut block = nu_parser::parse(&mut working_set, None, input.as_bytes(), false); if let Some(pipeline) = block.pipelines.get(1) { if let Some(element) = pipeline.elements.first() { return Err(ShellError::GenericError { error: "error when loading nuon text".into(), msg: "could not load nuon text".into(), span, help: None, inner: vec![ShellError::OutsideSpannedLabeledError { src: input.to_string(), error: "error when loading".into(), msg: "excess values when loading".into(), span: element.expr.span, }], }); } else { return Err(ShellError::GenericError { error: "error when loading nuon text".into(), msg: "could not load nuon text".into(), span, help: None, inner: vec![ShellError::GenericError { error: "error when loading".into(), msg: "excess values when loading".into(), span, help: None, inner: vec![], }], }); } } let expr = if block.pipelines.is_empty() { Expression::new( &mut working_set, Expr::Nothing, span.unwrap_or(Span::unknown()), Type::Nothing, ) } else { let mut pipeline = Arc::make_mut(&mut block).pipelines.remove(0); if let Some(expr) = pipeline.elements.get(1) { return Err(ShellError::GenericError { error: "error when loading nuon text".into(), msg: "could not load nuon text".into(), span, help: None, inner: vec![ShellError::OutsideSpannedLabeledError { src: input.to_string(), error: "error when loading".into(), msg: "detected a pipeline in nuon file".into(), span: expr.expr.span, }], }); } if pipeline.elements.is_empty() { Expression::new( &mut working_set, Expr::Nothing, span.unwrap_or(Span::unknown()), Type::Nothing, ) } else { pipeline.elements.remove(0).expr } }; if let Some(err) = working_set.parse_errors.first() { return Err(ShellError::GenericError { error: "error when parsing nuon text".into(), msg: "could not parse nuon text".into(), span, help: None, inner: vec![ShellError::OutsideSpannedLabeledError { src: input.to_string(), error: "error when parsing".into(), msg: err.to_string(), span: err.span(), }], }); } let value = convert_to_value(expr, span.unwrap_or(Span::unknown()), input)?; Ok(value) } fn convert_to_value( expr: Expression, span: Span, original_text: &str, ) -> Result<Value, ShellError> { match expr.expr { Expr::AttributeBlock(..) => Err(ShellError::OutsideSpannedLabeledError { src: original_text.to_string(), error: "Error when loading".into(), msg: "attributes not supported in nuon".into(), span: expr.span, }), Expr::BinaryOp(..) => Err(ShellError::OutsideSpannedLabeledError { src: original_text.to_string(), error: "Error when loading".into(), msg: "binary operators not supported in nuon".into(), span: expr.span, }), Expr::UnaryNot(..) => Err(ShellError::OutsideSpannedLabeledError { src: original_text.to_string(), error: "Error when loading".into(), msg: "unary operators not supported in nuon".into(), span: expr.span, }), Expr::Block(..) => Err(ShellError::OutsideSpannedLabeledError { src: original_text.to_string(), error: "Error when loading".into(), msg: "blocks not supported in nuon".into(), span: expr.span, }), Expr::Closure(..) => Err(ShellError::OutsideSpannedLabeledError { src: original_text.to_string(), error: "Error when loading".into(), msg: "closures not supported in nuon".into(), span: expr.span, }), Expr::Binary(val) => Ok(Value::binary(val, span)), Expr::Bool(val) => Ok(Value::bool(val, span)), Expr::Call(..) => Err(ShellError::OutsideSpannedLabeledError { src: original_text.to_string(), error: "Error when loading".into(), msg: "calls not supported in nuon".into(), span: expr.span, }), Expr::CellPath(val) => Ok(Value::cell_path(val, span)), Expr::DateTime(dt) => Ok(Value::date(dt, span)), Expr::ExternalCall(..) => Err(ShellError::OutsideSpannedLabeledError { src: original_text.to_string(), error: "Error when loading".into(), msg: "calls not supported in nuon".into(), span: expr.span, }), Expr::Filepath(val, _) => Ok(Value::string(val, span)), Expr::Directory(val, _) => Ok(Value::string(val, span)), Expr::Float(val) => Ok(Value::float(val, span)), Expr::FullCellPath(full_cell_path) => { if !full_cell_path.tail.is_empty() { Err(ShellError::OutsideSpannedLabeledError { src: original_text.to_string(), error: "Error when loading".into(), msg: "subexpressions and cellpaths not supported in nuon".into(), span: expr.span, }) } else { convert_to_value(full_cell_path.head, span, original_text) } } Expr::Garbage => Err(ShellError::OutsideSpannedLabeledError { src: original_text.to_string(), error: "Error when loading".into(), msg: "extra tokens in input file".into(), span: expr.span, }), Expr::GlobPattern(val, _) => Ok(Value::string(val, span)), Expr::ImportPattern(..) => Err(ShellError::OutsideSpannedLabeledError { src: original_text.to_string(), error: "Error when loading".into(), msg: "imports not supported in nuon".into(), span: expr.span, }), Expr::Overlay(..) => Err(ShellError::OutsideSpannedLabeledError { src: original_text.to_string(), error: "Error when loading".into(), msg: "overlays not supported in nuon".into(), span: expr.span, }), Expr::Int(val) => Ok(Value::int(val, span)), Expr::Keyword(kw) => Err(ShellError::OutsideSpannedLabeledError { src: original_text.to_string(), error: "Error when loading".into(), msg: format!( "{} not supported in nuon", String::from_utf8_lossy(&kw.keyword) ), span: expr.span, }), Expr::List(vals) => { let mut output = vec![]; for item in vals { match item { ListItem::Item(expr) => { output.push(convert_to_value(expr, span, original_text)?); } ListItem::Spread(_, inner) => { return Err(ShellError::OutsideSpannedLabeledError { src: original_text.to_string(), error: "Error when loading".into(), msg: "spread operator not supported in nuon".into(), span: inner.span, }); } } } Ok(Value::list(output, span)) } Expr::MatchBlock(..) => Err(ShellError::OutsideSpannedLabeledError { src: original_text.to_string(), error: "Error when loading".into(), msg: "match blocks not supported in nuon".into(), span: expr.span, }), Expr::Nothing => Ok(Value::nothing(span)), Expr::Operator(..) => Err(ShellError::OutsideSpannedLabeledError { src: original_text.to_string(), error: "Error when loading".into(), msg: "operators not supported in nuon".into(), span: expr.span, }), Expr::Range(range) => { let from = if let Some(f) = range.from { convert_to_value(f, span, original_text)? } else { Value::nothing(expr.span) }; let next = if let Some(s) = range.next { convert_to_value(s, span, original_text)? } else { Value::nothing(expr.span) }; let to = if let Some(t) = range.to { convert_to_value(t, span, original_text)? } else { Value::nothing(expr.span) }; Ok(Value::range( Range::new(from, next, to, range.operator.inclusion, expr.span)?, expr.span, )) } Expr::Record(key_vals) => { let mut record = Record::with_capacity(key_vals.len()); let mut key_spans = Vec::with_capacity(key_vals.len()); for key_val in key_vals { match key_val { RecordItem::Pair(key, val) => { let key_str = match key.expr { Expr::String(key_str) => key_str, _ => { return Err(ShellError::OutsideSpannedLabeledError { src: original_text.to_string(), error: "Error when loading".into(), msg: "only strings can be keys".into(), span: key.span, }); } }; if let Some(i) = record.index_of(&key_str) { return Err(ShellError::ColumnDefinedTwice { col_name: key_str, second_use: key.span, first_use: key_spans[i], }); } else { key_spans.push(key.span); record.push(key_str, convert_to_value(val, span, original_text)?); } } RecordItem::Spread(_, inner) => { return Err(ShellError::OutsideSpannedLabeledError { src: original_text.to_string(), error: "Error when loading".into(), msg: "spread operator not supported in nuon".into(), span: inner.span, }); } } } Ok(Value::record(record, span)) } Expr::RowCondition(..) => Err(ShellError::OutsideSpannedLabeledError { src: original_text.to_string(), error: "Error when loading".into(), msg: "row conditions not supported in nuon".into(), span: expr.span, }), Expr::Signature(..) => Err(ShellError::OutsideSpannedLabeledError { src: original_text.to_string(), error: "Error when loading".into(), msg: "signatures not supported in nuon".into(), span: expr.span, }), Expr::String(s) | Expr::RawString(s) => Ok(Value::string(s, span)), Expr::StringInterpolation(..) => Err(ShellError::OutsideSpannedLabeledError { src: original_text.to_string(), error: "Error when loading".into(), msg: "string interpolation not supported in nuon".into(), span: expr.span, }), Expr::GlobInterpolation(..) => Err(ShellError::OutsideSpannedLabeledError { src: original_text.to_string(), error: "Error when loading".into(), msg: "glob interpolation not supported in nuon".into(), span: expr.span, }), Expr::Collect(..) => Err(ShellError::OutsideSpannedLabeledError { src: original_text.to_string(), error: "Error when loading".into(), msg: "`$in` not supported in nuon".into(), span: expr.span, }), Expr::Subexpression(..) => Err(ShellError::OutsideSpannedLabeledError { src: original_text.to_string(), error: "Error when loading".into(), msg: "subexpressions not supported in nuon".into(), span: expr.span, }), Expr::Table(mut table) => { let mut cols = vec![]; let mut output = vec![]; for key in table.columns.as_mut() { let key_str = match &mut key.expr { Expr::String(key_str) => key_str, _ => { return Err(ShellError::OutsideSpannedLabeledError { src: original_text.to_string(), error: "Error when loading".into(), msg: "only strings can be keys".into(), span: expr.span, }); } }; if let Some(idx) = cols.iter().position(|existing| existing == key_str) { return Err(ShellError::ColumnDefinedTwice { col_name: key_str.clone(), second_use: key.span, first_use: table.columns[idx].span, }); } else { cols.push(std::mem::take(key_str)); } } for row in table.rows.into_vec() { if cols.len() != row.len() { return Err(ShellError::OutsideSpannedLabeledError { src: original_text.to_string(), error: "Error when loading".into(), msg: "table has mismatched columns".into(), span: expr.span, }); } let record = cols .iter() .zip(row.into_vec()) .map(|(col, cell)| { convert_to_value(cell, span, original_text).map(|val| (col.clone(), val)) }) .collect::<Result<_, _>>()?; output.push(Value::record(record, span)); } Ok(Value::list(output, span)) } Expr::ValueWithUnit(value) => { let size = match value.expr.expr { Expr::Int(val) => val, _ => { return Err(ShellError::OutsideSpannedLabeledError { src: original_text.to_string(), error: "Error when loading".into(), msg: "non-integer unit value".into(), span: expr.span, }); } }; match value.unit.item { Unit::Filesize(unit) => match Filesize::from_unit(size, unit) { Some(val) => Ok(val.into_value(span)), None => Err(ShellError::OutsideSpannedLabeledError { src: original_text.into(), error: "filesize too large".into(), msg: "filesize too large".into(), span: expr.span, }), }, Unit::Nanosecond => Ok(Value::duration(size, span)), Unit::Microsecond => Ok(Value::duration(size * 1000, span)), Unit::Millisecond => Ok(Value::duration(size * 1000 * 1000, span)), Unit::Second => Ok(Value::duration(size * 1000 * 1000 * 1000, span)), Unit::Minute => Ok(Value::duration(size * 1000 * 1000 * 1000 * 60, span)), Unit::Hour => Ok(Value::duration(size * 1000 * 1000 * 1000 * 60 * 60, span)), Unit::Day => match size.checked_mul(1000 * 1000 * 1000 * 60 * 60 * 24) { Some(val) => Ok(Value::duration(val, span)), None => Err(ShellError::OutsideSpannedLabeledError { src: original_text.to_string(), error: "day duration too large".into(), msg: "day duration too large".into(), span: expr.span, }), }, Unit::Week => match size.checked_mul(1000 * 1000 * 1000 * 60 * 60 * 24 * 7) { Some(val) => Ok(Value::duration(val, span)), None => Err(ShellError::OutsideSpannedLabeledError { src: original_text.to_string(), error: "week duration too large".into(), msg: "week duration too large".into(), span: expr.span, }), }, } } Expr::Var(..) => Err(ShellError::OutsideSpannedLabeledError { src: original_text.to_string(), error: "Error when loading".into(), msg: "variables not supported in nuon".into(), span: expr.span, }), Expr::VarDecl(..) => Err(ShellError::OutsideSpannedLabeledError { src: original_text.to_string(), error: "Error when loading".into(), msg: "variable declarations not supported in nuon".into(), span: expr.span, }), } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nuon/src/lib.rs
crates/nuon/src/lib.rs
#![doc = include_str!("../README.md")] mod from; mod to; pub use from::from_nuon; pub use to::ToStyle; pub use to::to_nuon; #[cfg(test)] mod tests { use chrono::DateTime; use nu_protocol::{ BlockId, IntRange, Range, Span, Value, ast::{CellPath, PathMember, RangeInclusion}, casing::Casing, engine::{Closure, EngineState}, record, }; use crate::{ToStyle, from_nuon, to_nuon}; /// test something of the form /// ```nushell /// $v | from nuon | to nuon | $in == $v /// ``` /// /// an optional "middle" value can be given to test what the value is between `from nuon` and /// `to nuon`. fn nuon_end_to_end(input: &str, middle: Option<Value>) { let engine_state = EngineState::new(); let val = from_nuon(input, None).unwrap(); if let Some(m) = middle { assert_eq!(val, m); } assert_eq!( to_nuon(&engine_state, &val, ToStyle::Default, None, false).unwrap(), input ); } #[test] fn list_of_numbers() { nuon_end_to_end( "[1, 2, 3]", Some(Value::test_list(vec![ Value::test_int(1), Value::test_int(2), Value::test_int(3), ])), ); } #[test] fn list_of_strings() { nuon_end_to_end( "[abc, xyz, def]", Some(Value::test_list(vec![ Value::test_string("abc"), Value::test_string("xyz"), Value::test_string("def"), ])), ); } #[test] fn table() { nuon_end_to_end( "[[my, columns]; [abc, xyz], [def, ijk]]", Some(Value::test_list(vec![ Value::test_record(record!( "my" => Value::test_string("abc"), "columns" => Value::test_string("xyz") )), Value::test_record(record!( "my" => Value::test_string("def"), "columns" => Value::test_string("ijk") )), ])), ); } #[test] fn from_nuon_illegal_table() { assert!( from_nuon("[[repeated repeated]; [abc, xyz], [def, ijk]]", None) .unwrap_err() .to_string() .contains("Record field or table column used twice: repeated") ); } #[test] fn bool() { nuon_end_to_end("false", Some(Value::test_bool(false))); } #[test] fn escaping() { nuon_end_to_end(r#""hello\"world""#, None); } #[test] fn escaping2() { nuon_end_to_end(r#""hello\\world""#, None); } #[test] fn escaping3() { nuon_end_to_end( r#"[hello\\world]"#, Some(Value::test_list(vec![Value::test_string( r#"hello\\world"#, )])), ); } #[test] fn escaping4() { nuon_end_to_end(r#"["hello\"world"]"#, None); } #[test] fn escaping5() { nuon_end_to_end(r#"{s: "hello\"world"}"#, None); } #[test] fn negative_int() { nuon_end_to_end("-1", Some(Value::test_int(-1))); } #[test] fn records() { nuon_end_to_end( r#"{name: "foo bar", age: 100, height: 10}"#, Some(Value::test_record(record!( "name" => Value::test_string("foo bar"), "age" => Value::test_int(100), "height" => Value::test_int(10), ))), ); } #[test] fn range() { nuon_end_to_end( "1..42", Some(Value::test_range(Range::IntRange( IntRange::new( Value::test_int(1), Value::test_int(2), Value::test_int(42), RangeInclusion::Inclusive, Span::unknown(), ) .unwrap(), ))), ); } #[test] fn filesize() { nuon_end_to_end("1024b", Some(Value::test_filesize(1024))); assert_eq!(from_nuon("1kib", None).unwrap(), Value::test_filesize(1024)); } #[test] fn duration() { nuon_end_to_end("60000000000ns", Some(Value::test_duration(60_000_000_000))); } #[test] fn to_nuon_datetime() { nuon_end_to_end( "1970-01-01T00:00:00+00:00", Some(Value::test_date(DateTime::UNIX_EPOCH.into())), ); } #[test] #[ignore] fn to_nuon_errs_on_closure() { let engine_state = EngineState::new(); assert!( to_nuon( &engine_state, &Value::test_closure(Closure { block_id: BlockId::new(0), captures: vec![] }), ToStyle::Default, None, false, ) .unwrap_err() .to_string() .contains("Unsupported input") ); } #[test] fn binary() { nuon_end_to_end( "0x[ABCDEF]", Some(Value::test_binary(vec![0xab, 0xcd, 0xef])), ); } #[test] fn binary_roundtrip() { let engine_state = EngineState::new(); assert_eq!( to_nuon( &engine_state, &from_nuon("0x[1f ff]", None).unwrap(), ToStyle::Default, None, false, ) .unwrap(), "0x[1FFF]" ); } #[test] fn read_sample_data() { assert_eq!( from_nuon( include_str!("../../../tests/fixtures/formats/sample.nuon"), None, ) .unwrap(), Value::test_list(vec![ Value::test_list(vec![ Value::test_record(record!( "a" => Value::test_int(1), "nuon" => Value::test_int(2), "table" => Value::test_int(3) )), Value::test_record(record!( "a" => Value::test_int(4), "nuon" => Value::test_int(5), "table" => Value::test_int(6) )), ]), Value::test_filesize(100 * 1024), Value::test_duration(100 * 1_000_000_000), Value::test_bool(true), Value::test_record(record!( "name" => Value::test_string("Bobby"), "age" => Value::test_int(99) ),), Value::test_binary(vec![0x11, 0xff, 0xee, 0x1f]), ]) ); } #[test] fn float_doesnt_become_int() { let engine_state = EngineState::new(); assert_eq!( to_nuon( &engine_state, &Value::test_float(1.0), ToStyle::Default, None, false ) .unwrap(), "1.0" ); } #[test] fn float_inf_parsed_properly() { let engine_state = EngineState::new(); assert_eq!( to_nuon( &engine_state, &Value::test_float(f64::INFINITY), ToStyle::Default, None, false, ) .unwrap(), "inf" ); } #[test] fn float_neg_inf_parsed_properly() { let engine_state = EngineState::new(); assert_eq!( to_nuon( &engine_state, &Value::test_float(f64::NEG_INFINITY), ToStyle::Default, None, false, ) .unwrap(), "-inf" ); } #[test] fn float_nan_parsed_properly() { let engine_state = EngineState::new(); assert_eq!( to_nuon( &engine_state, &Value::test_float(-f64::NAN), ToStyle::Default, None, false, ) .unwrap(), "NaN" ); } #[test] fn to_nuon_converts_columns_with_spaces() { let engine_state = EngineState::new(); assert!( from_nuon( &to_nuon( &engine_state, &Value::test_list(vec![ Value::test_record(record!( "a" => Value::test_int(1), "b" => Value::test_int(2), "c d" => Value::test_int(3) )), Value::test_record(record!( "a" => Value::test_int(4), "b" => Value::test_int(5), "c d" => Value::test_int(6) )) ]), ToStyle::Default, None, false, ) .unwrap(), None, ) .is_ok() ); } #[test] fn to_nuon_quotes_empty_string() { let engine_state = EngineState::new(); let res = to_nuon( &engine_state, &Value::test_string(""), ToStyle::Default, None, false, ); assert!(res.is_ok()); assert_eq!(res.unwrap(), r#""""#); } #[test] fn to_nuon_quotes_empty_string_in_list() { nuon_end_to_end( r#"[""]"#, Some(Value::test_list(vec![Value::test_string("")])), ); } #[test] fn to_nuon_quotes_empty_string_in_table() { nuon_end_to_end( "[[a, b]; [\"\", la], [le, lu]]", Some(Value::test_list(vec![ Value::test_record(record!( "a" => Value::test_string(""), "b" => Value::test_string("la"), )), Value::test_record(record!( "a" => Value::test_string("le"), "b" => Value::test_string("lu"), )), ])), ); } #[test] fn cell_path() { nuon_end_to_end( r#"$.foo.bar.0"#, Some(Value::test_cell_path(CellPath { members: vec![ PathMember::string( "foo".to_string(), false, Casing::Sensitive, Span::new(2, 5), ), PathMember::string( "bar".to_string(), false, Casing::Sensitive, Span::new(6, 9), ), PathMember::int(0, false, Span::new(10, 11)), ], })), ); } #[test] fn does_not_quote_strings_unnecessarily() { let engine_state = EngineState::new(); assert_eq!( to_nuon( &engine_state, &Value::test_list(vec![ Value::test_record(record!( "a" => Value::test_int(1), "b" => Value::test_int(2), "c d" => Value::test_int(3) )), Value::test_record(record!( "a" => Value::test_int(4), "b" => Value::test_int(5), "c d" => Value::test_int(6) )) ]), ToStyle::Default, None, false, ) .unwrap(), "[[a, b, \"c d\"]; [1, 2, 3], [4, 5, 6]]" ); assert_eq!( to_nuon( &engine_state, &Value::test_record(record!( "ro name" => Value::test_string("sam"), "rank" => Value::test_int(10) )), ToStyle::Default, None, false, ) .unwrap(), "{\"ro name\": sam, rank: 10}" ); } #[test] fn quotes_some_strings_necessarily() { nuon_end_to_end( r#"["true", "false", "null", "NaN", "NAN", "nan", "+nan", "-nan", "inf", "+inf", "-inf", "INF", "Infinity", "+Infinity", "-Infinity", "INFINITY", "+19.99", "-19.99", "19.99b", "19.99kb", "19.99mb", "19.99gb", "19.99tb", "19.99pb", "19.99eb", "19.99zb", "19.99kib", "19.99mib", "19.99gib", "19.99tib", "19.99pib", "19.99eib", "19.99zib", "19ns", "19us", "19ms", "19sec", "19min", "19hr", "19day", "19wk", "-11.0..-15.0", "11.0..-15.0", "-11.0..15.0", "-11.0..<-15.0", "11.0..<-15.0", "-11.0..<15.0", "-11.0..", "11.0..", "..15.0", "..-15.0", "..<15.0", "..<-15.0", "2000-01-01", "2022-02-02T14:30:00", "2022-02-02T14:30:00+05:00", ", ", "", "&&"]"#, None, ); } #[test] // NOTE: this test could be stronger, but the output of [`from_nuon`] on the content of `../../../tests/fixtures/formats/code.nu` is // not the same in the CI and locally... // // ## locally // ``` // OutsideSpannedLabeledError { // src: "register", // error: "Error when loading", // msg: "calls not supported in nuon", // span: Span { start: 0, end: 8 } // } // ``` // // ## in the CI // ``` // GenericError { // error: "error when parsing nuon text", // msg: "could not parse nuon text", // span: None, // help: None, // inner: [OutsideSpannedLabeledError { // src: "register", // error: "error when parsing", // msg: "Unknown state.", // span: Span { start: 0, end: 8 } // }] // } // ``` fn read_code_should_fail_rather_than_panic() { assert!( from_nuon( include_str!("../../../tests/fixtures/formats/code.nu"), None, ) .is_err() ); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nuon/src/to.rs
crates/nuon/src/to.rs
use core::fmt::Write; use nu_engine::get_columns; use nu_protocol::{Range, ShellError, Span, Value, engine::EngineState}; use nu_utils::{ObviousFloat, escape_quote_string, needs_quoting}; /// control the way Nushell [`Value`] is converted to NUON data pub enum ToStyle { /// no extra indentation /// /// `{ a: 1, b: 2 }` will be converted to `{a: 1, b: 2}` Default, /// no white space at all /// /// `{ a: 1, b: 2 }` will be converted to `{a:1,b:2}` Raw, #[allow(clippy::tabs_in_doc_comments)] /// tabulation-based indentation /// /// using 2 as the variant value, `{ a: 1, b: 2 }` will be converted to /// ```text /// { /// a: 1, /// b: 2 /// } /// ``` Tabs(usize), /// space-based indentation /// /// using 3 as the variant value, `{ a: 1, b: 2 }` will be converted to /// ```text /// { /// a: 1, /// b: 2 /// } /// ``` Spaces(usize), } /// convert an actual Nushell [`Value`] to a raw string representation of the NUON data /// // WARNING: please leave the following two trailing spaces, they matter for the documentation // formatting /// > **Note** /// > a [`Span`] can be passed to [`to_nuon`] if there is context available to the caller, e.g. when /// > using this function in a command implementation such as [`to nuon`](https://www.nushell.sh/commands/docs/to_nuon.html). /// /// also see [`super::from_nuon`] for the inverse operation pub fn to_nuon( engine_state: &EngineState, input: &Value, style: ToStyle, span: Option<Span>, serialize_types: bool, ) -> Result<String, ShellError> { let span = span.unwrap_or(Span::unknown()); let indentation = match style { ToStyle::Default => None, ToStyle::Raw => Some("".to_string()), ToStyle::Tabs(t) => Some("\t".repeat(t)), ToStyle::Spaces(s) => Some(" ".repeat(s)), }; let res = value_to_string( engine_state, input, span, 0, indentation.as_deref(), serialize_types, )?; Ok(res) } fn value_to_string( engine_state: &EngineState, v: &Value, span: Span, depth: usize, indent: Option<&str>, serialize_types: bool, ) -> Result<String, ShellError> { let (nl, sep, kv_sep) = get_true_separators(indent); let idt = get_true_indentation(depth, indent); let idt_po = get_true_indentation(depth + 1, indent); let idt_pt = get_true_indentation(depth + 2, indent); match v { Value::Binary { val, .. } => { let mut s = String::with_capacity(2 * val.len()); for byte in val { if write!(s, "{byte:02X}").is_err() { return Err(ShellError::UnsupportedInput { msg: "could not convert binary to string".into(), input: "value originates from here".into(), msg_span: span, input_span: v.span(), }); } } Ok(format!("0x[{s}]")) } Value::Closure { val, .. } => { if serialize_types { Ok(escape_quote_string( &val.coerce_into_string(engine_state, span)?, )) } else { Err(ShellError::UnsupportedInput { msg: "closures are currently not deserializable (use --serialize to serialize as a string)".into(), input: "value originates from here".into(), msg_span: span, input_span: v.span(), }) } } Value::Bool { val, .. } => { if *val { Ok("true".to_string()) } else { Ok("false".to_string()) } } Value::CellPath { val, .. } => Ok(val.to_string()), Value::Custom { .. } => Err(ShellError::UnsupportedInput { msg: "custom values are currently not nuon-compatible".to_string(), input: "value originates from here".into(), msg_span: span, input_span: v.span(), }), Value::Date { val, .. } => Ok(val.to_rfc3339()), // FIXME: make durations use the shortest lossless representation. Value::Duration { val, .. } => Ok(format!("{}ns", *val)), // Propagate existing errors Value::Error { error, .. } => Err(*error.clone()), // FIXME: make filesizes use the shortest lossless representation. Value::Filesize { val, .. } => Ok(format!("{}b", val.get())), Value::Float { val, .. } => Ok(ObviousFloat(*val).to_string()), Value::Int { val, .. } => Ok(val.to_string()), Value::List { vals, .. } => { let headers = get_columns(vals); if !headers.is_empty() && vals.iter().all(|x| x.columns().eq(headers.iter())) { // Table output let headers: Vec<String> = headers .iter() .map(|string| { let string = if needs_quoting(string) { &escape_quote_string(string) } else { string }; format!("{idt}{string}") }) .collect(); let headers_output = headers.join(&format!(",{sep}{nl}{idt_pt}")); let mut table_output = vec![]; for val in vals { let mut row = vec![]; if let Value::Record { val, .. } = val { for val in val.values() { row.push(value_to_string_without_quotes( engine_state, val, span, depth + 2, indent, serialize_types, )?); } } table_output.push(row.join(&format!(",{sep}{nl}{idt_pt}"))); } Ok(format!( "[{nl}{idt_po}[{nl}{idt_pt}{}{nl}{idt_po}];{sep}{nl}{idt_po}[{nl}{idt_pt}{}{nl}{idt_po}]{nl}{idt}]", headers_output, table_output.join(&format!("{nl}{idt_po}],{sep}{nl}{idt_po}[{nl}{idt_pt}")) )) } else { let mut collection = vec![]; for val in vals { collection.push(format!( "{idt_po}{}", value_to_string_without_quotes( engine_state, val, span, depth + 1, indent, serialize_types )? )); } Ok(format!( "[{nl}{}{nl}{idt}]", collection.join(&format!(",{sep}{nl}")) )) } } Value::Nothing { .. } => Ok("null".to_string()), Value::Range { val, .. } => match **val { Range::IntRange(range) => Ok(range.to_string()), Range::FloatRange(range) => Ok(range.to_string()), }, Value::Record { val, .. } => { let mut collection = vec![]; for (col, val) in &**val { let col = if needs_quoting(col) { &escape_quote_string(col) } else { col }; collection.push(format!( "{idt_po}{col}:{kv_sep}{}", value_to_string_without_quotes( engine_state, val, span, depth + 1, indent, serialize_types )? )); } Ok(format!( "{{{nl}{}{nl}{idt}}}", collection.join(&format!(",{sep}{nl}")) )) } // All strings outside data structures are quoted because they are in 'command position' // (could be mistaken for commands by the Nu parser) Value::String { val, .. } => Ok(escape_quote_string(val)), Value::Glob { val, .. } => Ok(escape_quote_string(val)), } } fn get_true_indentation(depth: usize, indent: Option<&str>) -> String { match indent { Some(i) => i.repeat(depth), None => "".to_string(), } } /// Converts the provided indent into three types of separator: /// - New line separators /// - Inline separator /// - Key-value separators inside Records fn get_true_separators(indent: Option<&str>) -> (String, String, String) { match indent { Some("") => ("".to_string(), "".to_string(), "".to_string()), Some(_) => ("\n".to_string(), "".to_string(), " ".to_string()), None => ("".to_string(), " ".to_string(), " ".to_string()), } } fn value_to_string_without_quotes( engine_state: &EngineState, v: &Value, span: Span, depth: usize, indent: Option<&str>, serialize_types: bool, ) -> Result<String, ShellError> { match v { Value::String { val, .. } => Ok({ if needs_quoting(val) { escape_quote_string(val) } else { val.clone() } }), _ => value_to_string(engine_state, v, span, depth, indent, serialize_types), } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/lib.rs
crates/nu-command/src/lib.rs
#![cfg_attr(not(feature = "os"), allow(unused))] #![doc = include_str!("../README.md")] mod bytes; mod charting; mod conversions; mod date; mod debug; mod default_context; mod env; mod example_test; mod experimental; #[cfg(feature = "os")] mod filesystem; mod filters; mod formats; mod generators; mod hash; mod help; mod math; mod misc; mod network; mod path; #[cfg(feature = "os")] mod platform; mod progress_bar; #[cfg(feature = "rand")] mod random; mod removed; mod shells; mod sort_utils; #[cfg(feature = "sqlite")] mod stor; mod strings; #[cfg(feature = "os")] mod system; mod viewers; pub use bytes::*; pub use charting::*; pub use conversions::*; pub use date::*; pub use debug::*; pub use default_context::*; pub use env::*; #[cfg(test)] pub use example_test::{test_examples, test_examples_with_commands}; pub use experimental::*; #[cfg(feature = "os")] pub use filesystem::*; pub use filters::*; pub use formats::*; pub use generators::*; pub use hash::*; pub use help::*; pub use math::*; pub use misc::*; pub use network::*; pub use path::*; #[cfg(feature = "os")] pub use platform::*; #[cfg(feature = "rand")] pub use random::*; pub use removed::*; pub use shells::*; pub use sort_utils::*; #[cfg(feature = "sqlite")] pub use stor::*; pub use strings::*; #[cfg(feature = "os")] pub use system::*; pub use viewers::*; #[cfg(feature = "sqlite")] mod database; #[cfg(feature = "sqlite")] pub use database::*;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/default_context.rs
crates/nu-command/src/default_context.rs
use crate::*; use nu_protocol::engine::{EngineState, StateWorkingSet}; pub fn add_shell_command_context(mut engine_state: EngineState) -> EngineState { let delta = { let mut working_set = StateWorkingSet::new(&engine_state); macro_rules! bind_command { ( $( $command:expr ),* $(,)? ) => { $( working_set.add_decl(Box::new($command)); )* }; } // If there are commands that have the same name as default declarations, // they have to be registered before the main declarations. This helps to make // them only accessible if the correct input value category is used with the // declaration // Database-related // Adds all related commands to query databases #[cfg(feature = "sqlite")] add_database_decls(&mut working_set); // Charts bind_command! { Histogram } // Filters #[cfg(feature = "rand")] bind_command! { Shuffle } bind_command! { All, Any, Append, Chunks, Columns, Compact, Default, Drop, DropColumn, DropNth, Each, Enumerate, Every, Filter, Find, First, Flatten, Get, GroupBy, Headers, Insert, IsEmpty, IsNotEmpty, Interleave, Items, Join, Take, Merge, MergeDeep, Move, TakeWhile, TakeUntil, Last, Length, Lines, ParEach, ChunkBy, Prepend, Reduce, Reject, Rename, Reverse, Select, Skip, SkipUntil, SkipWhile, Slice, Sort, SortBy, SplitList, Tee, Transpose, Uniq, UniqBy, Upsert, Update, Values, Where, Window, Wrap, Zip, }; // Misc bind_command! { DeleteVar, Panic, Source, Tutor, }; // Path bind_command! { Path, PathBasename, PathSelf, PathDirname, PathExists, PathExpand, PathJoin, PathParse, PathRelativeTo, PathSplit, PathType, }; // System #[cfg(feature = "os")] bind_command! { Complete, External, Exec, NuCheck, Sys, SysCpu, SysDisks, SysHost, SysMem, SysNet, SysTemp, SysUsers, UName, Which, }; // Help bind_command! { Help, HelpAliases, HelpExterns, HelpCommands, HelpModules, HelpOperators, HelpPipeAndRedirect, HelpEscapes, }; // Debug bind_command! { Ast, Debug, DebugEnv, DebugExperimentalOptions, DebugInfo, DebugProfile, Explain, Inspect, Metadata, MetadataAccess, MetadataSet, TimeIt, View, ViewBlocks, ViewFiles, ViewIr, ViewSource, ViewSpan, }; #[cfg(all(feature = "os", windows))] bind_command! { Registry, RegistryQuery } #[cfg(all( feature = "os", any( target_os = "android", target_os = "linux", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd", target_os = "macos", target_os = "windows" ) ))] bind_command! { Ps }; // Strings bind_command! { Ansi, AnsiLink, AnsiStrip, Char, Decode, Encode, DecodeHex, EncodeHex, DecodeBase32, EncodeBase32, DecodeBase32Hex, EncodeBase32Hex, DecodeBase64, EncodeBase64, Detect, DetectColumns, DetectType, Parse, Split, SplitChars, SplitColumn, SplitRow, SplitWords, Str, StrCapitalize, StrContains, StrDistance, StrDowncase, StrEndswith, StrExpand, StrJoin, StrReplace, StrIndexOf, StrLength, StrReverse, StrStats, StrStartsWith, StrSubstring, StrTrim, StrUpcase, Format, FormatDate, FormatDuration, FormatFilesize, }; // FileSystem #[cfg(feature = "os")] bind_command! { Cd, Ls, UMkdir, Mktemp, UMv, UCp, Open, Start, Rm, Save, UTouch, Glob, Watch, }; // Platform #[cfg(feature = "os")] bind_command! { Clear, Du, Input, InputList, InputListen, IsTerminal, Kill, Sleep, Term, TermSize, TermQuery, Whoami, }; #[cfg(all(unix, feature = "os"))] bind_command! { ULimit }; // Date bind_command! { Date, DateFromHuman, DateHumanize, DateListTimezones, DateNow, DateToTimezone, }; // Shells bind_command! { Exit, }; // Formats bind_command! { From, FromCsv, FromJson, FromMsgpack, FromMsgpackz, FromNuon, FromOds, FromSsv, FromToml, FromTsv, FromXlsx, FromXml, FromYaml, FromYml, To, ToCsv, ToJson, ToMd, ToMsgpack, ToMsgpackz, ToNuon, ToText, ToToml, ToTsv, Upsert, Where, ToXml, ToYaml, ToYml, }; // Viewers bind_command! { Griddle, Table, }; // Conversions bind_command! { Fill, Into, IntoBool, IntoBinary, IntoCellPath, IntoDatetime, IntoDuration, IntoFloat, IntoFilesize, IntoInt, IntoRecord, IntoString, IntoGlob, IntoValue, SplitCellPath, }; // Env bind_command! { ExportEnv, LoadEnv, SourceEnv, WithEnv, ConfigNu, ConfigEnv, ConfigFlatten, ConfigMeta, ConfigReset, ConfigUseColors, }; // Math bind_command! { Math, MathAbs, MathAvg, MathCeil, MathFloor, MathMax, MathMedian, MathMin, MathMode, MathProduct, MathRound, MathSqrt, MathStddev, MathSum, MathVariance, MathLog, }; // Bytes bind_command! { Bytes, BytesLen, BytesSplit, BytesStartsWith, BytesEndsWith, BytesReverse, BytesReplace, BytesAdd, BytesAt, BytesIndexOf, BytesCollect, BytesRemove, BytesBuild } // Network #[cfg(feature = "network")] bind_command! { Http, HttpDelete, HttpGet, HttpHead, HttpPatch, HttpPost, HttpPut, HttpOptions, HttpPool, Port, VersionCheck, } bind_command! { Url, UrlBuildQuery, UrlSplitQuery, UrlDecode, UrlEncode, UrlJoin, UrlParse, } // Random #[cfg(feature = "rand")] bind_command! { Random, RandomBool, RandomChars, RandomDice, RandomFloat, RandomInt, RandomUuid, RandomBinary }; // Generators bind_command! { Cal, Seq, SeqDate, SeqChar, Generate, }; // Hash bind_command! { Hash, HashMd5::default(), HashSha256::default(), }; // Experimental bind_command! { IsAdmin, JobSpawn, JobList, JobKill, JobId, JobTag, Job, }; #[cfg(not(target_family = "wasm"))] bind_command! { JobSend, JobRecv, JobFlush, } #[cfg(all(unix, feature = "os"))] bind_command! { JobUnfreeze, } // Removed bind_command! { LetEnv, DateFormat, }; // Stor #[cfg(feature = "sqlite")] bind_command! { Stor, StorCreate, StorDelete, StorExport, StorImport, StorInsert, StorOpen, StorReset, StorUpdate, }; working_set.render() }; if let Err(err) = engine_state.merge_delta(delta) { eprintln!("Error creating default context: {err:?}"); } // Cache the table decl id so we don't have to look it up later let table_decl_id = engine_state.find_decl("table".as_bytes(), &[]); engine_state.table_decl_id = table_decl_id; engine_state }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/progress_bar.rs
crates/nu-command/src/progress_bar.rs
use indicatif::{ProgressBar, ProgressState, ProgressStyle}; use std::fmt; // This module includes the progress bar used to show the progress when using the command `save` // Eventually it would be nice to find a better place for it. pub struct NuProgressBar { pub pb: ProgressBar, } impl NuProgressBar { pub fn new(total_bytes: Option<u64>) -> NuProgressBar { // Let's create the progress bar template. let template = match total_bytes { Some(_) => { // We will use a progress bar if we know the total bytes of the stream ProgressStyle::with_template( "{spinner:.green} [{elapsed_precise}] [{bar:30.cyan/blue}] [{bytes}/{total_bytes}] {binary_bytes_per_sec} ({eta}) {wide_msg}", ) } _ => { // But if we don't know the total then we just show the stats progress ProgressStyle::with_template( "{spinner:.green} [{elapsed_precise}] {bytes} {binary_bytes_per_sec} {wide_msg}", ) } }; let total_bytes = total_bytes.unwrap_or_default(); let new_progress_bar = ProgressBar::new(total_bytes); new_progress_bar.set_style( template .unwrap_or_else(|_| ProgressStyle::default_bar()) .with_key("eta", |state: &ProgressState, w: &mut dyn fmt::Write| { let _ = fmt::write(w, format_args!("{:.1}s", state.eta().as_secs_f64())); }) .progress_chars("#>-"), ); NuProgressBar { pb: new_progress_bar, } } pub fn update_bar(&mut self, bytes_processed: u64) { self.pb.set_position(bytes_processed); } pub fn abandoned_msg(&self, msg: String) { self.pb.abandon_with_message(msg); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/example_test.rs
crates/nu-command/src/example_test.rs
#[cfg(test)] use nu_protocol::engine::Command; #[cfg(test)] /// Runs the test examples in the passed in command and check their signatures and return values. /// /// # Panics /// If you get a ExternalNotSupported panic, you may be using a command /// that's not in the default working set of the test harness. /// You may want to use test_examples_with_commands and include any other dependencies. pub fn test_examples(cmd: impl Command + 'static) { test_examples::test_examples(cmd, &[]); } #[cfg(test)] pub fn test_examples_with_commands(cmd: impl Command + 'static, commands: &[&dyn Command]) { test_examples::test_examples(cmd, commands); } #[cfg(test)] mod test_examples { use super::super::{ Ansi, Date, Enumerate, Filter, First, Flatten, From, Get, Into, IntoDatetime, IntoString, Lines, Math, MathRound, MathSum, ParEach, Path, PathParse, Random, Seq, Sort, SortBy, Split, SplitColumn, SplitRow, Str, StrJoin, StrLength, StrReplace, Update, Url, Values, Wrap, }; use crate::{Default, Each, To}; use nu_cmd_lang::example_support::{ check_all_signature_input_output_types_entries_have_examples, check_example_evaluates_to_expected_output, check_example_input_and_output_types_match_command_signature, }; use nu_cmd_lang::{Break, Describe, Echo, If, Let, Mut}; use nu_protocol::{ Type, engine::{Command, EngineState, StateWorkingSet}, }; use std::collections::HashSet; pub fn test_examples(cmd: impl Command + 'static, commands: &[&dyn Command]) { let examples = cmd.examples(); let signature = cmd.signature(); let mut engine_state = make_engine_state(cmd.clone_box(), commands); let cwd = std::env::current_dir().expect("Could not get current working directory."); let mut witnessed_type_transformations = HashSet::<(Type, Type)>::new(); for example in examples { if example.result.is_none() { continue; } witnessed_type_transformations.extend( check_example_input_and_output_types_match_command_signature( &example, &cwd, &mut make_engine_state(cmd.clone_box(), commands), &signature.input_output_types, signature.operates_on_cell_paths(), ), ); check_example_evaluates_to_expected_output( cmd.name(), &example, cwd.as_path(), &mut engine_state, ); } check_all_signature_input_output_types_entries_have_examples( signature, witnessed_type_transformations, ); } fn make_engine_state(cmd: Box<dyn Command>, commands: &[&dyn Command]) -> Box<EngineState> { let mut engine_state = Box::new(EngineState::new()); let delta = { // Base functions that are needed for testing // Try to keep this working set small to keep tests running as fast as possible let mut working_set = StateWorkingSet::new(&engine_state); working_set.add_decl(Box::new(Ansi)); working_set.add_decl(Box::new(Break)); working_set.add_decl(Box::new(Date)); working_set.add_decl(Box::new(Default)); working_set.add_decl(Box::new(Describe)); working_set.add_decl(Box::new(Each)); working_set.add_decl(Box::new(Echo)); working_set.add_decl(Box::new(Enumerate)); working_set.add_decl(Box::new(Filter)); working_set.add_decl(Box::new(First)); working_set.add_decl(Box::new(Flatten)); working_set.add_decl(Box::new(From)); working_set.add_decl(Box::new(Get)); working_set.add_decl(Box::new(If)); working_set.add_decl(Box::new(Into)); working_set.add_decl(Box::new(IntoString)); working_set.add_decl(Box::new(IntoDatetime)); working_set.add_decl(Box::new(Let)); working_set.add_decl(Box::new(Lines)); working_set.add_decl(Box::new(Math)); working_set.add_decl(Box::new(MathRound)); working_set.add_decl(Box::new(MathSum)); working_set.add_decl(Box::new(Mut)); working_set.add_decl(Box::new(Path)); working_set.add_decl(Box::new(PathParse)); working_set.add_decl(Box::new(ParEach)); working_set.add_decl(Box::new(Random)); working_set.add_decl(Box::new(Seq)); working_set.add_decl(Box::new(Sort)); working_set.add_decl(Box::new(SortBy)); working_set.add_decl(Box::new(Split)); working_set.add_decl(Box::new(SplitColumn)); working_set.add_decl(Box::new(SplitRow)); working_set.add_decl(Box::new(Str)); working_set.add_decl(Box::new(StrJoin)); working_set.add_decl(Box::new(StrLength)); working_set.add_decl(Box::new(StrReplace)); working_set.add_decl(Box::new(To)); working_set.add_decl(Box::new(Url)); working_set.add_decl(Box::new(Update)); working_set.add_decl(Box::new(Values)); working_set.add_decl(Box::new(Wrap)); // Add any extra commands that the test harness needs for command in commands { working_set.add_decl(command.clone_box()); } // Adding the command that is being tested to the working set working_set.add_decl(cmd); working_set.render() }; engine_state .merge_delta(delta) .expect("Error merging delta"); engine_state } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/sort_utils.rs
crates/nu-command/src/sort_utils.rs
use nu_engine::ClosureEval; use nu_protocol::{PipelineData, Record, ShellError, Span, Value, ast::CellPath}; use nu_utils::IgnoreCaseExt; use std::cmp::Ordering; /// A specification of sort order for `sort_by`. /// /// A closure comparator allows the user to return custom ordering to sort by. /// A cell path comparator uses the value referred to by the cell path as the sorting key. pub enum Comparator { KeyClosure(ClosureEval), CustomClosure(ClosureEval), CellPath(CellPath), } /// Sort a slice of `Value`s. /// /// Sort has the following invariants, in order of precedence: /// - Null values (Nothing type) are always sorted to the end. /// - For natural sort, numeric values (numeric strings, ints, and floats) appear first, sorted by numeric value /// - Values appear by order of `Value`'s `PartialOrd`. /// - Sorting for values with equal ordering is stable. /// /// Generally, values of different types are ordered by order of appearance in the `Value` enum. /// However, this is not always the case. For example, ints and floats will be grouped together since /// `Value`'s `PartialOrd` defines a non-decreasing ordering between non-decreasing integers and floats. pub fn sort(vec: &mut [Value], insensitive: bool, natural: bool) -> Result<(), ShellError> { // allow the comparator function to indicate error // by mutating this option captured by the closure, // since sort_by closure must be infallible let mut compare_err: Option<ShellError> = None; vec.sort_by(|a, b| { // we've already hit an error, bail out now if compare_err.is_some() { return Ordering::Equal; } compare_values(a, b, insensitive, natural).unwrap_or_else(|err| { compare_err.get_or_insert(err); Ordering::Equal }) }); if let Some(err) = compare_err { Err(err) } else { Ok(()) } } /// Sort a slice of `Value`s by criteria specified by one or multiple `Comparator`s. pub fn sort_by( vec: &mut [Value], mut comparators: Vec<Comparator>, head_span: Span, insensitive: bool, natural: bool, ) -> Result<(), ShellError> { if comparators.is_empty() { return Err(ShellError::GenericError { error: "expected name".into(), msg: "requires a cell path or closure to sort data".into(), span: Some(head_span), help: None, inner: vec![], }); } // allow the comparator function to indicate error // by mutating this option captured by the closure, // since sort_by closure must be infallible let mut compare_err: Option<ShellError> = None; vec.sort_by(|a, b| { compare_by( a, b, &mut comparators, head_span, insensitive, natural, &mut compare_err, ) }); if let Some(err) = compare_err { Err(err) } else { Ok(()) } } /// Sort a record's key-value pairs. /// /// Can sort by key or by value. pub fn sort_record( record: Record, sort_by_value: bool, reverse: bool, insensitive: bool, natural: bool, ) -> Result<Record, ShellError> { let mut input_pairs: Vec<(String, Value)> = record.into_iter().collect(); // allow the comparator function to indicate error // by mutating this option captured by the closure, // since sort_by closure must be infallible let mut compare_err: Option<ShellError> = None; if sort_by_value { input_pairs.sort_by(|a, b| { // we've already hit an error, bail out now if compare_err.is_some() { return Ordering::Equal; } compare_values(&a.1, &b.1, insensitive, natural).unwrap_or_else(|err| { compare_err.get_or_insert(err); Ordering::Equal }) }); } else { input_pairs.sort_by(|a, b| compare_strings(&a.0, &b.0, insensitive, natural)); }; if let Some(err) = compare_err { return Err(err); } if reverse { input_pairs.reverse() } Ok(input_pairs.into_iter().collect()) } pub fn compare_by( left: &Value, right: &Value, comparators: &mut [Comparator], span: Span, insensitive: bool, natural: bool, error: &mut Option<ShellError>, ) -> Ordering { // we've already hit an error, bail out now if error.is_some() { return Ordering::Equal; } for cmp in comparators.iter_mut() { let result = match cmp { Comparator::CellPath(cell_path) => { compare_cell_path(left, right, cell_path, insensitive, natural) } Comparator::KeyClosure(closure) => { compare_key_closure(left, right, closure, span, insensitive, natural) } Comparator::CustomClosure(closure) => { compare_custom_closure(left, right, closure, span) } }; match result { Ok(Ordering::Equal) => {} Ok(ordering) => return ordering, Err(err) => { // don't bother continuing through the remaining comparators as we've hit an error // don't overwrite if there's an existing error error.get_or_insert(err); return Ordering::Equal; } } } Ordering::Equal } /// Determines whether a value should be sorted as a string /// /// If we're natural sorting, we want to sort strings, integers, and floats alphanumerically, so we should string sort. /// Otherwise, we only want to string sort if both values are strings or globs (to enable case insensitive comparison) fn should_sort_as_string(val: &Value, natural: bool) -> bool { matches!( (val, natural), (&Value::String { .. }, _) | (&Value::Glob { .. }, _) | (&Value::Int { .. }, true) | (&Value::Float { .. }, true) ) } /// Simple wrapper around `should_sort_as_string` to determine if two values /// should be compared as strings. fn should_string_compare(left: &Value, right: &Value, natural: bool) -> bool { should_sort_as_string(left, natural) && should_sort_as_string(right, natural) } pub fn compare_values( left: &Value, right: &Value, insensitive: bool, natural: bool, ) -> Result<Ordering, ShellError> { if should_string_compare(left, right, natural) { Ok(compare_strings( &left.coerce_str()?, &right.coerce_str()?, insensitive, natural, )) } else { Ok(left.partial_cmp(right).unwrap_or(Ordering::Equal)) } } pub fn compare_strings(left: &str, right: &str, insensitive: bool, natural: bool) -> Ordering { fn compare_inner<T>(left: T, right: T, natural: bool) -> Ordering where T: AsRef<str> + Ord, { if natural { alphanumeric_sort::compare_str(left, right) } else { left.cmp(&right) } } // only allocate a String if necessary for case folding if insensitive { compare_inner(left.to_folded_case(), right.to_folded_case(), natural) } else { compare_inner(left, right, natural) } } pub fn compare_cell_path( left: &Value, right: &Value, cell_path: &CellPath, insensitive: bool, natural: bool, ) -> Result<Ordering, ShellError> { let left = left.follow_cell_path(&cell_path.members)?; let right = right.follow_cell_path(&cell_path.members)?; compare_values(&left, &right, insensitive, natural) } pub fn compare_key_closure( left: &Value, right: &Value, closure_eval: &mut ClosureEval, span: Span, insensitive: bool, natural: bool, ) -> Result<Ordering, ShellError> { let left_key = closure_eval .run_with_value(left.clone())? .into_value(span)?; let right_key = closure_eval .run_with_value(right.clone())? .into_value(span)?; compare_values(&left_key, &right_key, insensitive, natural) } pub fn compare_custom_closure( left: &Value, right: &Value, closure_eval: &mut ClosureEval, span: Span, ) -> Result<Ordering, ShellError> { closure_eval .add_arg(left.clone()) .add_arg(right.clone()) .run_with_input(PipelineData::value( Value::list(vec![left.clone(), right.clone()], span), None, )) .and_then(|data| data.into_value(span)) .map(|val| { if val.is_true() { Ordering::Less } else { Ordering::Greater } }) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/removed/mod.rs
crates/nu-command/src/removed/mod.rs
mod format; mod let_env; mod removed_commands; pub use format::DateFormat; pub use let_env::LetEnv; pub use removed_commands::*;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/removed/format.rs
crates/nu-command/src/removed/format.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct DateFormat; impl Command for DateFormat { fn name(&self) -> &str { "date format" } fn signature(&self) -> Signature { Signature::build("date format") .input_output_types(vec![ (Type::Date, Type::String), (Type::String, Type::String), ]) .allow_variants_without_examples(true) // https://github.com/nushell/nushell/issues/7032 .switch("list", "lists strftime cheatsheet", Some('l')) .optional( "format string", SyntaxShape::String, "The desired date format.", ) .category(Category::Removed) } fn description(&self) -> &str { "Removed command: use `format date` instead." } fn run( &self, _engine_state: &EngineState, _stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { Err(nu_protocol::ShellError::RemovedCommand { removed: self.name().to_string(), replacement: "format date".to_owned(), span: call.head, }) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/removed/removed_commands.rs
crates/nu-command/src/removed/removed_commands.rs
use std::collections::HashMap; /// Return map of <removed_command_name, new_command_name> /// This covers simple removed commands nicely, but it's not great for deprecating /// subcommands like `foo bar` where `foo` is still a valid command. /// For those, it's currently easiest to have a "stub" command that just returns an error. pub fn removed_commands() -> HashMap<String, String> { [ ("fetch".to_string(), "http get".to_string()), ("post".to_string(), "http post".to_string()), ("benchmark".to_string(), "timeit".to_string()), ] .into_iter() .collect() }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/removed/let_env.rs
crates/nu-command/src/removed/let_env.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct LetEnv; impl Command for LetEnv { fn name(&self) -> &str { "let-env" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![(Type::Nothing, Type::Nothing)]) .allow_variants_without_examples(true) .optional("var_name", SyntaxShape::String, "Variable name.") .optional( "initial_value", SyntaxShape::Keyword(b"=".to_vec(), Box::new(SyntaxShape::MathExpression)), "Equals sign followed by value.", ) .category(Category::Removed) } fn description(&self) -> &str { "`let-env FOO = ...` has been removed, use `$env.FOO = ...` instead." } fn run( &self, _: &EngineState, _: &mut Stack, call: &Call, _: PipelineData, ) -> Result<PipelineData, ShellError> { Err(nu_protocol::ShellError::RemovedCommand { removed: self.name().to_string(), replacement: "$env.<environment variable> = ...".to_owned(), span: call.head, }) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/system/complete.rs
crates/nu-command/src/system/complete.rs
use nu_engine::command_prelude::*; use nu_protocol::OutDest; #[derive(Clone)] pub struct Complete; impl Command for Complete { fn name(&self) -> &str { "complete" } fn signature(&self) -> Signature { Signature::build("complete") .category(Category::System) .input_output_types(vec![(Type::Any, Type::record())]) } fn description(&self) -> &str { "Capture the outputs and exit code from an external piped in command in a nushell table." } fn extra_description(&self) -> &str { r#"In order to capture stdout, stderr, and exit_code, externally piped in commands need to be wrapped with `do`"# } fn run( &self, _engine_state: &EngineState, _stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; match input { PipelineData::ByteStream(stream, ..) => { let Ok(child) = stream.into_child() else { return Err(ShellError::GenericError { error: "Complete only works with external commands".into(), msg: "complete only works on external commands".into(), span: Some(call.head), help: None, inner: vec![], }); }; let output = child.wait_with_output()?; let exit_code = output.exit_status.code(); let mut record = Record::new(); if let Some(stdout) = output.stdout { record.push( "stdout", match String::from_utf8(stdout) { Ok(str) => Value::string(str, head), Err(err) => Value::binary(err.into_bytes(), head), }, ); } if let Some(stderr) = output.stderr { record.push( "stderr", match String::from_utf8(stderr) { Ok(str) => Value::string(str, head), Err(err) => Value::binary(err.into_bytes(), head), }, ); } record.push("exit_code", Value::int(exit_code.into(), head)); Ok(Value::record(record, call.head).into_pipeline_data()) } // bubble up errors from the previous command PipelineData::Value(Value::Error { error, .. }, _) => Err(*error), _ => Err(ShellError::GenericError { error: "Complete only works with external commands".into(), msg: "complete only works on external commands".into(), span: Some(head), help: None, inner: vec![], }), } } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Run the external command to completion, capturing stdout, stderr, and exit_code", example: "^external arg1 | complete", result: None, }] } fn pipe_redirection(&self) -> (Option<OutDest>, Option<OutDest>) { (Some(OutDest::PipeSeparate), Some(OutDest::PipeSeparate)) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/system/run_external.rs
crates/nu-command/src/system/run_external.rs
use nu_cmd_base::hook::eval_hook; use nu_engine::{command_prelude::*, env_to_strings}; use nu_path::{AbsolutePath, dots::expand_ndots_safe, expand_tilde}; use nu_protocol::{ ByteStream, NuGlob, OutDest, Signals, UseAnsiColoring, did_you_mean, process::{ChildProcess, PostWaitCallback}, shell_error::io::IoError, }; use nu_system::{ForegroundChild, kill_by_pid}; use nu_utils::IgnoreCaseExt; use pathdiff::diff_paths; #[cfg(windows)] use std::os::windows::process::CommandExt; use std::{ borrow::Cow, ffi::{OsStr, OsString}, io::Write, path::{Path, PathBuf}, process::Stdio, sync::Arc, thread, }; #[derive(Clone)] pub struct External; impl Command for External { fn name(&self) -> &str { "run-external" } fn description(&self) -> &str { "Runs external command." } fn extra_description(&self) -> &str { r#"All externals are run with this command, whether you call it directly with `run-external external` or use `external` or `^external`. If you create a custom command with this name, that will be used instead."# } fn signature(&self) -> nu_protocol::Signature { Signature::build(self.name()) .input_output_types(vec![(Type::Any, Type::Any)]) .rest( "command", SyntaxShape::OneOf(vec![SyntaxShape::GlobPattern, SyntaxShape::Any]), "External command to run, with arguments.", ) .category(Category::System) } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let cwd = engine_state.cwd(Some(stack))?; let rest = call.rest::<Value>(engine_state, stack, 0)?; let name_args = rest.split_first().map(|(x, y)| (x, y.to_vec())); let Some((name, mut call_args)) = name_args else { return Err(ShellError::MissingParameter { param_name: "no command given".into(), span: call.head, }); }; let name_str: Cow<str> = match &name { Value::Glob { val, .. } => Cow::Borrowed(val), Value::String { val, .. } => Cow::Borrowed(val), Value::List { vals, .. } => { let Some((first, args)) = vals.split_first() else { return Err(ShellError::MissingParameter { param_name: "external command given as list empty".into(), span: call.head, }); }; // Prepend elements in command list to the list of arguments except the first call_args.splice(0..0, args.to_vec()); first.coerce_str()? } _ => Cow::Owned(name.clone().coerce_into_string()?), }; let expanded_name = match &name { // Expand tilde and ndots on the name if it's a bare string / glob (#13000) Value::Glob { no_expand, .. } if !*no_expand => { expand_ndots_safe(expand_tilde(&*name_str)) } _ => Path::new(&*name_str).to_owned(), }; let paths = nu_engine::env::path_str(engine_state, stack, call.head).unwrap_or_default(); // On Windows, the user could have run the cmd.exe built-in commands "assoc" // and "ftype" to create a file association for an arbitrary file extension. // They then could have added that extension to the PATHEXT environment variable. // For example, a nushell script with extension ".nu" can be set up with // "assoc .nu=nuscript" and "ftype nuscript=C:\path\to\nu.exe '%1' %*", // and then by adding ".NU" to PATHEXT. In this case we use the which command, // which will find the executable with or without the extension. If "which" // returns true, that means that we've found the script and we believe the // user wants to use the windows association to run the script. The only // easy way to do this is to run cmd.exe with the script as an argument. // File extensions of .COM, .EXE, .BAT, and .CMD are ignored because Windows // can run those files directly. PS1 files are also ignored and that // extension is handled in a separate block below. let pathext_script_in_windows = if cfg!(windows) { if let Some(executable) = which(&expanded_name, &paths, cwd.as_ref()) { let ext = executable .extension() .unwrap_or_default() .to_string_lossy() .to_uppercase(); !["COM", "EXE", "BAT", "CMD", "PS1"] .iter() .any(|c| *c == ext) } else { false } } else { false }; // let's make sure it's a .ps1 script, but only on Windows let (potential_powershell_script, path_to_ps1_executable) = if cfg!(windows) { if let Some(executable) = which(&expanded_name, &paths, cwd.as_ref()) { let ext = executable .extension() .unwrap_or_default() .to_string_lossy() .to_uppercase(); (ext == "PS1", Some(executable)) } else { (false, None) } } else { (false, None) }; // Find the absolute path to the executable. On Windows, set the // executable to "cmd.exe" if it's a CMD internal command. If the // command is not found, display a helpful error message. let executable = if cfg!(windows) && (is_cmd_internal_command(&name_str) || pathext_script_in_windows) { PathBuf::from("cmd.exe") } else if cfg!(windows) && potential_powershell_script && path_to_ps1_executable.is_some() { // If we're on Windows and we're trying to run a PowerShell script, we'll use // `powershell.exe` to run it. We shouldn't have to check for powershell.exe because // it's automatically installed on all modern windows systems. PathBuf::from("powershell.exe") } else { // Determine the PATH to be used and then use `which` to find it - though this has no // effect if it's an absolute path already let Some(executable) = which(&expanded_name, &paths, cwd.as_ref()) else { return Err(command_not_found( &name_str, call.head, engine_state, stack, &cwd, )); }; executable }; // Create the command. let mut command = std::process::Command::new(&executable); // Configure PWD. command.current_dir(cwd); // Configure environment variables. let envs = env_to_strings(engine_state, stack)?; command.env_clear(); command.envs(envs); // Configure args. let args = eval_external_arguments(engine_state, stack, call_args)?; #[cfg(windows)] if is_cmd_internal_command(&name_str) || pathext_script_in_windows { // The /D flag disables execution of AutoRun commands from registry. // The /C flag followed by a command name instructs CMD to execute // that command and quit. command.args(["/D", "/C", &expanded_name.to_string_lossy()]); for arg in &args { command.raw_arg(escape_cmd_argument(arg)?); } } else if potential_powershell_script { command.args([ "-File", &path_to_ps1_executable.unwrap_or_default().to_string_lossy(), ]); command.args(args.into_iter().map(|s| s.item)); } else { command.args(args.into_iter().map(|s| s.item)); } #[cfg(not(windows))] command.args(args.into_iter().map(|s| s.item)); // Configure stdout and stderr. If both are set to `OutDest::Pipe`, // we'll set up a pipe that merges two streams into one. let stdout = stack.stdout(); let stderr = stack.stderr(); let merged_stream = if matches!(stdout, OutDest::Pipe) && matches!(stderr, OutDest::Pipe) { let (reader, writer) = os_pipe::pipe().map_err(|err| IoError::new(err, call.head, None))?; command.stdout( writer .try_clone() .map_err(|err| IoError::new(err, call.head, None))?, ); command.stderr(writer); Some(reader) } else { if engine_state.is_background_job() && matches!(stdout, OutDest::Inherit | OutDest::Print) { command.stdout(Stdio::null()); } else { command.stdout( Stdio::try_from(stdout).map_err(|err| IoError::new(err, call.head, None))?, ); } if engine_state.is_background_job() && matches!(stderr, OutDest::Inherit | OutDest::Print) { command.stderr(Stdio::null()); } else { command.stderr( Stdio::try_from(stderr).map_err(|err| IoError::new(err, call.head, None))?, ); } None }; // Configure stdin. We'll try connecting input to the child process // directly. If that's not possible, we'll set up a pipe and spawn a // thread to copy data into the child process. let data_to_copy_into_stdin = match input { PipelineData::ByteStream(stream, metadata) => match stream.into_stdio() { Ok(stdin) => { command.stdin(stdin); None } Err(stream) => { command.stdin(Stdio::piped()); Some(PipelineData::byte_stream(stream, metadata)) } }, PipelineData::Empty => { command.stdin(Stdio::inherit()); None } value => { command.stdin(Stdio::piped()); Some(value) } }; // Log the command we're about to run in case it's useful for debugging purposes. log::trace!("run-external spawning: {command:?}"); // Spawn the child process. On Unix, also put the child process to // foreground if we're in an interactive session. #[cfg(windows)] let child = ForegroundChild::spawn(command); #[cfg(unix)] let child = ForegroundChild::spawn( command, engine_state.is_interactive, engine_state.is_background_job(), &engine_state.pipeline_externals_state, ); let mut child = child.map_err(|err| { let context = format!("Could not spawn foreground child: {err}"); IoError::new_internal(err, context, nu_protocol::location!()) })?; if let Some(thread_job) = engine_state.current_thread_job() && !thread_job.try_add_pid(child.pid()) { kill_by_pid(child.pid().into()).map_err(|err| { ShellError::Io(IoError::new_internal( err, "Could not spawn external stdin worker", nu_protocol::location!(), )) })?; } // If we need to copy data into the child process, do it now. if let Some(data) = data_to_copy_into_stdin { let stdin = child.as_mut().stdin.take().expect("stdin is piped"); let engine_state = engine_state.clone(); let stack = stack.clone(); thread::Builder::new() .name("external stdin worker".into()) .spawn(move || { let _ = write_pipeline_data(engine_state, stack, data, stdin); }) .map_err(|err| { IoError::new_with_additional_context( err, call.head, None, "Could not spawn external stdin worker", ) })?; } let child_pid = child.pid(); // Wrap the output into a `PipelineData::byte_stream`. let mut child = ChildProcess::new( child, merged_stream, matches!(stderr, OutDest::Pipe), call.head, Some(PostWaitCallback::for_job_control( engine_state, Some(child_pid), executable .as_path() .file_name() .and_then(|it| it.to_str()) .map(|it| it.to_string()), )), )?; if matches!(stdout, OutDest::Pipe | OutDest::PipeSeparate) || matches!(stderr, OutDest::Pipe | OutDest::PipeSeparate) { child.ignore_error(true); } Ok(PipelineData::byte_stream( ByteStream::child(child, call.head), None, )) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Run an external command", example: r#"run-external "echo" "-n" "hello""#, result: None, }, Example { description: "Redirect stdout from an external command into the pipeline", example: r#"run-external "echo" "-n" "hello" | split chars"#, result: None, }, Example { description: "Redirect stderr from an external command into the pipeline", example: r#"run-external "nu" "-c" "print -e hello" e>| split chars"#, result: None, }, ] } } /// Evaluate all arguments, performing expansions when necessary. pub fn eval_external_arguments( engine_state: &EngineState, stack: &mut Stack, call_args: Vec<Value>, ) -> Result<Vec<Spanned<OsString>>, ShellError> { let cwd = engine_state.cwd(Some(stack))?; let mut args: Vec<Spanned<OsString>> = Vec::with_capacity(call_args.len()); for arg in call_args { let span = arg.span(); match arg { // Expand globs passed to run-external Value::Glob { val, no_expand, .. } if !no_expand => args.extend( expand_glob( &val, cwd.as_std_path(), span, engine_state.signals().clone(), )? .into_iter() .map(|s| s.into_spanned(span)), ), other => args .push(OsString::from(coerce_into_string(engine_state, other)?).into_spanned(span)), } } Ok(args) } /// Custom `coerce_into_string()`, including globs, since those are often args to `run-external` /// as well fn coerce_into_string(engine_state: &EngineState, val: Value) -> Result<String, ShellError> { match val { Value::List { .. } => Err(ShellError::CannotPassListToExternal { arg: String::from_utf8_lossy(engine_state.get_span_contents(val.span())).into_owned(), span: val.span(), }), Value::Glob { val, .. } => Ok(val), _ => val.coerce_into_string(), } } /// Performs glob expansion on `arg`. If the expansion found no matches or the pattern /// is not a valid glob, then this returns the original string as the expansion result. /// /// Note: This matches the default behavior of Bash, but is known to be /// error-prone. We might want to change this behavior in the future. fn expand_glob( arg: &str, cwd: &Path, span: Span, signals: Signals, ) -> Result<Vec<OsString>, ShellError> { // For an argument that isn't a glob, just do the `expand_tilde` // and `expand_ndots` expansion if !nu_glob::is_glob(arg) { let path = expand_ndots_safe(expand_tilde(arg)); return Ok(vec![path.into()]); } // We must use `nu_engine::glob_from` here, in order to ensure we get paths from the correct // dir let glob = NuGlob::Expand(arg.to_owned()).into_spanned(span); if let Ok((prefix, matches)) = nu_engine::glob_from(&glob, cwd, span, None, signals.clone()) { let mut result: Vec<OsString> = vec![]; for m in matches { signals.check(&span)?; if let Ok(arg) = m { let arg = resolve_globbed_path_to_cwd_relative(arg, prefix.as_ref(), cwd); result.push(arg.into()); } else { result.push(arg.into()); } } // FIXME: do we want to special-case this further? We might accidentally expand when they don't // intend to if result.is_empty() { result.push(arg.into()); } Ok(result) } else { Ok(vec![arg.into()]) } } fn resolve_globbed_path_to_cwd_relative( path: PathBuf, prefix: Option<&PathBuf>, cwd: &Path, ) -> PathBuf { if let Some(prefix) = prefix { if let Ok(remainder) = path.strip_prefix(prefix) { let new_prefix = if let Some(pfx) = diff_paths(prefix, cwd) { pfx } else { prefix.to_path_buf() }; new_prefix.join(remainder) } else { path } } else { path } } /// Write `PipelineData` into `writer`. If `PipelineData` is not binary, it is /// first rendered using the `table` command. /// /// Note: Avoid using this function when piping data from an external command to /// another external command, because it copies data unnecessarily. Instead, /// extract the pipe from the `PipelineData::byte_stream` of the first command /// and hand it to the second command directly. fn write_pipeline_data( mut engine_state: EngineState, mut stack: Stack, data: PipelineData, mut writer: impl Write, ) -> Result<(), ShellError> { if let PipelineData::ByteStream(stream, ..) = data { stream.write_to(writer)?; } else if let PipelineData::Value(Value::Binary { val, .. }, ..) = data { writer.write_all(&val).map_err(|err| { IoError::new_internal( err, "Could not write pipeline data", nu_protocol::location!(), ) })?; } else { stack.start_collect_value(); // Turn off color as we pass data through Arc::make_mut(&mut engine_state.config).use_ansi_coloring = UseAnsiColoring::False; // Invoke the `table` command. let output = crate::Table.run(&engine_state, &mut stack, &Call::new(Span::unknown()), data)?; // Write the output. for value in output { let bytes = value.coerce_into_binary()?; writer.write_all(&bytes).map_err(|err| { IoError::new_internal( err, "Could not write pipeline data", nu_protocol::location!(), ) })?; } } Ok(()) } /// Returns a helpful error message given an invalid command name, pub fn command_not_found( name: &str, span: Span, engine_state: &EngineState, stack: &mut Stack, cwd: &AbsolutePath, ) -> ShellError { // Run the `command_not_found` hook if there is one. if let Some(hook) = &stack.get_config(engine_state).hooks.command_not_found { let mut stack = stack.start_collect_value(); // Set a special environment variable to avoid infinite loops when the // `command_not_found` hook triggers itself. let canary = "ENTERED_COMMAND_NOT_FOUND"; if stack.has_env_var(engine_state, canary) { return ShellError::ExternalCommand { label: format!( "Command {name} not found while running the `command_not_found` hook" ), help: "Make sure the `command_not_found` hook itself does not use unknown commands" .into(), span, }; } stack.add_env_var(canary.into(), Value::bool(true, Span::unknown())); let output = eval_hook( &mut engine_state.clone(), &mut stack, None, vec![("cmd_name".into(), Value::string(name, span))], hook, "command_not_found", ); // Remove the special environment variable that we just set. stack.remove_env_var(engine_state, canary); match output { Ok(PipelineData::Value(Value::String { val, .. }, ..)) => { return ShellError::ExternalCommand { label: format!("Command `{name}` not found"), help: val, span, }; } Err(err) => { return err; } _ => { // The hook did not return a string, so ignore it. } } } // If the name is one of the removed commands, recommend a replacement. if let Some(replacement) = crate::removed_commands().get(&name.to_lowercase()) { return ShellError::RemovedCommand { removed: name.to_lowercase(), replacement: replacement.clone(), span, }; } // The command might be from another module. Try to find it. if let Some(module) = engine_state.which_module_has_decl(name.as_bytes(), &[]) { let module = String::from_utf8_lossy(module); // Is the command already imported? let full_name = format!("{module} {name}"); if engine_state.find_decl(full_name.as_bytes(), &[]).is_some() { return ShellError::ExternalCommand { label: format!("Command `{name}` not found"), help: format!("Did you mean `{full_name}`?"), span, }; } else { return ShellError::ExternalCommand { label: format!("Command `{name}` not found"), help: format!( "A command with that name exists in module `{module}`. Try importing it with `use`" ), span, }; } } // Try to match the name with the search terms of existing commands. let signatures = engine_state.get_signatures_and_declids(false); if let Some((sig, _)) = signatures.iter().find(|(sig, _)| { sig.search_terms .iter() .any(|term| term.to_folded_case() == name.to_folded_case()) }) { return ShellError::ExternalCommand { label: format!("Command `{name}` not found"), help: format!("Did you mean `{}`?", sig.name), span, }; } // Try a fuzzy search on the names of all existing commands. if let Some(cmd) = did_you_mean(signatures.iter().map(|(sig, _)| &sig.name), name) { // The user is invoking an external command with the same name as a // built-in command. Remind them of this. if cmd == name { return ShellError::ExternalCommand { label: format!("Command `{name}` not found"), help: "There is a built-in command with the same name".into(), span, }; } return ShellError::ExternalCommand { label: format!("Command `{name}` not found"), help: format!("Did you mean `{cmd}`?"), span, }; } // If we find a file, it's likely that the user forgot to set permissions if cwd.join(name).is_file() { return ShellError::ExternalCommand { label: format!("Command `{name}` not found"), help: format!( "`{name}` refers to a file that is not executable. Did you forget to set execute permissions?" ), span, }; } // We found nothing useful. Give up and return a generic error message. ShellError::ExternalCommand { label: format!("Command `{name}` not found"), help: format!("`{name}` is neither a Nushell built-in or a known external command"), span, } } /// Searches for the absolute path of an executable by name. `.bat` and `.cmd` /// files are recognized as executables on Windows. /// /// This is a wrapper around `which::which_in()` except that, on Windows, it /// also searches the current directory before any PATH entries. /// /// Note: the `which.rs` crate always uses PATHEXT from the environment. As /// such, changing PATHEXT within Nushell doesn't work without updating the /// actual environment of the Nushell process. pub fn which(name: impl AsRef<OsStr>, paths: &str, cwd: &Path) -> Option<PathBuf> { #[cfg(windows)] let paths = format!("{};{}", cwd.display(), paths); which::which_in(name, Some(paths), cwd).ok() } /// Returns true if `name` is a (somewhat useful) CMD internal command. The full /// list can be found at <https://ss64.com/nt/syntax-internal.html> fn is_cmd_internal_command(name: &str) -> bool { const COMMANDS: &[&str] = &[ "ASSOC", "CLS", "ECHO", "FTYPE", "MKLINK", "PAUSE", "START", "VER", "VOL", ]; COMMANDS.iter().any(|cmd| cmd.eq_ignore_ascii_case(name)) } /// Returns true if a string contains CMD special characters. fn has_cmd_special_character(s: impl AsRef<[u8]>) -> bool { s.as_ref() .iter() .any(|b| matches!(b, b'<' | b'>' | b'&' | b'|' | b'^')) } /// Escape an argument for CMD internal commands. The result can be safely passed to `raw_arg()`. #[cfg_attr(not(windows), allow(dead_code))] fn escape_cmd_argument(arg: &Spanned<OsString>) -> Result<Cow<'_, OsStr>, ShellError> { let Spanned { item: arg, span } = arg; let bytes = arg.as_encoded_bytes(); if bytes.iter().any(|b| matches!(b, b'\r' | b'\n' | b'%')) { // \r and \n truncate the rest of the arguments and % can expand environment variables Err(ShellError::ExternalCommand { label: "Arguments to CMD internal commands cannot contain new lines or percent signs '%'" .into(), help: "some characters currently cannot be securely escaped".into(), span: *span, }) } else if bytes.contains(&b'"') { // If `arg` is already quoted by double quotes, confirm there's no // embedded double quotes, then leave it as is. if bytes.iter().filter(|b| **b == b'"').count() == 2 && bytes.starts_with(b"\"") && bytes.ends_with(b"\"") { Ok(Cow::Borrowed(arg)) } else { Err(ShellError::ExternalCommand { label: "Arguments to CMD internal commands cannot contain embedded double quotes" .into(), help: "this case currently cannot be securely handled".into(), span: *span, }) } } else if bytes.contains(&b' ') || has_cmd_special_character(bytes) { // If `arg` contains space or special characters, quote the entire argument by double quotes. let mut new_str = OsString::new(); new_str.push("\""); new_str.push(arg); new_str.push("\""); Ok(Cow::Owned(new_str)) } else { // FIXME?: what if `arg.is_empty()`? Ok(Cow::Borrowed(arg)) } } #[cfg(test)] mod test { use super::*; use nu_test_support::{fs::Stub, playground::Playground}; #[test] fn test_expand_glob() { Playground::setup("test_expand_glob", |dirs, play| { play.with_files(&[Stub::EmptyFile("a.txt"), Stub::EmptyFile("b.txt")]); let cwd = dirs.test().as_std_path(); let actual = expand_glob("*.txt", cwd, Span::unknown(), Signals::empty()).unwrap(); let expected = &["a.txt", "b.txt"]; assert_eq!(actual, expected); let actual = expand_glob("./*.txt", cwd, Span::unknown(), Signals::empty()).unwrap(); assert_eq!(actual, expected); let actual = expand_glob("'*.txt'", cwd, Span::unknown(), Signals::empty()).unwrap(); let expected = &["'*.txt'"]; assert_eq!(actual, expected); let actual = expand_glob(".", cwd, Span::unknown(), Signals::empty()).unwrap(); let expected = &["."]; assert_eq!(actual, expected); let actual = expand_glob("./a.txt", cwd, Span::unknown(), Signals::empty()).unwrap(); let expected = &["./a.txt"]; assert_eq!(actual, expected); let actual = expand_glob("[*.txt", cwd, Span::unknown(), Signals::empty()).unwrap(); let expected = &["[*.txt"]; assert_eq!(actual, expected); let actual = expand_glob("~/foo.txt", cwd, Span::unknown(), Signals::empty()).unwrap(); let home = dirs::home_dir().expect("failed to get home dir"); let expected: Vec<OsString> = vec![home.join("foo.txt").into()]; assert_eq!(actual, expected); }) } #[test] fn test_write_pipeline_data() { let mut engine_state = EngineState::new(); let stack = Stack::new(); let cwd = std::env::current_dir() .unwrap() .into_os_string() .into_string() .unwrap(); // set the PWD environment variable as it's required now engine_state.add_env_var("PWD".into(), Value::string(cwd, Span::test_data())); let mut buf = vec![]; let input = PipelineData::empty(); write_pipeline_data(engine_state.clone(), stack.clone(), input, &mut buf).unwrap(); assert_eq!(buf, b""); let mut buf = vec![]; let input = PipelineData::value(Value::string("foo", Span::unknown()), None); write_pipeline_data(engine_state.clone(), stack.clone(), input, &mut buf).unwrap(); assert_eq!(buf, b"foo"); let mut buf = vec![]; let input = PipelineData::value(Value::binary(b"foo", Span::unknown()), None); write_pipeline_data(engine_state.clone(), stack.clone(), input, &mut buf).unwrap(); assert_eq!(buf, b"foo"); let mut buf = vec![]; let input = PipelineData::byte_stream( ByteStream::read( b"foo".as_slice(), Span::unknown(), Signals::empty(), ByteStreamType::Unknown, ), None, ); write_pipeline_data(engine_state.clone(), stack.clone(), input, &mut buf).unwrap(); assert_eq!(buf, b"foo"); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/system/registry_query.rs
crates/nu-command/src/system/registry_query.rs
use nu_engine::command_prelude::*; use nu_protocol::shell_error::io::IoError; use windows::{Win32::System::Environment::ExpandEnvironmentStringsW, core::PCWSTR}; use winreg::{RegKey, enums::*, types::FromRegValue}; #[derive(Clone)] pub struct RegistryQuery; impl Command for RegistryQuery { fn name(&self) -> &str { "registry query" } fn signature(&self) -> Signature { Signature::build("registry query") .input_output_types(vec![(Type::Nothing, Type::Any)]) .switch("hkcr", "query the hkey_classes_root hive", None) .switch("hkcu", "query the hkey_current_user hive", None) .switch("hklm", "query the hkey_local_machine hive", None) .switch("hku", "query the hkey_users hive", None) .switch("hkpd", "query the hkey_performance_data hive", None) .switch("hkpt", "query the hkey_performance_text hive", None) .switch("hkpnls", "query the hkey_performance_nls_text hive", None) .switch("hkcc", "query the hkey_current_config hive", None) .switch("hkdd", "query the hkey_dyn_data hive", None) .switch( "hkculs", "query the hkey_current_user_local_settings hive", None, ) .switch( "no-expand", "do not expand %ENV% placeholders in REG_EXPAND_SZ", Some('u'), ) .required("key", SyntaxShape::String, "Registry key to query.") .optional( "value", SyntaxShape::String, "Optionally supply a registry value to query.", ) .category(Category::System) } fn description(&self) -> &str { "Query the Windows registry." } fn extra_description(&self) -> &str { "Currently supported only on Windows systems." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { registry_query(engine_state, stack, call) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Query the HKEY_CURRENT_USER hive", example: "registry query --hkcu environment", result: None, }, Example { description: "Query the HKEY_LOCAL_MACHINE hive", example: r"registry query --hklm 'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'", result: None, }, ] } } fn registry_query( engine_state: &EngineState, stack: &mut Stack, call: &Call, ) -> Result<PipelineData, ShellError> { let call_span = call.head; let skip_expand = call.has_flag(engine_state, stack, "no-expand")?; let registry_key: Spanned<String> = call.req(engine_state, stack, 0)?; let registry_key_span = &registry_key.clone().span; let registry_value: Option<Spanned<String>> = call.opt(engine_state, stack, 1)?; let reg_hive = get_reg_hive(engine_state, stack, call)?; let reg_key = reg_hive .open_subkey(registry_key.item) .map_err(|err| IoError::new(err, *registry_key_span, None))?; if registry_value.is_none() { let mut reg_values = vec![]; for (name, val) in reg_key.enum_values().flatten() { let reg_type = format!("{:?}", val.vtype); let nu_value = reg_value_to_nu_value(val, call_span, skip_expand); reg_values.push(Value::record( record! { "name" => Value::string(name, call_span), "value" => nu_value, "type" => Value::string(reg_type, call_span), }, *registry_key_span, )) } Ok(reg_values.into_pipeline_data(call_span, engine_state.signals().clone())) } else { match registry_value { Some(value) => { let reg_value = reg_key.get_raw_value(value.item.as_str()); match reg_value { Ok(val) => { let reg_type = format!("{:?}", val.vtype); let nu_value = reg_value_to_nu_value(val, call_span, skip_expand); Ok(Value::record( record! { "name" => Value::string(value.item, call_span), "value" => nu_value, "type" => Value::string(reg_type, call_span), }, value.span, ) .into_pipeline_data()) } Err(_) => Err(ShellError::GenericError { error: "Unable to find registry key/value".into(), msg: format!("Registry value: {} was not found", value.item), span: Some(value.span), help: None, inner: vec![], }), } } None => Ok(Value::nothing(call_span).into_pipeline_data()), } } } fn get_reg_hive( engine_state: &EngineState, stack: &mut Stack, call: &Call, ) -> Result<RegKey, ShellError> { let flags = [ "hkcr", "hkcu", "hklm", "hku", "hkpd", "hkpt", "hkpnls", "hkcc", "hkdd", "hkculs", ] .iter() .copied() .filter_map(|flag| match call.has_flag(engine_state, stack, flag) { Ok(true) => Some(Ok(flag)), Ok(false) => None, Err(e) => Some(Err(e)), }) .collect::<Result<Vec<_>, ShellError>>()?; if flags.len() > 1 { return Err(ShellError::GenericError { error: "Only one registry key can be specified".into(), msg: "Only one registry key can be specified".into(), span: Some(call.head), help: None, inner: vec![], }); } let hive = flags.first().copied().unwrap_or("hkcu"); let hkey = match hive { "hkcr" => HKEY_CLASSES_ROOT, "hkcu" => HKEY_CURRENT_USER, "hklm" => HKEY_LOCAL_MACHINE, "hku" => HKEY_USERS, "hkpd" => HKEY_PERFORMANCE_DATA, "hkpt" => HKEY_PERFORMANCE_TEXT, "hkpnls" => HKEY_PERFORMANCE_NLSTEXT, "hkcc" => HKEY_CURRENT_CONFIG, "hkdd" => HKEY_DYN_DATA, "hkculs" => HKEY_CURRENT_USER_LOCAL_SETTINGS, _ => { return Err(ShellError::NushellFailedSpanned { msg: "Entered unreachable code".into(), label: "Unknown registry hive".into(), span: call.head, }); } }; Ok(RegKey::predef(hkey)) } fn reg_value_to_nu_value( mut reg_value: winreg::RegValue, call_span: Span, skip_expand: bool, ) -> nu_protocol::Value { match reg_value.vtype { REG_NONE => Value::nothing(call_span), REG_BINARY => Value::binary(reg_value.bytes, call_span), REG_MULTI_SZ => reg_value_to_nu_list_string(reg_value, call_span), REG_SZ | REG_EXPAND_SZ => reg_value_to_nu_string(reg_value, call_span, skip_expand), REG_DWORD | REG_DWORD_BIG_ENDIAN | REG_QWORD => reg_value_to_nu_int(reg_value, call_span), // This should be impossible, as registry symlinks should be automatically transparent // to the registry API as it's used by winreg, since it never uses REG_OPTION_OPEN_LINK. // If it happens, decode as if the link is a string; it should be a registry path string. REG_LINK => { reg_value.vtype = REG_SZ; reg_value_to_nu_string(reg_value, call_span, skip_expand) } // Decode these as binary; that seems to be the least bad option available to us. // REG_RESOURCE_LIST is a struct CM_RESOURCE_LIST. // REG_FULL_RESOURCE_DESCRIPTOR is a struct CM_FULL_RESOURCE_DESCRIPTOR. // REG_RESOURCE_REQUIREMENTS_LIST is a struct IO_RESOURCE_REQUIREMENTS_LIST. REG_RESOURCE_LIST | REG_FULL_RESOURCE_DESCRIPTOR | REG_RESOURCE_REQUIREMENTS_LIST => { reg_value.vtype = REG_BINARY; Value::binary(reg_value.bytes, call_span) } } } fn reg_value_to_nu_string( reg_value: winreg::RegValue, call_span: Span, skip_expand: bool, ) -> nu_protocol::Value { let value = String::from_reg_value(&reg_value) .expect("registry value type should be REG_SZ or REG_EXPAND_SZ"); // REG_EXPAND_SZ contains unexpanded references to environment variables, for example, %PATH%. // winreg not expanding these is arguably correct, as it's just wrapping raw registry access. // These placeholder-having strings work in *some* Windows contexts, but Rust's fs/path APIs // don't handle them, so they won't work in Nu unless we expand them here. Eagerly expanding the // strings here seems to be the least bad option. This is what PowerShell does, for example, // although reg.exe does not. We could do the substitution with our env, but the officially // correct way to expand these strings is to call Win32's ExpandEnvironmentStrings function. // ref: <https://learn.microsoft.com/en-us/windows/win32/sysinfo/registry-value-types> // We can skip the dance if the string doesn't actually have any unexpanded placeholders. if skip_expand || reg_value.vtype != REG_EXPAND_SZ || !value.contains('%') { return Value::string(value, call_span); } // The encoding dance is unfortunate since we read "Windows Unicode" from the registry, but // it's the most resilient option and avoids making potentially wrong alignment assumptions. let value_utf16 = value.encode_utf16().chain([0]).collect::<Vec<u16>>(); // Like most Win32 string functions, the return value is the number of TCHAR written, // or the required buffer size (in TCHAR) if the buffer is too small, or 0 for error. // Since we already checked for the case where no expansion is done, we can start with // an empty output buffer, since we expect to require at least one resize loop anyway. let mut out_buffer = vec![]; loop { match unsafe { ExpandEnvironmentStringsW(PCWSTR(value_utf16.as_ptr()), Some(&mut *out_buffer)) } { 0 => { // 0 means error, but we don't know what the error is. We could try to get // the error code with GetLastError, but that's a whole other can of worms. // Instead, we'll just return the original string and hope for the best. // Presumably, registry strings shouldn't ever cause this to error anyway. return Value::string(value, call_span); } size if size as usize <= out_buffer.len() => { // The buffer was large enough, so we're done. Remember to remove the trailing nul! let out_value_utf16 = &out_buffer[..size as usize - 1]; let out_value = String::from_utf16_lossy(out_value_utf16); return Value::string(out_value, call_span); } size => { // The buffer was too small, so we need to resize and try again. // Clear first to indicate we don't care about the old contents. out_buffer.clear(); out_buffer.resize(size as usize, 0); continue; } } } } #[test] fn no_expand_does_not_expand() { let unexpanded = "%AppData%"; let reg_val = || winreg::RegValue { bytes: unexpanded .encode_utf16() .chain([0]) .flat_map(u16::to_ne_bytes) .collect(), vtype: REG_EXPAND_SZ, }; // normally we do expand let nu_val_expanded = reg_value_to_nu_string(reg_val(), Span::unknown(), false); assert!(nu_val_expanded.coerce_string().is_ok()); assert_ne!(nu_val_expanded.coerce_string().unwrap(), unexpanded); // unless we skip expansion let nu_val_skip_expand = reg_value_to_nu_string(reg_val(), Span::unknown(), true); assert!(nu_val_skip_expand.coerce_string().is_ok()); assert_eq!(nu_val_skip_expand.coerce_string().unwrap(), unexpanded); } fn reg_value_to_nu_list_string(reg_value: winreg::RegValue, call_span: Span) -> nu_protocol::Value { let values = <Vec<String>>::from_reg_value(&reg_value) .expect("registry value type should be REG_MULTI_SZ") .into_iter() .map(|s| Value::string(s, call_span)); // There's no REG_MULTI_EXPAND_SZ, so no need to do placeholder expansion here. Value::list(values.collect(), call_span) } fn reg_value_to_nu_int(reg_value: winreg::RegValue, call_span: Span) -> nu_protocol::Value { let value = match reg_value.vtype { // See discussion here https://github.com/nushell/nushell/pull/10806#issuecomment-1791832088 // "The unwraps here are effectively infallible...", so I changed them to expects. REG_DWORD => u32::from_reg_value(&reg_value) .expect("registry value type should be REG_DWORD") as i64, REG_DWORD_BIG_ENDIAN => { // winreg (v0.51.0) doesn't natively decode REG_DWORD_BIG_ENDIAN u32::from_be_bytes(unsafe { *reg_value.bytes.as_ptr().cast() }) as i64 } REG_QWORD => u64::from_reg_value(&reg_value) .expect("registry value type should be REG_QWORD") as i64, _ => unreachable!( "registry value type should be REG_DWORD, REG_DWORD_BIG_ENDIAN, or REG_QWORD" ), }; Value::int(value, call_span) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/system/uname.rs
crates/nu-command/src/system/uname.rs
use nu_engine::command_prelude::*; use nu_protocol::{Value, record}; use uucore::{localized_help_template, translate}; #[derive(Clone)] pub struct UName; impl Command for UName { fn name(&self) -> &str { "uname" } fn signature(&self) -> Signature { Signature::build("uname") .input_output_types(vec![(Type::Nothing, Type::table())]) .category(Category::System) } fn description(&self) -> &str { "Print certain system information using uutils/coreutils uname." } fn search_terms(&self) -> Vec<&str> { // add other terms? vec!["system", "coreutils"] } fn run( &self, _engine_state: &EngineState, _stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { // setup the uutils error translation let _ = localized_help_template("uname"); let span = call.head; // Simulate `uname -all` is called every time let opts = uu_uname::Options { all: true, kernel_name: false, nodename: false, kernel_release: false, kernel_version: false, machine: false, processor: false, hardware_platform: false, os: false, }; let output = uu_uname::UNameOutput::new(&opts).map_err(|e| ShellError::GenericError { error: format!("{e}"), msg: translate!(&e.to_string()), span: None, help: None, inner: Vec::new(), })?; let outputs = [ output.kernel_name, output.nodename, output.kernel_release, output.kernel_version, output.machine, output.os, ]; let outputs = outputs .iter() .map(|name| { Ok(name .as_ref() .ok_or("unknown") .map_err(|_| ShellError::NotFound { span })? .to_string()) }) .collect::<Result<Vec<String>, ShellError>>()?; Ok(PipelineData::value( Value::record( record! { "kernel-name" => Value::string(outputs[0].clone(), span), "nodename" => Value::string(outputs[1].clone(), span), "kernel-release" => Value::string(outputs[2].clone(), span), "kernel-version" => Value::string(outputs[3].clone(), span), "machine" => Value::string(outputs[4].clone(), span), "operating-system" => Value::string(outputs[5].clone(), span), }, span, ), None, )) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Print all information", example: "uname", result: None, }] } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/system/registry.rs
crates/nu-command/src/system/registry.rs
use nu_engine::{command_prelude::*, get_full_help}; #[derive(Clone)] pub struct Registry; impl Command for Registry { fn name(&self) -> &str { "registry" } fn signature(&self) -> Signature { Signature::build("registry") .category(Category::System) .input_output_types(vec![(Type::Nothing, Type::String)]) } fn description(&self) -> &str { "Various commands for interacting with the system registry (Windows only)." } fn extra_description(&self) -> &str { "You must use one of the following subcommands. Using this command as-is will only produce this help message." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> std::result::Result<PipelineData, ShellError> { Ok(Value::string(get_full_help(self, engine_state, stack), call.head).into_pipeline_data()) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/system/which_.rs
crates/nu-command/src/system/which_.rs
use nu_engine::{command_prelude::*, env}; use nu_protocol::engine::CommandType; use std::collections::HashSet; use std::fs; use std::{ffi::OsStr, path::Path}; use which::sys; use which::sys::Sys; #[derive(Clone)] pub struct Which; impl Command for Which { fn name(&self) -> &str { "which" } fn signature(&self) -> Signature { Signature::build("which") .input_output_types(vec![(Type::Nothing, Type::table())]) .allow_variants_without_examples(true) .rest("applications", SyntaxShape::String, "Application(s).") .switch("all", "list all executables", Some('a')) .category(Category::System) } fn description(&self) -> &str { "Finds a program file, alias or custom command. If `application` is not provided, all deduplicated commands will be returned." } fn search_terms(&self) -> Vec<&str> { vec![ "find", "path", "location", "command", "whereis", // linux binary to find binary locations in path "get-command", // powershell command to find commands and binaries in path ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { which(engine_state, stack, call) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Find if the 'myapp' application is available", example: "which myapp", result: None, }, Example { description: "Find all executables across all paths without deduplication", example: "which -a", result: None, }, ] } } // Shortcut for creating an entry to the output table fn entry( arg: impl Into<String>, path: impl Into<String>, cmd_type: CommandType, span: Span, ) -> Value { Value::record( record! { "command" => Value::string(arg, span), "path" => Value::string(path, span), "type" => Value::string(cmd_type.to_string(), span), }, span, ) } fn get_entry_in_commands(engine_state: &EngineState, name: &str, span: Span) -> Option<Value> { if let Some(decl_id) = engine_state.find_decl(name.as_bytes(), &[]) { let decl = engine_state.get_decl(decl_id); Some(entry(name, "", decl.command_type(), span)) } else { None } } fn get_first_entry_in_path( item: &str, span: Span, cwd: impl AsRef<Path>, paths: impl AsRef<OsStr>, ) -> Option<Value> { which::which_in(item, Some(paths), cwd) .map(|path| entry(item, path.to_string_lossy(), CommandType::External, span)) .ok() } fn get_all_entries_in_path( item: &str, span: Span, cwd: impl AsRef<Path>, paths: impl AsRef<OsStr>, ) -> Vec<Value> { which::which_in_all(&item, Some(paths), cwd) .map(|iter| { iter.map(|path| entry(item, path.to_string_lossy(), CommandType::External, span)) .collect() }) .unwrap_or_default() } fn list_all_executables( engine_state: &EngineState, paths: impl AsRef<OsStr>, all: bool, ) -> Vec<Value> { let decls = engine_state.get_decls_sorted(false); let mut results = Vec::with_capacity(decls.len()); let mut seen_commands = HashSet::with_capacity(decls.len()); for (name_bytes, decl_id) in decls { let name = String::from_utf8_lossy(&name_bytes).to_string(); seen_commands.insert(name.clone()); let decl = engine_state.get_decl(decl_id); results.push(entry( name, String::new(), decl.command_type(), Span::unknown(), )); } // Add PATH executables let path_iter = sys::RealSys .env_split_paths(paths.as_ref()) .into_iter() .filter_map(|dir| fs::read_dir(dir).ok()) .flat_map(|entries| entries.flatten()) .map(|entry| entry.path()) .filter_map(|path| { if !path.is_executable() { return None; } let filename = path.file_name()?.to_string_lossy().to_string(); if !all && !seen_commands.insert(filename.clone()) { return None; } let full_path = path.to_string_lossy().to_string(); Some(entry( filename, full_path, CommandType::External, Span::unknown(), )) }); results.extend(path_iter); results } #[derive(Debug)] struct WhichArgs { applications: Vec<Spanned<String>>, all: bool, } fn which_single( application: Spanned<String>, all: bool, engine_state: &EngineState, cwd: impl AsRef<Path>, paths: impl AsRef<OsStr>, ) -> Vec<Value> { let (external, prog_name) = if application.item.starts_with('^') { (true, application.item[1..].to_string()) } else { (false, application.item.clone()) }; //If prog_name is an external command, don't search for nu-specific programs //If all is false, we can save some time by only searching for the first matching //program //This match handles all different cases match (all, external) { (true, true) => get_all_entries_in_path(&prog_name, application.span, cwd, paths), (true, false) => { let mut output: Vec<Value> = vec![]; if let Some(entry) = get_entry_in_commands(engine_state, &prog_name, application.span) { output.push(entry); } output.extend(get_all_entries_in_path( &prog_name, application.span, cwd, paths, )); output } (false, true) => get_first_entry_in_path(&prog_name, application.span, cwd, paths) .into_iter() .collect(), (false, false) => get_entry_in_commands(engine_state, &prog_name, application.span) .or_else(|| get_first_entry_in_path(&prog_name, application.span, cwd, paths)) .into_iter() .collect(), } } fn which( engine_state: &EngineState, stack: &mut Stack, call: &Call, ) -> Result<PipelineData, ShellError> { let head = call.head; let which_args = WhichArgs { applications: call.rest(engine_state, stack, 0)?, all: call.has_flag(engine_state, stack, "all")?, }; let mut output = vec![]; #[allow(deprecated)] let cwd = env::current_dir_str(engine_state, stack)?; let paths = env::path_str(engine_state, stack, head)?; if which_args.applications.is_empty() { return Ok(list_all_executables(engine_state, paths, which_args.all) .into_iter() .into_pipeline_data(head, engine_state.signals().clone())); } for app in which_args.applications { let values = which_single(app, which_args.all, engine_state, &cwd, &paths); output.extend(values); } Ok(output .into_iter() .into_pipeline_data(head, engine_state.signals().clone())) } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { crate::test_examples(Which) } } // -------------------- // Copied from https://docs.rs/is_executable/ v1.0.5 // Removed path.exists() check in `mod windows`. /// An extension trait for `std::fs::Path` providing an `is_executable` method. /// /// See the module documentation for examples. pub trait IsExecutable { /// Returns `true` if there is a file at the given path and it is /// executable. Returns `false` otherwise. /// /// See the module documentation for details. fn is_executable(&self) -> bool; } #[cfg(unix)] mod unix { use std::os::unix::fs::PermissionsExt; use std::path::Path; use super::IsExecutable; impl IsExecutable for Path { fn is_executable(&self) -> bool { let metadata = match self.metadata() { Ok(metadata) => metadata, Err(_) => return false, }; let permissions = metadata.permissions(); metadata.is_file() && permissions.mode() & 0o111 != 0 } } } #[cfg(target_os = "windows")] mod windows { use std::os::windows::ffi::OsStrExt; use std::path::Path; use windows::Win32::Storage::FileSystem::GetBinaryTypeW; use windows::core::PCWSTR; use super::IsExecutable; impl IsExecutable for Path { fn is_executable(&self) -> bool { // Check using file extension if let Some(pathext) = std::env::var_os("PATHEXT") && let Some(extension) = self.extension() { let extension = extension.to_string_lossy(); // Originally taken from: // https://github.com/nushell/nushell/blob/93e8f6c05e1e1187d5b674d6b633deb839c84899/crates/nu-cli/src/completion/command.rs#L64-L74 return pathext .to_string_lossy() .split(';') // Filter out empty tokens and ';' at the end .filter(|f| f.len() > 1) .any(|ext| { // Cut off the leading '.' character let ext = &ext[1..]; extension.eq_ignore_ascii_case(ext) }); } // Check using file properties // This code is only reached if there is no file extension or retrieving PATHEXT fails let windows_string: Vec<u16> = self.as_os_str().encode_wide().chain(Some(0)).collect(); let mut binary_type: u32 = 0; let result = unsafe { GetBinaryTypeW(PCWSTR(windows_string.as_ptr()), &mut binary_type) }; if result.is_ok() && let 0..=6 = binary_type { return true; } false } } } // For WASI, we can't check if a file is executable // Since wasm and wasi // is not supposed to add executables ideologically, // specify them collectively #[cfg(any(target_os = "wasi", target_family = "wasm"))] mod wasm { use std::path::Path; use super::IsExecutable; impl IsExecutable for Path { fn is_executable(&self) -> bool { false } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/system/mod.rs
crates/nu-command/src/system/mod.rs
mod complete; mod exec; mod nu_check; #[cfg(any( target_os = "android", target_os = "linux", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd", target_os = "macos", target_os = "windows" ))] mod ps; #[cfg(windows)] mod registry; #[cfg(windows)] mod registry_query; mod run_external; mod sys; mod uname; mod which_; pub use complete::Complete; pub use exec::Exec; pub use nu_check::NuCheck; #[cfg(any( target_os = "android", target_os = "linux", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd", target_os = "macos", target_os = "windows" ))] pub use ps::Ps; #[cfg(windows)] pub use registry::Registry; #[cfg(windows)] pub use registry_query::RegistryQuery; pub use run_external::{External, command_not_found, eval_external_arguments, which}; pub use sys::*; pub use uname::UName; pub use which_::Which;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/system/nu_check.rs
crates/nu-command/src/system/nu_check.rs
use nu_engine::{command_prelude::*, find_in_dirs_env, get_dirs_var_from_call}; use nu_parser::{parse, parse_module_block, parse_module_file_or_dir, unescape_unquote_string}; use nu_protocol::{ engine::{FileStack, StateWorkingSet}, shell_error::io::IoError, }; use std::path::{Path, PathBuf}; #[derive(Clone)] pub struct NuCheck; impl Command for NuCheck { fn name(&self) -> &str { "nu-check" } fn signature(&self) -> Signature { Signature::build("nu-check") .input_output_types(vec![ (Type::Nothing, Type::Bool), (Type::String, Type::Bool), (Type::List(Box::new(Type::Any)), Type::Bool), // FIXME Type::Any input added to disable pipeline input type checking, as run-time checks can raise undesirable type errors // which aren't caught by the parser. see https://github.com/nushell/nushell/pull/14922 for more details (Type::Any, Type::Bool), ]) // type is string to avoid automatically canonicalizing the path .optional("path", SyntaxShape::String, "File path to parse.") .switch("as-module", "Parse content as module", Some('m')) .switch("debug", "Show error messages", Some('d')) .category(Category::Strings) } fn description(&self) -> &str { "Validate and parse input content." } fn search_terms(&self) -> Vec<&str> { vec!["syntax", "parse", "debug"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let path_arg: Option<Spanned<String>> = call.opt(engine_state, stack, 0)?; let as_module = call.has_flag(engine_state, stack, "as-module")?; let is_debug = call.has_flag(engine_state, stack, "debug")?; // DO NOT ever try to merge the working_set in this command let mut working_set = StateWorkingSet::new(engine_state); let input_span = input.span().unwrap_or(call.head); match input { PipelineData::Value(Value::String { val, .. }, ..) => { let contents = Vec::from(val); if as_module { parse_module(&mut working_set, None, &contents, is_debug, input_span) } else { parse_script(&mut working_set, None, &contents, is_debug, input_span) } } PipelineData::ListStream(stream, ..) => { let config = stack.get_config(engine_state); let list_stream = stream.into_string("\n", &config); let contents = Vec::from(list_stream); if as_module { parse_module(&mut working_set, None, &contents, is_debug, call.head) } else { parse_script(&mut working_set, None, &contents, is_debug, call.head) } } PipelineData::ByteStream(stream, ..) => { let contents = stream.into_bytes()?; if as_module { parse_module(&mut working_set, None, &contents, is_debug, call.head) } else { parse_script(&mut working_set, None, &contents, is_debug, call.head) } } _ => { if let Some(path_str) = path_arg { let path_span = path_str.span; // look up the path as relative to FILE_PWD or inside NU_LIB_DIRS (same process as source-env) let path = match find_in_dirs_env( &path_str.item, engine_state, stack, get_dirs_var_from_call(stack, call), ) { Ok(Some(path)) => path, Ok(None) => { return Err(ShellError::Io(IoError::new( ErrorKind::FileNotFound, path_span, PathBuf::from(path_str.item), ))); } Err(err) => return Err(err), }; if as_module || path.is_dir() { parse_file_or_dir_module( path.to_string_lossy().as_bytes(), &mut working_set, is_debug, path_span, call.head, ) } else { // Unlike `parse_file_or_dir_module`, `parse_file_script` parses the content directly, // without adding the file to the stack. Therefore we need to handle this manually. working_set.files = FileStack::with_file(path.clone()); parse_file_script(&path, &mut working_set, is_debug, path_span, call.head) // The working set is not merged, so no need to pop the file from the stack. } } else { Err(ShellError::GenericError { error: "Failed to execute command".into(), msg: "Requires path argument if ran without pipeline input".into(), span: Some(call.head), help: Some("Please run 'nu-check --help' for more details".into()), inner: vec![], }) } } } } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Parse a input file as script(Default)", example: "nu-check script.nu", result: None, }, Example { description: "Parse a input file as module", example: "nu-check --as-module module.nu", result: None, }, Example { description: "Parse a input file by showing error message", example: "nu-check --debug script.nu", result: None, }, Example { description: "Parse a byte stream as script by showing error message", example: "open foo.nu | nu-check --debug script.nu", result: None, }, Example { description: "Parse an internal stream as module by showing error message", example: "open module.nu | lines | nu-check --debug --as-module module.nu", result: None, }, Example { description: "Parse a string as script", example: "$'two(char nl)lines' | nu-check ", result: None, }, ] } } fn parse_module( working_set: &mut StateWorkingSet, filename: Option<String>, contents: &[u8], is_debug: bool, call_head: Span, ) -> Result<PipelineData, ShellError> { let filename = filename.unwrap_or_else(|| "empty".to_string()); let file_id = working_set.add_file(filename.clone(), contents); let new_span = working_set.get_span_for_file(file_id); let starting_error_count = working_set.parse_errors.len(); parse_module_block(working_set, new_span, filename.as_bytes()); check_parse( starting_error_count, working_set, is_debug, Some( "If the content is intended to be a script, please try to remove `--as-module` flag " .to_string(), ), call_head, ) } fn parse_script( working_set: &mut StateWorkingSet, filename: Option<&str>, contents: &[u8], is_debug: bool, call_head: Span, ) -> Result<PipelineData, ShellError> { let starting_error_count = working_set.parse_errors.len(); parse(working_set, filename, contents, false); check_parse(starting_error_count, working_set, is_debug, None, call_head) } fn check_parse( starting_error_count: usize, working_set: &StateWorkingSet, is_debug: bool, help: Option<String>, call_head: Span, ) -> Result<PipelineData, ShellError> { if starting_error_count != working_set.parse_errors.len() { let msg = format!( r#"Found : {}"#, working_set .parse_errors .first() .expect("Missing parser error") ); if is_debug { Err(ShellError::GenericError { error: "Failed to parse content".into(), msg, span: Some(call_head), help, inner: vec![], }) } else { Ok(PipelineData::value(Value::bool(false, call_head), None)) } } else { Ok(PipelineData::value(Value::bool(true, call_head), None)) } } fn parse_file_script( path: &Path, working_set: &mut StateWorkingSet, is_debug: bool, path_span: Span, call_head: Span, ) -> Result<PipelineData, ShellError> { let filename = check_path(working_set, path_span, call_head)?; match std::fs::read(path) { Ok(contents) => parse_script(working_set, Some(&filename), &contents, is_debug, call_head), Err(err) => Err(ShellError::Io(IoError::new( err.not_found_as(NotFound::File), path_span, PathBuf::from(path), ))), } } fn parse_file_or_dir_module( path_bytes: &[u8], working_set: &mut StateWorkingSet, is_debug: bool, path_span: Span, call_head: Span, ) -> Result<PipelineData, ShellError> { let _ = check_path(working_set, path_span, call_head)?; let starting_error_count = working_set.parse_errors.len(); let _ = parse_module_file_or_dir(working_set, path_bytes, path_span, None); if starting_error_count != working_set.parse_errors.len() { if is_debug { let msg = format!( r#"Found : {}"#, working_set .parse_errors .first() .expect("Missing parser error") ); Err(ShellError::GenericError { error: "Failed to parse content".into(), msg, span: Some(path_span), help: Some("If the content is intended to be a script, please try to remove `--as-module` flag ".into()), inner: vec![], }) } else { Ok(PipelineData::value(Value::bool(false, call_head), None)) } } else { Ok(PipelineData::value(Value::bool(true, call_head), None)) } } fn check_path( working_set: &mut StateWorkingSet, path_span: Span, call_head: Span, ) -> Result<String, ShellError> { let bytes = working_set.get_span_contents(path_span); let (filename, err) = unescape_unquote_string(bytes, path_span); if let Some(e) = err { Err(ShellError::GenericError { error: "Could not escape filename".to_string(), msg: "could not escape filename".to_string(), span: Some(call_head), help: Some(format!("Returned error: {e}")), inner: vec![], }) } else { Ok(filename) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/system/exec.rs
crates/nu-command/src/system/exec.rs
use std::borrow::Cow; use nu_engine::{command_prelude::*, env_to_strings}; #[derive(Clone)] pub struct Exec; impl Command for Exec { fn name(&self) -> &str { "exec" } fn signature(&self) -> Signature { Signature::build("exec") .input_output_types(vec![(Type::Nothing, Type::Any)]) .rest( "command", SyntaxShape::OneOf(vec![SyntaxShape::GlobPattern, SyntaxShape::Any]), "External command to run, with arguments.", ) .allows_unknown_args() .category(Category::System) } fn description(&self) -> &str { "Execute a command, replacing or exiting the current process, depending on platform." } fn extra_description(&self) -> &str { r#"On Unix-based systems, the current process is replaced with the command. On Windows based systems, Nushell will wait for the command to finish and then exit with the command's exit code."# } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let cwd = engine_state.cwd(Some(stack))?; let rest = call.rest::<Value>(engine_state, stack, 0)?; let name_args = rest.split_first(); let Some((name, call_args)) = name_args else { return Err(ShellError::MissingParameter { param_name: "no command given".into(), span: call.head, }); }; let name_str: Cow<str> = match &name { Value::Glob { val, .. } => Cow::Borrowed(val), Value::String { val, .. } => Cow::Borrowed(val), _ => Cow::Owned(name.clone().coerce_into_string()?), }; // Find the absolute path to the executable. If the command is not // found, display a helpful error message. let executable = { let paths = nu_engine::env::path_str(engine_state, stack, call.head)?; let Some(executable) = crate::which(name_str.as_ref(), &paths, cwd.as_ref()) else { return Err(crate::command_not_found( &name_str, call.head, engine_state, stack, &cwd, )); }; executable }; // Create the command. let mut command = std::process::Command::new(executable); // Configure PWD. command.current_dir(cwd); // Configure environment variables. let envs = env_to_strings(engine_state, stack)?; command.env_clear(); command.envs(envs); // Decrement SHLVL as removing the current shell from the stack // (only works in interactive mode, same as initialization) if engine_state.is_interactive { let shlvl = engine_state .get_env_var("SHLVL") .and_then(|shlvl_env| shlvl_env.coerce_str().ok()?.parse::<i64>().ok()) .unwrap_or(1) .saturating_sub(1); command.env("SHLVL", shlvl.to_string()); } // Configure args. let args = crate::eval_external_arguments(engine_state, stack, call_args.to_vec())?; command.args(args.into_iter().map(|s| s.item)); // Execute the child process, replacing/terminating the current process // depending on platform. #[cfg(unix)] { use std::os::unix::process::CommandExt; let err = command.exec(); Err(ShellError::ExternalCommand { label: "Failed to exec into new process".into(), help: err.to_string(), span: call.head, }) } #[cfg(windows)] { let mut child = command.spawn().map_err(|err| ShellError::ExternalCommand { label: "Failed to exec into new process".into(), help: err.to_string(), span: call.head, })?; let status = child.wait().map_err(|err| ShellError::ExternalCommand { label: "Failed to wait for child process".into(), help: err.to_string(), span: call.head, })?; std::process::exit(status.code().expect("status.code() succeeds on Windows")) } } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Execute external 'ps aux' tool", example: "exec ps aux", result: None, }, Example { description: "Execute 'nautilus'", example: "exec nautilus", result: None, }, ] } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false