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-cmd-plugin/src/commands/plugin/rm.rs
crates/nu-cmd-plugin/src/commands/plugin/rm.rs
use nu_engine::command_prelude::*; use crate::util::{canonicalize_possible_filename_arg, modify_plugin_file}; #[derive(Clone)] pub struct PluginRm; impl Command for PluginRm { fn name(&self) -> &str { "plugin rm" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_type(Type::Nothing, Type::Nothing) // This matches the option to `nu` .named( "plugin-config", SyntaxShape::Filepath, "Use a plugin registry file other than the one set in `$nu.plugin-path`", None, ) .switch( "force", "Don't cause an error if the plugin name wasn't found in the file", Some('f'), ) .required( "name", SyntaxShape::String, "The name, or filename, of the plugin to remove.", ) .category(Category::Plugin) } fn description(&self) -> &str { "Remove a plugin from the plugin registry file." } fn extra_description(&self) -> &str { r#" This does not remove the plugin commands from the current scope or from `plugin list` in the current shell. It instead removes the plugin from the plugin registry file (by default, `$nu.plugin-path`). The changes will be apparent the next time `nu` is launched with that plugin registry file. This can be useful for removing an invalid plugin signature, if it can't be fixed with `plugin add`. "# .trim() } fn search_terms(&self) -> Vec<&str> { vec!["remove", "delete", "signature"] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "plugin rm inc", description: "Remove the installed signatures for the `inc` plugin.", result: None, }, Example { example: "plugin rm ~/.cargo/bin/nu_plugin_inc", description: "Remove the installed signatures for the plugin with the filename `~/.cargo/bin/nu_plugin_inc`.", result: None, }, Example { example: "plugin rm --plugin-config polars.msgpackz polars", description: "Remove the installed signatures for the `polars` plugin from the \"polars.msgpackz\" plugin registry file.", result: None, }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let name: Spanned<String> = call.req(engine_state, stack, 0)?; let custom_path = call.get_flag(engine_state, stack, "plugin-config")?; let force = call.has_flag(engine_state, stack, "force")?; let filename = canonicalize_possible_filename_arg(engine_state, stack, &name.item); modify_plugin_file(engine_state, stack, call.head, &custom_path, |contents| { if let Some(index) = contents .plugins .iter() .position(|p| p.name == name.item || p.filename == filename) { contents.plugins.remove(index); Ok(()) } else if force { Ok(()) } else { Err(ShellError::GenericError { error: format!("Failed to remove the `{}` plugin", name.item), msg: "couldn't find a plugin with this name in the registry file".into(), span: Some(name.span), help: None, inner: vec![], }) } })?; Ok(Value::nothing(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-plugin/src/commands/plugin/list.rs
crates/nu-cmd-plugin/src/commands/plugin/list.rs
use itertools::{EitherOrBoth, Itertools}; use nu_engine::command_prelude::*; use nu_protocol::{IntoValue, PluginRegistryItemData}; use crate::util::read_plugin_file; #[derive(Clone)] pub struct PluginList; impl Command for PluginList { fn name(&self) -> &str { "plugin list" } fn signature(&self) -> Signature { Signature::build("plugin list") .input_output_type( Type::Nothing, Type::Table( [ ("name".into(), Type::String), ("version".into(), Type::String), ("status".into(), Type::String), ("pid".into(), Type::Int), ("filename".into(), Type::String), ("shell".into(), Type::String), ("commands".into(), Type::List(Type::String.into())), ] .into(), ), ) .named( "plugin-config", SyntaxShape::Filepath, "Use a plugin registry file other than the one set in `$nu.plugin-path`", None, ) .switch( "engine", "Show info for plugins that are loaded into the engine only.", Some('e'), ) .switch( "registry", "Show info for plugins from the registry file only.", Some('r'), ) .category(Category::Plugin) } fn description(&self) -> &str { "List loaded and installed plugins." } fn extra_description(&self) -> &str { r#" The `status` column will contain one of the following values: - `added`: The plugin is present in the plugin registry file, but not in the engine. - `loaded`: The plugin is present both in the plugin registry file and in the engine, but is not running. - `running`: The plugin is currently running, and the `pid` column should contain its process ID. - `modified`: The plugin state present in the plugin registry file is different from the state in the engine. - `removed`: The plugin is still loaded in the engine, but is not present in the plugin registry file. - `invalid`: The data in the plugin registry file couldn't be deserialized, and the plugin most likely needs to be added again. `running` takes priority over any other status. Unless `--registry` is used or the plugin has not been loaded yet, the values of `version`, `filename`, `shell`, and `commands` reflect the values in the engine and not the ones in the plugin registry file. See also: `plugin use` "# .trim() } fn search_terms(&self) -> Vec<&str> { vec!["scope"] } fn examples(&self) -> Vec<nu_protocol::Example<'_>> { vec![ Example { example: "plugin list", description: "List installed plugins.", result: Some(Value::test_list(vec![Value::test_record(record! { "name" => Value::test_string("inc"), "version" => Value::test_string(env!("CARGO_PKG_VERSION")), "status" => Value::test_string("running"), "pid" => Value::test_int(106480), "filename" => if cfg!(windows) { Value::test_string(r"C:\nu\plugins\nu_plugin_inc.exe") } else { Value::test_string("/opt/nu/plugins/nu_plugin_inc") }, "shell" => Value::test_nothing(), "commands" => Value::test_list(vec![Value::test_string("inc")]), })])), }, Example { example: "ps | where pid in (plugin list).pid", description: "Get process information for running plugins.", result: None, }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let custom_path = call.get_flag(engine_state, stack, "plugin-config")?; let engine_mode = call.has_flag(engine_state, stack, "engine")?; let registry_mode = call.has_flag(engine_state, stack, "registry")?; let plugins_info = match (engine_mode, registry_mode) { // --engine and --registry together is equivalent to the default. (false, false) | (true, true) => { if engine_state.plugin_path.is_some() || custom_path.is_some() { let plugins_in_engine = get_plugins_in_engine(engine_state); let plugins_in_registry = get_plugins_in_registry(engine_state, stack, call.head, &custom_path)?; merge_plugin_info(plugins_in_engine, plugins_in_registry) } else { // Don't produce error when running nu --no-config-file get_plugins_in_engine(engine_state) } } (true, false) => get_plugins_in_engine(engine_state), (false, true) => get_plugins_in_registry(engine_state, stack, call.head, &custom_path)?, }; Ok(plugins_info.into_value(call.head).into_pipeline_data()) } } #[derive(Debug, Clone, IntoValue, PartialOrd, Ord, PartialEq, Eq)] struct PluginInfo { name: String, version: Option<String>, status: PluginStatus, pid: Option<u32>, filename: String, shell: Option<String>, commands: Vec<CommandInfo>, } #[derive(Debug, Clone, IntoValue, PartialOrd, Ord, PartialEq, Eq)] struct CommandInfo { name: String, description: String, } #[derive(Debug, Clone, Copy, IntoValue, PartialOrd, Ord, PartialEq, Eq)] #[nu_value(rename_all = "snake_case")] enum PluginStatus { Added, Loaded, Running, Modified, Removed, Invalid, } fn get_plugins_in_engine(engine_state: &EngineState) -> Vec<PluginInfo> { // Group plugin decls by plugin identity let decls = engine_state.plugin_decls().into_group_map_by(|decl| { decl.plugin_identity() .expect("plugin decl should have identity") }); // Build plugins list engine_state .plugins() .iter() .map(|plugin| { // Find commands that belong to the plugin let commands: Vec<(String, String)> = decls .get(plugin.identity()) .into_iter() .flat_map(|decls| { decls .iter() .map(|decl| (decl.name().to_owned(), decl.description().to_owned())) }) .sorted() .collect(); PluginInfo { name: plugin.identity().name().into(), version: plugin.metadata().and_then(|m| m.version), status: if plugin.pid().is_some() { PluginStatus::Running } else { PluginStatus::Loaded }, pid: plugin.pid(), filename: plugin.identity().filename().to_string_lossy().into_owned(), shell: plugin .identity() .shell() .map(|path| path.to_string_lossy().into_owned()), commands: commands .iter() .map(|(name, desc)| CommandInfo { name: name.clone(), description: desc.clone(), }) .collect(), } }) .sorted() .collect() } fn get_plugins_in_registry( engine_state: &EngineState, stack: &mut Stack, span: Span, custom_path: &Option<Spanned<String>>, ) -> Result<Vec<PluginInfo>, ShellError> { let plugin_file_contents = read_plugin_file(engine_state, stack, span, custom_path)?; let plugins_info = plugin_file_contents .plugins .into_iter() .map(|plugin| { let mut info = PluginInfo { name: plugin.name, version: None, status: PluginStatus::Added, pid: None, filename: plugin.filename.to_string_lossy().into_owned(), shell: plugin.shell.map(|path| path.to_string_lossy().into_owned()), commands: vec![], }; if let PluginRegistryItemData::Valid { metadata, commands } = plugin.data { info.version = metadata.version; info.commands = commands .into_iter() .map(|command| CommandInfo { name: command.sig.name.clone(), description: command.sig.description.clone(), }) .sorted() .collect(); } else { info.status = PluginStatus::Invalid; } info }) .sorted() .collect(); Ok(plugins_info) } /// If no options are provided, the command loads from both the plugin list in the engine and what's /// in the registry file. We need to reconcile the two to set the proper states and make sure that /// new plugins that were added to the plugin registry file show up. fn merge_plugin_info( from_engine: Vec<PluginInfo>, from_registry: Vec<PluginInfo>, ) -> Vec<PluginInfo> { from_engine .into_iter() .merge_join_by(from_registry, |info_a, info_b| { info_a.name.cmp(&info_b.name) }) .map(|either_or_both| match either_or_both { // Exists in the engine, but not in the registry file EitherOrBoth::Left(info) => PluginInfo { status: match info.status { PluginStatus::Running => info.status, // The plugin is not in the registry file, so it should be marked as `removed` _ => PluginStatus::Removed, }, ..info }, // Exists in the registry file, but not in the engine EitherOrBoth::Right(info) => info, // Exists in both EitherOrBoth::Both(info_engine, info_registry) => PluginInfo { status: match (info_engine.status, info_registry.status) { // Above all, `running` should be displayed if the plugin is running (PluginStatus::Running, _) => PluginStatus::Running, // `invalid` takes precedence over other states because the user probably wants // to fix it (_, PluginStatus::Invalid) => PluginStatus::Invalid, // Display `modified` if the state in the registry is different somehow _ if info_engine.is_modified(&info_registry) => PluginStatus::Modified, // Otherwise, `loaded` (it's not running) _ => PluginStatus::Loaded, }, ..info_engine }, }) .sorted() .collect() } impl PluginInfo { /// True if the plugin info shows some kind of change (other than status/pid) relative to the /// other fn is_modified(&self, other: &PluginInfo) -> bool { self.name != other.name || self.filename != other.filename || self.shell != other.shell || self.commands != other.commands } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-plugin/src/commands/plugin/mod.rs
crates/nu-cmd-plugin/src/commands/plugin/mod.rs
use nu_engine::{command_prelude::*, get_full_help}; mod add; mod list; mod rm; mod stop; mod use_; pub use add::PluginAdd; pub use list::PluginList; pub use rm::PluginRm; pub use stop::PluginStop; pub use use_::PluginUse; #[derive(Clone)] pub struct PluginCommand; impl Command for PluginCommand { fn name(&self) -> &str { "plugin" } fn signature(&self) -> Signature { Signature::build("plugin") .input_output_types(vec![(Type::Nothing, Type::Nothing)]) .category(Category::Plugin) } fn description(&self) -> &str { "Commands for managing plugins." } 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()) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "plugin add nu_plugin_inc", description: "Run the `nu_plugin_inc` plugin from the current directory and install its signatures.", result: None, }, Example { example: "plugin use inc", description: " Load (or reload) the `inc` plugin from the plugin registry file and put its commands in scope. The plugin must already be in the registry file at parse time. " .trim(), result: None, }, Example { example: "plugin list", description: "List installed plugins", result: None, }, Example { example: "plugin stop inc", description: "Stop the plugin named `inc`.", result: None, }, Example { example: "plugin rm inc", description: "Remove the installed signatures for the `inc` plugin.", result: None, }, ] } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-plugin/src/commands/plugin/add.rs
crates/nu-cmd-plugin/src/commands/plugin/add.rs
use crate::util::{get_plugin_dirs, modify_plugin_file}; use nu_engine::command_prelude::*; use nu_plugin_engine::{GetPlugin, PersistentPlugin}; use nu_protocol::{ PluginGcConfig, PluginIdentity, PluginRegistryItem, RegisteredPlugin, shell_error::io::IoError, }; use std::{path::PathBuf, sync::Arc}; #[derive(Clone)] pub struct PluginAdd; impl Command for PluginAdd { fn name(&self) -> &str { "plugin add" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_type(Type::Nothing, Type::Nothing) // This matches the option to `nu` .named( "plugin-config", SyntaxShape::Filepath, "Use a plugin registry file other than the one set in `$nu.plugin-path`", None, ) .named( "shell", SyntaxShape::Filepath, "Use an additional shell program (cmd, sh, python, etc.) to run the plugin", Some('s'), ) .required( "filename", SyntaxShape::String, "Path to the executable for the plugin.", ) .category(Category::Plugin) } fn description(&self) -> &str { "Add a plugin to the plugin registry file." } fn extra_description(&self) -> &str { r#" This does not load the plugin commands into the scope - see `plugin use` for that. Instead, it runs the plugin to get its command signatures, and then edits the plugin registry file (by default, `$nu.plugin-path`). The changes will be apparent the next time `nu` is next launched with that plugin registry file. "# .trim() } fn search_terms(&self) -> Vec<&str> { vec!["load", "register", "signature"] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "plugin add nu_plugin_inc", description: "Run the `nu_plugin_inc` plugin from the current directory or $env.NU_PLUGIN_DIRS and install its signatures.", result: None, }, Example { example: "plugin add --plugin-config polars.msgpackz nu_plugin_polars", description: "Run the `nu_plugin_polars` plugin from the current directory or $env.NU_PLUGIN_DIRS, and install its signatures to the \"polars.msgpackz\" plugin registry file.", result: None, }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let filename: Spanned<String> = call.req(engine_state, stack, 0)?; let shell: Option<Spanned<String>> = call.get_flag(engine_state, stack, "shell")?; let cwd = engine_state.cwd(Some(stack))?; // Check the current directory, or fall back to NU_PLUGIN_DIRS let filename_expanded = nu_path::locate_in_dirs(&filename.item, &cwd, || { get_plugin_dirs(engine_state, stack) }) .map_err(|err| { IoError::new( err.not_found_as(NotFound::File), filename.span, PathBuf::from(filename.item), ) })?; let shell_expanded = shell .as_ref() .map(|s| { nu_path::canonicalize_with(&s.item, &cwd) .map_err(|err| IoError::new(err, s.span, None)) }) .transpose()?; // Parse the plugin filename so it can be used to spawn the plugin let identity = PluginIdentity::new(filename_expanded, shell_expanded).map_err(|_| { ShellError::GenericError { error: "Plugin filename is invalid".into(), msg: "plugin executable files must start with `nu_plugin_`".into(), span: Some(filename.span), help: None, inner: vec![], } })?; let custom_path = call.get_flag(engine_state, stack, "plugin-config")?; // Start the plugin manually, to get the freshest signatures and to not affect engine // state. Provide a GC config that will stop it ASAP let plugin = Arc::new(PersistentPlugin::new( identity, PluginGcConfig { enabled: true, stop_after: 0, }, )); let interface = plugin.clone().get_plugin(Some((engine_state, stack)))?; let metadata = interface.get_metadata()?; let commands = interface.get_signature()?; modify_plugin_file(engine_state, stack, call.head, &custom_path, |contents| { // Update the file with the received metadata and signatures let item = PluginRegistryItem::new(plugin.identity(), metadata, commands); contents.upsert_plugin(item); Ok(()) })?; Ok(Value::nothing(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-plugin/src/commands/plugin/stop.rs
crates/nu-cmd-plugin/src/commands/plugin/stop.rs
use nu_engine::command_prelude::*; use crate::util::canonicalize_possible_filename_arg; #[derive(Clone)] pub struct PluginStop; impl Command for PluginStop { fn name(&self) -> &str { "plugin stop" } fn signature(&self) -> Signature { Signature::build("plugin stop") .input_output_type(Type::Nothing, Type::Nothing) .required( "name", SyntaxShape::String, "The name, or filename, of the plugin to stop.", ) .category(Category::Plugin) } fn description(&self) -> &str { "Stop an installed plugin if it was running." } fn examples(&self) -> Vec<nu_protocol::Example<'_>> { vec![ Example { example: "plugin stop inc", description: "Stop the plugin named `inc`.", result: None, }, Example { example: "plugin stop ~/.cargo/bin/nu_plugin_inc", description: "Stop the plugin with the filename `~/.cargo/bin/nu_plugin_inc`.", result: None, }, Example { example: "plugin list | each { |p| plugin stop $p.name }", description: "Stop all plugins.", result: None, }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let name: Spanned<String> = call.req(engine_state, stack, 0)?; let filename = canonicalize_possible_filename_arg(engine_state, stack, &name.item); let mut found = false; for plugin in engine_state.plugins() { let id = &plugin.identity(); if id.name() == name.item || id.filename() == filename { plugin.stop()?; found = true; } } if found { Ok(PipelineData::empty()) } else { Err(ShellError::GenericError { error: format!("Failed to stop the `{}` plugin", name.item), msg: "couldn't find a plugin with this name".into(), span: Some(name.span), help: Some("you may need to `plugin add` the plugin first".into()), inner: vec![], }) } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-system/src/foreground.rs
crates/nu-system/src/foreground.rs
use std::sync::{Arc, atomic::AtomicU32}; use std::io; use std::process::{Child, Command}; use crate::ExitStatus; #[cfg(unix)] use std::{io::IsTerminal, sync::atomic::Ordering}; #[cfg(unix)] pub use child_pgroup::stdin_fd; #[cfg(unix)] use nix::{sys::signal, sys::wait, unistd::Pid}; /// A simple wrapper for [`std::process::Child`] /// /// It can only be created by [`ForegroundChild::spawn`]. /// /// # Spawn behavior /// ## Unix /// /// For interactive shells, the spawned child process will get its own process group id, /// and it will be put in the foreground (by making stdin belong to the child's process group). /// On drop, the calling process's group will become the foreground process group once again. /// /// For non-interactive mode, processes are spawned normally without any foreground process handling. /// /// ## Other systems /// /// It does nothing special on non-unix systems, so `spawn` is the same as [`std::process::Command::spawn`]. pub struct ForegroundChild { inner: Child, #[cfg(unix)] pipeline_state: Option<Arc<(AtomicU32, AtomicU32)>>, // this is unix-only since we don't have to deal with process groups in windows #[cfg(unix)] interactive: bool, } impl ForegroundChild { #[cfg(not(unix))] pub fn spawn(mut command: Command) -> io::Result<Self> { command.spawn().map(|child| Self { inner: child }) } #[cfg(unix)] pub fn spawn( mut command: Command, interactive: bool, background: bool, pipeline_state: &Arc<(AtomicU32, AtomicU32)>, ) -> io::Result<Self> { let interactive = interactive && io::stdin().is_terminal(); let uses_dedicated_process_group = interactive || background; if uses_dedicated_process_group { let (pgrp, pcnt) = pipeline_state.as_ref(); let existing_pgrp = pgrp.load(Ordering::SeqCst); child_pgroup::prepare_command(&mut command, existing_pgrp, background); command .spawn() .map(|child| { child_pgroup::set(&child, existing_pgrp, background); let _ = pcnt.fetch_add(1, Ordering::SeqCst); if existing_pgrp == 0 { pgrp.store(child.id(), Ordering::SeqCst); } Self { inner: child, pipeline_state: Some(pipeline_state.clone()), interactive, } }) .inspect_err(|_e| { if interactive { child_pgroup::reset(); } }) } else { command.spawn().map(|child| Self { inner: child, pipeline_state: None, interactive, }) } } pub fn wait(&mut self) -> io::Result<ForegroundWaitStatus> { #[cfg(unix)] { let child_pid = Pid::from_raw(self.inner.id() as i32); unix_wait(child_pid).inspect(|result| { if let (true, ForegroundWaitStatus::Frozen(_)) = (self.interactive, result) { child_pgroup::reset(); } }) } #[cfg(not(unix))] self.as_mut().wait().map(Into::into) } pub fn pid(&self) -> u32 { self.inner.id() } } #[cfg(unix)] fn unix_wait(child_pid: Pid) -> std::io::Result<ForegroundWaitStatus> { use ForegroundWaitStatus::*; // the child may be stopped multiple times, we loop until it exits loop { let status = wait::waitpid(child_pid, Some(wait::WaitPidFlag::WUNTRACED)); match status { Err(e) => { return Err(e.into()); } Ok(wait::WaitStatus::Exited(_, status)) => { return Ok(Finished(ExitStatus::Exited(status))); } Ok(wait::WaitStatus::Signaled(_, signal, core_dumped)) => { return Ok(Finished(ExitStatus::Signaled { signal: signal as i32, core_dumped, })); } Ok(wait::WaitStatus::Stopped(_, _)) => { return Ok(Frozen(UnfreezeHandle { child_pid })); } Ok(_) => { // keep waiting } }; } } pub enum ForegroundWaitStatus { Finished(ExitStatus), Frozen(UnfreezeHandle), } impl From<std::process::ExitStatus> for ForegroundWaitStatus { fn from(status: std::process::ExitStatus) -> Self { ForegroundWaitStatus::Finished(status.into()) } } #[derive(Debug)] pub struct UnfreezeHandle { #[cfg(unix)] child_pid: Pid, } impl UnfreezeHandle { #[cfg(unix)] pub fn unfreeze( self, pipeline_state: Option<Arc<(AtomicU32, AtomicU32)>>, ) -> io::Result<ForegroundWaitStatus> { // bring child's process group back into foreground and continue it // we only keep the guard for its drop impl let _guard = pipeline_state.map(|pipeline_state| { ForegroundGuard::new(self.child_pid.as_raw() as u32, &pipeline_state) }); if let Err(err) = signal::killpg(self.child_pid, signal::SIGCONT) { return Err(err.into()); } let child_pid = self.child_pid; unix_wait(child_pid) } pub fn pid(&self) -> u32 { #[cfg(unix)] { self.child_pid.as_raw() as u32 } #[cfg(not(unix))] 0 } } impl AsMut<Child> for ForegroundChild { fn as_mut(&mut self) -> &mut Child { &mut self.inner } } #[cfg(unix)] impl Drop for ForegroundChild { fn drop(&mut self) { if let Some((pgrp, pcnt)) = self.pipeline_state.as_deref() && pcnt.fetch_sub(1, Ordering::SeqCst) == 1 { pgrp.store(0, Ordering::SeqCst); if self.interactive { child_pgroup::reset() } } } } /// Keeps a specific already existing process in the foreground as long as the [`ForegroundGuard`]. /// If the process needs to be spawned in the foreground, use [`ForegroundChild`] instead. This is /// used to temporarily bring frozen and plugin processes into the foreground. /// /// # OS-specific behavior /// ## Unix /// /// If there is already a foreground external process running, spawned with [`ForegroundChild`], /// this expects the process ID to remain in the process group created by the [`ForegroundChild`] /// for the lifetime of the guard, and keeps the terminal controlling process group set to that. /// If there is no foreground external process running, this sets the foreground process group to /// the provided process ID. The process group that is expected can be retrieved with /// [`.pgrp()`](Self::pgrp) if different from the provided process ID. /// /// ## Other systems /// /// It does nothing special on non-unix systems. #[derive(Debug)] pub struct ForegroundGuard { #[cfg(unix)] pgrp: Option<u32>, #[cfg(unix)] pipeline_state: Arc<(AtomicU32, AtomicU32)>, } impl ForegroundGuard { /// Move the given process to the foreground. #[cfg(unix)] pub fn new( pid: u32, pipeline_state: &Arc<(AtomicU32, AtomicU32)>, ) -> std::io::Result<ForegroundGuard> { use nix::unistd::{self, Pid}; let pid_nix = Pid::from_raw(pid as i32); let (pgrp, pcnt) = pipeline_state.as_ref(); // Might have to retry due to race conditions on the atomics loop { // Try to give control to the child, if there isn't currently a foreground group if pgrp .compare_exchange(0, pid, Ordering::SeqCst, Ordering::SeqCst) .is_ok() { let _ = pcnt.fetch_add(1, Ordering::SeqCst); // We don't need the child to change process group. Make the guard now so that if there // is an error, it will be cleaned up let guard = ForegroundGuard { pgrp: None, pipeline_state: pipeline_state.clone(), }; log::trace!("Giving control of the terminal to the process group, pid={pid}"); // Set the terminal controlling process group to the child process unistd::tcsetpgrp(unsafe { stdin_fd() }, pid_nix)?; return Ok(guard); } else if pcnt .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |count| { // Avoid a race condition: only increment if count is > 0 if count > 0 { Some(count + 1) } else { None } }) .is_ok() { // We successfully added another count to the foreground process group, which means // we only need to tell the child process to join this one let pgrp = pgrp.load(Ordering::SeqCst); log::trace!( "Will ask the process pid={pid} to join pgrp={pgrp} for control of the \ terminal" ); return Ok(ForegroundGuard { pgrp: Some(pgrp), pipeline_state: pipeline_state.clone(), }); } else { // The state has changed, we'll have to retry continue; } } } /// Move the given process to the foreground. #[cfg(not(unix))] pub fn new( pid: u32, pipeline_state: &Arc<(AtomicU32, AtomicU32)>, ) -> std::io::Result<ForegroundGuard> { let _ = (pid, pipeline_state); Ok(ForegroundGuard {}) } /// If the child process is expected to join a different process group to be in the foreground, /// this returns `Some(pgrp)`. This only ever returns `Some` on Unix. pub fn pgrp(&self) -> Option<u32> { #[cfg(unix)] { self.pgrp } #[cfg(not(unix))] { None } } /// This should only be called once by `Drop` fn reset_internal(&mut self) { #[cfg(unix)] { log::trace!("Leaving the foreground group"); let (pgrp, pcnt) = self.pipeline_state.as_ref(); if pcnt.fetch_sub(1, Ordering::SeqCst) == 1 { // Clean up if we are the last one around pgrp.store(0, Ordering::SeqCst); child_pgroup::reset() } } } } impl Drop for ForegroundGuard { fn drop(&mut self) { self.reset_internal(); } } // It's a simpler version of fish shell's external process handling. #[cfg(unix)] mod child_pgroup { use nix::{ sys::signal::{SaFlags, SigAction, SigHandler, SigSet, Signal, sigaction}, unistd::{self, Pid}, }; use std::{ os::{ fd::{AsFd, BorrowedFd}, unix::prelude::CommandExt, }, process::{Child, Command}, }; /// Alternative to having to call `std::io::stdin()` just to get the file descriptor of stdin /// /// # Safety /// I/O safety of reading from `STDIN_FILENO` unclear. /// /// Currently only intended to access `tcsetpgrp` and `tcgetpgrp` with the I/O safe `nix` /// interface. pub unsafe fn stdin_fd() -> impl AsFd { unsafe { BorrowedFd::borrow_raw(nix::libc::STDIN_FILENO) } } pub fn prepare_command(external_command: &mut Command, existing_pgrp: u32, background: bool) { unsafe { // Safety: // POSIX only allows async-signal-safe functions to be called. // `sigaction` and `getpid` are async-signal-safe according to: // https://manpages.ubuntu.com/manpages/bionic/man7/signal-safety.7.html // Also, `set_foreground_pid` is async-signal-safe. external_command.pre_exec(move || { // When this callback is run, std::process has already: // - reset SIGPIPE to SIG_DFL // According to glibc's job control manual: // https://www.gnu.org/software/libc/manual/html_node/Launching-Jobs.html // This has to be done *both* in the parent and here in the child due to race conditions. set_foreground_pid(Pid::this(), existing_pgrp, background); // `terminal.rs` makes the shell process ignore some signals, // so we set them to their default behavior for our child let default = SigAction::new(SigHandler::SigDfl, SaFlags::empty(), SigSet::empty()); let _ = sigaction(Signal::SIGQUIT, &default); let _ = sigaction(Signal::SIGTSTP, &default); let _ = sigaction(Signal::SIGTERM, &default); Ok(()) }); } } pub fn set(process: &Child, existing_pgrp: u32, background: bool) { set_foreground_pid( Pid::from_raw(process.id() as i32), existing_pgrp, background, ); } fn set_foreground_pid(pid: Pid, existing_pgrp: u32, background: bool) { // Safety: needs to be async-signal-safe. // `setpgid` and `tcsetpgrp` are async-signal-safe. // `existing_pgrp` is 0 when we don't have an existing foreground process in the pipeline. // A pgrp of 0 means the calling process's pid for `setpgid`. But not for `tcsetpgrp`. let pgrp = if existing_pgrp == 0 { pid } else { Pid::from_raw(existing_pgrp as i32) }; let _ = unistd::setpgid(pid, pgrp); if !background { let _ = unistd::tcsetpgrp(unsafe { stdin_fd() }, pgrp); } } /// Reset the foreground process group to the shell pub fn reset() { if let Err(e) = unistd::tcsetpgrp(unsafe { stdin_fd() }, unistd::getpgrp()) { eprintln!("ERROR: reset foreground id failed, tcsetpgrp result: {e:?}"); } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-system/src/lib.rs
crates/nu-system/src/lib.rs
#![doc = include_str!("../README.md")] mod exit_status; mod foreground; mod util; #[cfg(target_os = "freebsd")] mod freebsd; #[cfg(any(target_os = "android", target_os = "linux"))] mod linux; #[cfg(target_os = "macos")] mod macos; #[cfg(any(target_os = "netbsd", target_os = "openbsd"))] mod netbsd; pub mod os_info; #[cfg(target_os = "windows")] mod windows; pub use self::exit_status::ExitStatus; #[cfg(unix)] pub use self::foreground::stdin_fd; pub use self::foreground::{ ForegroundChild, ForegroundGuard, ForegroundWaitStatus, UnfreezeHandle, }; pub use self::util::*; #[cfg(target_os = "freebsd")] pub use self::freebsd::*; #[cfg(any(target_os = "android", target_os = "linux"))] pub use self::linux::*; #[cfg(target_os = "macos")] pub use self::macos::*; #[cfg(any(target_os = "netbsd", target_os = "openbsd"))] pub use self::netbsd::*; #[cfg(target_os = "windows")] pub use self::windows::*;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-system/src/macos.rs
crates/nu-system/src/macos.rs
use libc::{c_int, c_void, size_t}; use libproc::libproc::bsd_info::BSDInfo; use libproc::libproc::file_info::{ListFDs, ProcFDType, pidfdinfo}; use libproc::libproc::net_info::{InSockInfo, SocketFDInfo, SocketInfoKind, TcpSockInfo}; use libproc::libproc::pid_rusage::{RUsageInfoV2, pidrusage}; use libproc::libproc::proc_pid::{ListThreads, listpidinfo, pidinfo}; use libproc::libproc::task_info::{TaskAllInfo, TaskInfo}; use libproc::libproc::thread_info::ThreadInfo; use libproc::processes::{ProcFilter, pids_by_type}; use mach2::mach_time; use std::cmp; use std::path::{Path, PathBuf}; use std::thread; use std::time::{Duration, Instant}; pub struct ProcessInfo { pub pid: i32, pub ppid: i32, pub curr_task: TaskAllInfo, pub prev_task: TaskAllInfo, pub curr_path: Option<PathInfo>, pub curr_threads: Vec<ThreadInfo>, pub curr_udps: Vec<InSockInfo>, pub curr_tcps: Vec<TcpSockInfo>, pub curr_res: Option<RUsageInfoV2>, pub prev_res: Option<RUsageInfoV2>, pub interval: Duration, pub start_time: i64, pub user_id: i64, pub priority: i64, pub task_thread_num: i64, } pub fn collect_proc(interval: Duration, _with_thread: bool) -> Vec<ProcessInfo> { let mut base_procs = Vec::new(); let mut ret = Vec::new(); let arg_max = get_arg_max(); if let Ok(procs) = pids_by_type(ProcFilter::All) { for p in procs { if let Ok(task) = pidinfo::<TaskAllInfo>(p as i32, 0) { let res = pidrusage::<RUsageInfoV2>(p as i32).ok(); let time = Instant::now(); base_procs.push((p as i32, task, res, time)); } } } thread::sleep(interval); for (pid, prev_task, prev_res, prev_time) in base_procs { let curr_task = if let Ok(task) = pidinfo::<TaskAllInfo>(pid, 0) { task } else { clone_task_all_info(&prev_task) }; let curr_path = get_path_info(pid, arg_max); let threadids = listpidinfo::<ListThreads>(pid, curr_task.ptinfo.pti_threadnum as usize); let mut curr_threads = Vec::new(); if let Ok(threadids) = threadids { for t in threadids { if let Ok(thread) = pidinfo::<ThreadInfo>(pid, t) { curr_threads.push(thread); } } } let mut curr_tcps = Vec::new(); let mut curr_udps = Vec::new(); let fds = listpidinfo::<ListFDs>(pid, curr_task.pbsd.pbi_nfiles as usize); if let Ok(fds) = fds { for fd in fds { if let ProcFDType::Socket = fd.proc_fdtype.into() && let Ok(socket) = pidfdinfo::<SocketFDInfo>(pid, fd.proc_fd) { match socket.psi.soi_kind.into() { SocketInfoKind::In => { if socket.psi.soi_protocol == libc::IPPROTO_UDP { let info = unsafe { socket.psi.soi_proto.pri_in }; curr_udps.push(info); } } SocketInfoKind::Tcp => { let info = unsafe { socket.psi.soi_proto.pri_tcp }; curr_tcps.push(info); } _ => (), } } } } let curr_res = pidrusage::<RUsageInfoV2>(pid).ok(); let curr_time = Instant::now(); let interval = curr_time.saturating_duration_since(prev_time); let ppid = curr_task.pbsd.pbi_ppid as i32; let start_time = curr_task.pbsd.pbi_start_tvsec as i64; let user_id = curr_task.pbsd.pbi_uid as i64; let priority = curr_task.ptinfo.pti_priority as i64; let task_thread_num = curr_task.ptinfo.pti_threadnum as i64; let proc = ProcessInfo { pid, ppid, curr_task, prev_task, curr_path, curr_threads, curr_udps, curr_tcps, curr_res, prev_res, interval, start_time, user_id, priority, task_thread_num, }; ret.push(proc); } ret } fn get_arg_max() -> size_t { let mut mib: [c_int; 2] = [libc::CTL_KERN, libc::KERN_ARGMAX]; let mut arg_max = 0i32; let mut size = ::std::mem::size_of::<c_int>(); unsafe { while libc::sysctl( mib.as_mut_ptr(), 2, (&mut arg_max) as *mut i32 as *mut c_void, &mut size, ::std::ptr::null_mut(), 0, ) == -1 {} } arg_max as size_t } pub struct PathInfo { pub name: String, pub exe: PathBuf, pub root: PathBuf, pub cmd: Vec<String>, pub env: Vec<String>, pub cwd: PathBuf, } unsafe fn get_unchecked_str(cp: *mut u8, start: *mut u8) -> String { unsafe { let len = (cp as usize).saturating_sub(start as usize); let part = std::slice::from_raw_parts(start, len); String::from_utf8_unchecked(part.to_vec()) } } fn get_path_info(pid: i32, mut size: size_t) -> Option<PathInfo> { let mut proc_args = Vec::with_capacity(size); let ptr: *mut u8 = proc_args.as_mut_slice().as_mut_ptr(); let mut mib: [c_int; 3] = [libc::CTL_KERN, libc::KERN_PROCARGS2, pid as c_int]; unsafe { let ret = libc::sysctl( mib.as_mut_ptr(), 3, ptr as *mut c_void, &mut size, ::std::ptr::null_mut(), 0, ); if ret != -1 { let mut n_args: c_int = 0; libc::memcpy( (&mut n_args) as *mut c_int as *mut c_void, ptr as *const c_void, ::std::mem::size_of::<c_int>(), ); let mut cp = ptr.add(::std::mem::size_of::<c_int>()); let mut start = cp; if cp < ptr.add(size) { while cp < ptr.add(size) && *cp != 0 { cp = cp.offset(1); } let exe = Path::new(get_unchecked_str(cp, start).as_str()).to_path_buf(); let name = exe .file_name() .unwrap_or_default() .to_str() .unwrap_or("") .to_owned(); let mut need_root = true; let mut root = Default::default(); if exe.is_absolute() && let Some(parent) = exe.parent() { root = parent.to_path_buf(); need_root = false; } while cp < ptr.add(size) && *cp == 0 { cp = cp.offset(1); } start = cp; let mut c = 0; let mut cmd = Vec::new(); while c < n_args && cp < ptr.add(size) { if *cp == 0 { c += 1; cmd.push(get_unchecked_str(cp, start)); start = cp.offset(1); } cp = cp.offset(1); } start = cp; let mut env = Vec::new(); let mut cwd = PathBuf::default(); while cp < ptr.add(size) { if *cp == 0 { if cp == start { break; } let env_str = get_unchecked_str(cp, start); if let Some(pwd) = env_str.strip_prefix("PWD=") { cwd = PathBuf::from(pwd) } env.push(env_str); start = cp.offset(1); } cp = cp.offset(1); } if need_root { for env in env.iter() { if env.starts_with("PATH=") { root = Path::new(&env[6..]).to_path_buf(); break; } } } Some(PathInfo { exe, name, root, cmd, env, cwd, }) } else { None } } else { None } } } fn clone_task_all_info(src: &TaskAllInfo) -> TaskAllInfo { let pbsd = BSDInfo { pbi_flags: src.pbsd.pbi_flags, pbi_status: src.pbsd.pbi_status, pbi_xstatus: src.pbsd.pbi_xstatus, pbi_pid: src.pbsd.pbi_pid, pbi_ppid: src.pbsd.pbi_ppid, pbi_uid: src.pbsd.pbi_uid, pbi_gid: src.pbsd.pbi_gid, pbi_ruid: src.pbsd.pbi_ruid, pbi_rgid: src.pbsd.pbi_rgid, pbi_svuid: src.pbsd.pbi_svuid, pbi_svgid: src.pbsd.pbi_svgid, rfu_1: src.pbsd.rfu_1, pbi_comm: src.pbsd.pbi_comm, pbi_name: src.pbsd.pbi_name, pbi_nfiles: src.pbsd.pbi_nfiles, pbi_pgid: src.pbsd.pbi_pgid, pbi_pjobc: src.pbsd.pbi_pjobc, e_tdev: src.pbsd.e_tdev, e_tpgid: src.pbsd.e_tpgid, pbi_nice: src.pbsd.pbi_nice, pbi_start_tvsec: src.pbsd.pbi_start_tvsec, pbi_start_tvusec: src.pbsd.pbi_start_tvusec, }; // Comments taken from here https://github.com/apple-oss-distributions/xnu/blob/8d741a5de7ff4191bf97d57b9f54c2f6d4a15585/bsd/sys/proc_info.h#L127 let ptinfo = TaskInfo { // virtual memory size (bytes) pti_virtual_size: src.ptinfo.pti_virtual_size, // resident memory size (bytes) pti_resident_size: src.ptinfo.pti_resident_size, // total user time pti_total_user: src.ptinfo.pti_total_user, // total system time pti_total_system: src.ptinfo.pti_total_system, // existing threads only user pti_threads_user: src.ptinfo.pti_threads_user, // existing threads only system pti_threads_system: src.ptinfo.pti_threads_system, // default policy for new threads pti_policy: src.ptinfo.pti_policy, // number of page faults pti_faults: src.ptinfo.pti_faults, // number of actual pageins pti_pageins: src.ptinfo.pti_pageins, // number of copy-on-write faults pti_cow_faults: src.ptinfo.pti_cow_faults, // number of messages sent pti_messages_sent: src.ptinfo.pti_messages_sent, // number of messages received pti_messages_received: src.ptinfo.pti_messages_received, // number of mach system calls pti_syscalls_mach: src.ptinfo.pti_syscalls_mach, // number of unix system calls pti_syscalls_unix: src.ptinfo.pti_syscalls_unix, // number of context switches pti_csw: src.ptinfo.pti_csw, // number of threads in the task pti_threadnum: src.ptinfo.pti_threadnum, // number of running threads pti_numrunning: src.ptinfo.pti_numrunning, // task priority pti_priority: src.ptinfo.pti_priority, }; TaskAllInfo { pbsd, ptinfo } } impl ProcessInfo { /// PID of process pub fn pid(&self) -> i32 { self.pid } /// Parent PID of process pub fn ppid(&self) -> i32 { self.ppid } /// Name of command pub fn name(&self) -> String { if let Some(path) = &self.curr_path { if !path.cmd.is_empty() { let command_path = &path.exe; if let Some(command_name) = command_path.file_name() { command_name.to_string_lossy().to_string() } else { command_path.to_string_lossy().to_string() } } else { String::from("") } } else { String::from("") } } /// Full name of command, with arguments pub fn command(&self) -> String { if let Some(path) = &self.curr_path { if !path.cmd.is_empty() { path.cmd.join(" ").replace(['\n', '\t'], " ") } else { String::new() } } else { String::new() } } /// Get the status of the process pub fn status(&self) -> String { let mut state = 7; for t in &self.curr_threads { let s = match t.pth_run_state { 1 => 1, // TH_STATE_RUNNING 2 => 5, // TH_STATE_STOPPED 3 => { if t.pth_sleep_time > 20 { 4 } else { 3 } } // TH_STATE_WAITING 4 => 2, // TH_STATE_UNINTERRUPTIBLE 5 => 6, // TH_STATE_HALTED _ => 7, }; state = cmp::min(s, state); } let state = match state { 0 => "", 1 => "Running", 2 => "Uninterruptible", 3 => "Sleep", 4 => "Waiting", 5 => "Stopped", 6 => "Halted", _ => "?", }; state.to_string() } /// CPU usage as a percent of total pub fn cpu_usage(&self) -> f64 { let curr_time = self.curr_task.ptinfo.pti_total_user + self.curr_task.ptinfo.pti_total_system; let prev_time = self.prev_task.ptinfo.pti_total_user + self.prev_task.ptinfo.pti_total_system; let usage_ticks = curr_time.saturating_sub(prev_time); let interval_us = self.interval.as_micros(); let ticktime_us = mach_ticktime() / 1000.0; usage_ticks as f64 * 100.0 * ticktime_us / interval_us as f64 } /// Memory size in number of bytes pub fn mem_size(&self) -> u64 { self.curr_task.ptinfo.pti_resident_size } /// Virtual memory size in bytes pub fn virtual_size(&self) -> u64 { self.curr_task.ptinfo.pti_virtual_size } pub fn cwd(&self) -> String { self.curr_path .as_ref() .map(|cur_path| cur_path.cwd.display().to_string()) .unwrap_or_default() } } /// The Macos kernel returns process times in mach ticks rather than nanoseconds. To get times in /// nanoseconds, we need to multiply by the mach timebase, a fractional value reported by the /// kernel. It is uncertain if the kernel returns the same value on each call to /// mach_timebase_info; if it does, it may be worth reimplementing this as a lazy_static value. fn mach_ticktime() -> f64 { let mut timebase = mach_time::mach_timebase_info_data_t::default(); let err = unsafe { mach_time::mach_timebase_info(&mut timebase) }; if err == 0 { timebase.numer as f64 / timebase.denom as f64 } else { // assume times are in nanoseconds then... 1.0 } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-system/src/linux.rs
crates/nu-system/src/linux.rs
use log::info; use procfs::process::{FDInfo, Io, Process, Stat, Status}; use procfs::{ProcError, ProcessCGroups, WithCurrentSystemInfo}; use std::path::PathBuf; use std::thread; use std::time::{Duration, Instant}; pub enum ProcessTask { Process(Process), Task { stat: Box<Stat>, owner: u32 }, } impl ProcessTask { pub fn stat(&self) -> Result<Stat, ProcError> { match self { ProcessTask::Process(x) => x.stat(), ProcessTask::Task { stat: x, owner: _ } => Ok(*x.clone()), } } pub fn cmdline(&self) -> Result<Vec<String>, ProcError> { match self { ProcessTask::Process(x) => x.cmdline(), _ => Err(ProcError::Other("not supported".to_string())), } } pub fn cgroups(&self) -> Result<ProcessCGroups, ProcError> { match self { ProcessTask::Process(x) => x.cgroups(), _ => Err(ProcError::Other("not supported".to_string())), } } pub fn fd(&self) -> Result<Vec<FDInfo>, ProcError> { match self { ProcessTask::Process(x) => x.fd()?.collect(), _ => Err(ProcError::Other("not supported".to_string())), } } pub fn loginuid(&self) -> Result<u32, ProcError> { match self { ProcessTask::Process(x) => x.loginuid(), _ => Err(ProcError::Other("not supported".to_string())), } } pub fn owner(&self) -> u32 { match self { ProcessTask::Process(x) => x.uid().unwrap_or(0), ProcessTask::Task { stat: _, owner: x } => *x, } } pub fn wchan(&self) -> Result<String, ProcError> { match self { ProcessTask::Process(x) => x.wchan(), _ => Err(ProcError::Other("not supported".to_string())), } } } pub struct ProcessInfo { pub pid: i32, pub ppid: i32, pub curr_proc: ProcessTask, pub curr_io: Option<Io>, pub prev_io: Option<Io>, pub curr_stat: Option<Stat>, pub prev_stat: Option<Stat>, pub curr_status: Option<Status>, pub interval: Duration, pub cwd: PathBuf, } pub fn collect_proc(interval: Duration, _with_thread: bool) -> Vec<ProcessInfo> { let mut base_procs = Vec::new(); let mut ret = Vec::new(); // Take an initial snapshot of process I/O and CPU info, so we can calculate changes over time if let Ok(all_proc) = procfs::process::all_processes() { for proc in all_proc.flatten() { let io = proc.io().ok(); let stat = proc.stat().ok(); let time = Instant::now(); base_procs.push((proc.pid(), io, stat, time)); } } // wait a bit... thread::sleep(interval); // now get process info again, build up results for (pid, prev_io, prev_stat, prev_time) in base_procs { let curr_proc_pid = pid; let curr_proc = if let Ok(p) = Process::new(curr_proc_pid) { p } else { info!( "failed to retrieve info for pid={curr_proc_pid}, process probably died between snapshots" ); continue; }; let cwd = curr_proc.cwd().unwrap_or_default(); let curr_io = curr_proc.io().ok(); let curr_stat = curr_proc.stat().ok(); let curr_status = curr_proc.status().ok(); let curr_time = Instant::now(); let interval = curr_time.saturating_duration_since(prev_time); let ppid = curr_proc.stat().map(|p| p.ppid).unwrap_or_default(); let curr_proc = ProcessTask::Process(curr_proc); let proc = ProcessInfo { pid, ppid, curr_proc, curr_io, prev_io, curr_stat, prev_stat, curr_status, interval, cwd, }; ret.push(proc); } ret } impl ProcessInfo { /// PID of process pub fn pid(&self) -> i32 { self.pid } /// PPID of process pub fn ppid(&self) -> i32 { self.ppid } /// Name of command pub fn name(&self) -> String { if let Some(name) = self.comm() { return name; } // Fall back in case /proc/<pid>/stat source is not available. if let Ok(mut cmd) = self.curr_proc.cmdline() && let Some(name) = cmd.first_mut() { // Take over the first element and return it without extra allocations // (String::default() is allocation-free). return std::mem::take(name); } String::new() } /// Full name of command, with arguments /// /// WARNING: As this does no escaping, this function is lossy. It's OK-ish for display purposes /// but nothing else. // TODO: Maybe rename this to display_command and add escaping compatible with nushell? pub fn command(&self) -> String { if let Ok(cmd) = self.curr_proc.cmdline() { // Things like kworker/0:0 still have the cmdline file in proc, even though it's empty. if !cmd.is_empty() { return cmd.join(" ").replace(['\n', '\t'], " "); } } self.comm().unwrap_or_default() } pub fn cwd(&self) -> String { self.cwd.display().to_string() } /// Get the status of the process pub fn status(&self) -> String { if let Ok(p) = self.curr_proc.stat() { match p.state { 'S' => "Sleeping", 'R' => "Running", 'D' => "Disk sleep", 'Z' => "Zombie", 'T' => "Stopped", 't' => "Tracing", 'X' => "Dead", 'x' => "Dead", 'K' => "Wakekill", 'W' => "Waking", 'P' => "Parked", _ => "Unknown", } } else { "Unknown" } .into() } /// CPU usage as a percent of total pub fn cpu_usage(&self) -> f64 { if let Some(cs) = &self.curr_stat { if let Some(ps) = &self.prev_stat { let curr_time = cs.utime + cs.stime; let prev_time = ps.utime + ps.stime; let usage_ms = curr_time.saturating_sub(prev_time) * 1000 / procfs::ticks_per_second(); let interval_ms = self.interval.as_secs() * 1000 + u64::from(self.interval.subsec_millis()); usage_ms as f64 * 100.0 / interval_ms as f64 } else { 0.0 } } else { 0.0 } } /// Memory size in number of bytes pub fn mem_size(&self) -> u64 { match self.curr_proc.stat() { Ok(p) => p.rss_bytes().get(), Err(_) => 0, } } /// Virtual memory size in bytes pub fn virtual_size(&self) -> u64 { self.curr_proc.stat().map(|p| p.vsize).unwrap_or_default() } fn comm(&self) -> Option<String> { self.curr_proc.stat().map(|st| st.comm).ok() } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-system/src/netbsd.rs
crates/nu-system/src/netbsd.rs
//! This is used for both NetBSD and OpenBSD, because they are fairly similar. use itertools::{EitherOrBoth, Itertools}; use libc::{CTL_HW, CTL_KERN, KERN_PROC_ALL, KERN_PROC_ARGS, KERN_PROC_ARGV, sysctl}; use std::{ io, mem::{self, MaybeUninit}, ptr, time::{Duration, Instant}, }; #[cfg(target_os = "netbsd")] type KInfoProc = libc::kinfo_proc2; #[cfg(target_os = "openbsd")] type KInfoProc = libc::kinfo_proc; #[derive(Debug)] pub struct ProcessInfo { pub pid: i32, pub ppid: i32, pub argv: Vec<u8>, pub stat: i8, pub percent_cpu: f64, pub mem_resident: u64, // in bytes pub mem_virtual: u64, // in bytes } pub fn collect_proc(interval: Duration, _with_thread: bool) -> Vec<ProcessInfo> { compare_procs(interval).unwrap_or_else(|err| { log::warn!("Failed to get processes: {}", err); vec![] }) } fn compare_procs(interval: Duration) -> io::Result<Vec<ProcessInfo>> { let pagesize = get_pagesize()? as u64; // Compare two full snapshots of all of the processes over the interval let now = Instant::now(); let procs_a = get_procs()?; std::thread::sleep(interval); let procs_b = get_procs()?; let true_interval = Instant::now().saturating_duration_since(now); let true_interval_sec = true_interval.as_secs_f64(); // Join the processes between the two snapshots Ok(procs_a .into_iter() .merge_join_by(procs_b.into_iter(), |a, b| a.p_pid.cmp(&b.p_pid)) .map(|proc| { // Take both snapshotted processes if we can, but if not then just keep the one that // exists and set prev_proc to None let (prev_proc, proc) = match proc { EitherOrBoth::Both(a, b) => (Some(a), b), EitherOrBoth::Left(a) => (None, a), EitherOrBoth::Right(b) => (None, b), }; // The percentage CPU is the ratio of how much runtime occurred for the process out of // the true measured interval that occurred. let percent_cpu = if let Some(prev_proc) = prev_proc { let prev_rtime = prev_proc.p_rtime_sec as f64 + prev_proc.p_rtime_usec as f64 / 1_000_000.0; let rtime = proc.p_rtime_sec as f64 + proc.p_rtime_usec as f64 / 1_000_000.0; 100. * (rtime - prev_rtime).max(0.) / true_interval_sec } else { 0.0 }; Ok(ProcessInfo { pid: proc.p_pid, ppid: proc.p_ppid, argv: get_proc_args(proc.p_pid, KERN_PROC_ARGV)?, stat: proc.p_stat, percent_cpu, mem_resident: proc.p_vm_rssize.max(0) as u64 * pagesize, #[cfg(target_os = "netbsd")] mem_virtual: proc.p_vm_msize.max(0) as u64 * pagesize, #[cfg(target_os = "openbsd")] mem_virtual: proc.p_vm_map_size.max(0) as u64 * pagesize, }) }) // Remove errors from the list - probably just processes that are gone now .flat_map(|result: io::Result<_>| result.ok()) .collect()) } fn check(err: libc::c_int) -> std::io::Result<()> { if err < 0 { Err(io::Error::last_os_error()) } else { Ok(()) } } /// Call `sysctl()` in read mode (i.e. the last two arguments to set new values are NULL and zero) /// /// `name` is a flag array. /// /// # Safety /// `data` needs to be writable for `data_len` or be a `ptr::null()` paired with `data_len = 0` to /// poll for the expected length in the `data_len` out parameter. /// /// For more details see: https://man.netbsd.org/sysctl.3 unsafe fn sysctl_get( name: *const i32, name_len: u32, data: *mut libc::c_void, data_len: *mut usize, ) -> i32 { // Safety: Call to unsafe function `libc::sysctl` unsafe { sysctl( name, name_len, data, data_len, // NetBSD and OpenBSD differ in mutability for this pointer, but it's null anyway #[cfg(target_os = "netbsd")] ptr::null(), #[cfg(target_os = "openbsd")] ptr::null_mut(), 0, ) } } fn get_procs() -> io::Result<Vec<KInfoProc>> { // To understand what's going on here, see the sysctl(3) and sysctl(7) manpages for NetBSD. unsafe { const STRUCT_SIZE: usize = mem::size_of::<KInfoProc>(); #[cfg(target_os = "netbsd")] const TGT_KERN_PROC: i32 = libc::KERN_PROC2; #[cfg(target_os = "openbsd")] const TGT_KERN_PROC: i32 = libc::KERN_PROC; let mut ctl_name = [ CTL_KERN, TGT_KERN_PROC, KERN_PROC_ALL, 0, STRUCT_SIZE as i32, 0, ]; // First, try to figure out how large a buffer we need to allocate // (calling with NULL just tells us that) let mut data_len = 0; check(sysctl_get( ctl_name.as_ptr(), ctl_name.len() as u32, ptr::null_mut(), &mut data_len, ))?; // data_len will be set in bytes, so divide by the size of the structure let expected_len = data_len.div_ceil(STRUCT_SIZE); // Now allocate the Vec and set data_len to the real number of bytes allocated let mut vec: Vec<KInfoProc> = Vec::with_capacity(expected_len); data_len = vec.capacity() * STRUCT_SIZE; // We are also supposed to set ctl_name[5] to the number of structures we want ctl_name[5] = expected_len.try_into().expect("expected_len too big"); // Call sysctl() again to put the result in the vec check(sysctl_get( ctl_name.as_ptr(), ctl_name.len() as u32, vec.as_mut_ptr() as *mut libc::c_void, &mut data_len, ))?; // If that was ok, we can set the actual length of the vec to whatever // data_len was changed to, since that should now all be properly initialized data. let true_len = data_len.div_ceil(STRUCT_SIZE); vec.set_len(true_len); // Sort the procs by pid before using them vec.sort_by_key(|p| p.p_pid); Ok(vec) } } fn get_proc_args(pid: i32, what: i32) -> io::Result<Vec<u8>> { unsafe { let ctl_name = [CTL_KERN, KERN_PROC_ARGS, pid, what]; // First, try to figure out how large a buffer we need to allocate // (calling with NULL just tells us that) let mut data_len = 0; check(sysctl_get( ctl_name.as_ptr(), ctl_name.len() as u32, ptr::null_mut(), &mut data_len, ))?; // Now allocate the Vec and set data_len to the real number of bytes allocated let mut vec: Vec<u8> = Vec::with_capacity(data_len); data_len = vec.capacity(); // Call sysctl() again to put the result in the vec check(sysctl_get( ctl_name.as_ptr(), ctl_name.len() as u32, vec.as_mut_ptr() as *mut libc::c_void, &mut data_len, ))?; // If that was ok, we can set the actual length of the vec to whatever // data_len was changed to, since that should now all be properly initialized data. vec.set_len(data_len); // On OpenBSD we have to do an extra step, because it fills the buffer with pointers to the // strings first, even though the strings are within the buffer as well. #[cfg(target_os = "openbsd")] let vec = { use std::ffi::CStr; // Set up some bounds checking. We assume there will be some pointers at the base until // we reach NULL, but we want to make sure we only ever read data within the range of // min_ptr..max_ptr. let ptrs = vec.as_ptr() as *const *const u8; let min_ptr = vec.as_ptr() as *const u8; let max_ptr = vec.as_ptr().add(vec.len()) as *const u8; let max_index: isize = (vec.len() / mem::size_of::<*const u8>()) .try_into() .expect("too big for isize"); let mut new_vec = Vec::with_capacity(vec.len()); for index in 0..max_index { let ptr = ptrs.offset(index); if *ptr == ptr::null() { break; } else { // Make sure it's within the bounds of the buffer assert!( *ptr >= min_ptr && *ptr < max_ptr, "pointer out of bounds of the buffer returned by sysctl()" ); // Also bounds-check the C strings, to make sure we don't overrun the buffer new_vec.extend( CStr::from_bytes_until_nul(std::slice::from_raw_parts( *ptr, max_ptr.offset_from(*ptr) as usize, )) .expect("invalid C string") .to_bytes_with_nul(), ); } } new_vec }; Ok(vec) } } /// For getting simple values from the sysctl interface /// /// # Safety /// `T` needs to be of the structure that is expected to be returned by `sysctl` for the given /// `ctl_name` sequence and will then be assumed to be of correct layout. /// Thus only use it for primitive types or well defined fixed size types. For variable length /// arrays that can be returned from `sysctl` use it directly (or write a proper wrapper handling /// capacity management) /// /// # Panics /// If the size of the returned data diverges from the size of the expected `T` unsafe fn get_ctl<T>(ctl_name: &[i32]) -> io::Result<T> { let mut value: MaybeUninit<T> = MaybeUninit::uninit(); let mut value_len = mem::size_of_val(&value); // SAFETY: lengths to the pointers is provided, uninitialized data with checked length provided // Only assume initialized when the written data doesn't diverge in length, layout is the // safety responsibility of the caller. check(unsafe { sysctl_get( ctl_name.as_ptr(), ctl_name.len() as u32, value.as_mut_ptr() as *mut libc::c_void, &mut value_len, ) })?; assert_eq!( value_len, mem::size_of_val(&value), "Data requested from from `sysctl` diverged in size from the expected return type. For variable length data you need to manually truncate the data to the valid returned size!" ); Ok(unsafe { value.assume_init() }) } fn get_pagesize() -> io::Result<libc::c_int> { // not in libc for some reason const HW_PAGESIZE: i32 = 7; unsafe { get_ctl(&[CTL_HW, HW_PAGESIZE]) } } impl ProcessInfo { /// PID of process pub fn pid(&self) -> i32 { self.pid } /// Parent PID of process pub fn ppid(&self) -> i32 { self.ppid } /// Name of command pub fn name(&self) -> String { self.argv .split(|b| *b == 0) .next() .map(String::from_utf8_lossy) .unwrap_or_default() .into_owned() } /// Full name of command, with arguments pub fn command(&self) -> String { if let Some(last_nul) = self.argv.iter().rposition(|b| *b == 0) { // The command string is NUL separated // Take the string up to the last NUL, then replace the NULs with spaces String::from_utf8_lossy(&self.argv[0..last_nul]).replace("\0", " ") } else { "".into() } } /// Get the status of the process pub fn status(&self) -> String { // see sys/proc.h (OpenBSD), sys/lwp.h (NetBSD) // the names given here are the NetBSD ones, starting with LS*, but the OpenBSD ones are // the same, just starting with S* instead match self.stat { 1 /* LSIDL */ => "", 2 /* LSRUN */ => "Waiting", 3 /* LSSLEEP */ => "Sleeping", 4 /* LSSTOP */ => "Stopped", 5 /* LSZOMB */ => "Zombie", #[cfg(target_os = "openbsd")] // removed in NetBSD 6 /* LSDEAD */ => "Dead", 7 /* LSONPROC */ => "Running", #[cfg(target_os = "netbsd")] // doesn't exist in OpenBSD 8 /* LSSUSPENDED */ => "Suspended", _ => "Unknown", } .into() } /// CPU usage as a percent of total pub fn cpu_usage(&self) -> f64 { self.percent_cpu } /// Memory size in number of bytes pub fn mem_size(&self) -> u64 { self.mem_resident } /// Virtual memory size in bytes pub fn virtual_size(&self) -> u64 { self.mem_virtual } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-system/src/util.rs
crates/nu-system/src/util.rs
use std::io; use std::process::Command as CommandSys; /// Tries to forcefully kill a process by its PID pub fn kill_by_pid(pid: i64) -> Result<(), KillByPidError> { let mut cmd = build_kill_command(true, std::iter::once(pid), None); let output = cmd.output().map_err(KillByPidError::Output)?; match output.status.success() { true => Ok(()), false => Err(KillByPidError::KillProcess), } } /// Error while killing a process forcefully by its PID. pub enum KillByPidError { /// I/O error while capturing the output of the process. Output(io::Error), /// Killing the process failed. KillProcess, } /// Create a `std::process::Command` for the current target platform, for killing /// the processes with the given PIDs pub fn build_kill_command( force: bool, pids: impl Iterator<Item = i64>, signal: Option<u32>, ) -> CommandSys { if cfg!(windows) { let mut cmd = CommandSys::new("taskkill"); if force { cmd.arg("/F"); } // each pid must written as `/PID 0` otherwise // taskkill will act as `killall` unix command for id in pids { cmd.arg("/PID"); cmd.arg(id.to_string()); } cmd } else { let mut cmd = CommandSys::new("kill"); if let Some(signal_value) = signal { cmd.arg(format!("-{signal_value}")); } else if force { cmd.arg("-9"); } cmd.args(pids.map(move |id| id.to_string())); cmd } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-system/src/windows.rs
crates/nu-system/src/windows.rs
// Attribution: a lot of this came from procs https://github.com/dalance/procs // and sysinfo https://github.com/GuillaumeGomez/sysinfo use chrono::offset::TimeZone; use chrono::{Local, NaiveDate}; use libc::c_void; use ntapi::ntrtl::RTL_USER_PROCESS_PARAMETERS; use ntapi::ntwow64::{PEB32, RTL_USER_PROCESS_PARAMETERS32}; use std::cell::RefCell; use std::collections::HashMap; use std::ffi::OsString; use std::mem::{MaybeUninit, size_of, zeroed}; use std::os::windows::ffi::OsStringExt; use std::path::PathBuf; use std::ptr; use std::ptr::null_mut; use std::sync::LazyLock; use std::thread; use std::time::Duration; use web_time::Instant; use windows::core::{PCWSTR, PWSTR}; use windows::Wdk::System::SystemServices::RtlGetVersion; use windows::Wdk::System::Threading::{ NtQueryInformationProcess, PROCESSINFOCLASS, ProcessBasicInformation, ProcessCommandLineInformation, ProcessWow64Information, }; use windows::Win32::Foundation::{ CloseHandle, FALSE, FILETIME, HANDLE, HLOCAL, HMODULE, LocalFree, MAX_PATH, STATUS_BUFFER_OVERFLOW, STATUS_BUFFER_TOO_SMALL, STATUS_INFO_LENGTH_MISMATCH, UNICODE_STRING, }; use windows::Win32::Security::{ AdjustTokenPrivileges, GetTokenInformation, LookupAccountSidW, LookupPrivilegeValueW, PSID, SE_DEBUG_NAME, SE_PRIVILEGE_ENABLED, SID, SID_NAME_USE, TOKEN_ADJUST_PRIVILEGES, TOKEN_GROUPS, TOKEN_PRIVILEGES, TOKEN_QUERY, TOKEN_USER, TokenGroups, TokenUser, }; use windows::Win32::System::Diagnostics::Debug::ReadProcessMemory; use windows::Win32::System::Diagnostics::ToolHelp::{ CreateToolhelp32Snapshot, PROCESSENTRY32, Process32First, Process32Next, TH32CS_SNAPPROCESS, }; use windows::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQueryEx}; use windows::Win32::System::ProcessStatus::{ GetModuleBaseNameW, GetProcessMemoryInfo, K32EnumProcesses, PROCESS_MEMORY_COUNTERS, PROCESS_MEMORY_COUNTERS_EX, }; use windows::Win32::System::SystemInformation::OSVERSIONINFOEXW; use windows::Win32::System::Threading::{ GetCurrentProcess, GetPriorityClass, GetProcessIoCounters, GetProcessTimes, IO_COUNTERS, OpenProcess, OpenProcessToken, PEB, PROCESS_BASIC_INFORMATION, PROCESS_QUERY_INFORMATION, PROCESS_VM_READ, }; use windows::Win32::UI::Shell::CommandLineToArgvW; pub struct ProcessInfo { pub pid: i32, pub command: String, pub ppid: i32, pub start_time: chrono::DateTime<chrono::Local>, pub cpu_info: CpuInfo, pub memory_info: MemoryInfo, pub disk_info: DiskInfo, pub user: SidName, pub groups: Vec<SidName>, pub priority: u32, pub thread: i32, pub interval: Duration, pub cmd: Vec<String>, pub environ: Vec<String>, pub cwd: PathBuf, } #[derive(Default)] pub struct MemoryInfo { pub page_fault_count: u64, pub peak_working_set_size: u64, pub working_set_size: u64, pub quota_peak_paged_pool_usage: u64, pub quota_paged_pool_usage: u64, pub quota_peak_non_paged_pool_usage: u64, pub quota_non_paged_pool_usage: u64, pub page_file_usage: u64, pub peak_page_file_usage: u64, pub private_usage: u64, } #[derive(Default)] pub struct DiskInfo { pub prev_read: u64, pub prev_write: u64, pub curr_read: u64, pub curr_write: u64, } #[derive(Default)] pub struct CpuInfo { pub prev_sys: u64, pub prev_user: u64, pub curr_sys: u64, pub curr_user: u64, } pub fn collect_proc(interval: Duration, _with_thread: bool) -> Vec<ProcessInfo> { let mut base_procs = Vec::new(); let mut ret = Vec::new(); let _ = set_privilege(); for pid in get_pids() { let handle = get_handle(pid); if let Some(handle) = handle { let times = get_times(handle); let io = get_io(handle); let time = Instant::now(); if let (Some((_, _, sys, user)), Some((read, write))) = (times, io) { base_procs.push((pid, sys, user, read, write, time)); } } } thread::sleep(interval); let (mut ppids, mut threads) = get_ppid_threads(); for (pid, prev_sys, prev_user, prev_read, prev_write, prev_time) in base_procs { let ppid = ppids.remove(&pid); let thread = threads.remove(&pid); let handle = get_handle(pid); if let Some(handle) = handle { let command = get_command(handle); let memory_info = get_memory_info(handle); let times = get_times(handle); let io = get_io(handle); let start_time = if let Some((start, _, _, _)) = times { // 11_644_473_600 is the number of seconds between the Windows epoch (1601-01-01) and // the Linux epoch (1970-01-01). let Some(time) = chrono::Duration::try_seconds(start as i64 / 10_000_000) else { continue; }; let base = NaiveDate::from_ymd_opt(1601, 1, 1).and_then(|nd| nd.and_hms_opt(0, 0, 0)); if let Some(base) = base { let time = base + time; Local.from_utc_datetime(&time) } else { continue; } } else { let time = NaiveDate::from_ymd_opt(1601, 1, 1).and_then(|nt| nt.and_hms_opt(0, 0, 0)); if let Some(time) = time { Local.from_utc_datetime(&time) } else { continue; } }; let cpu_info = if let Some((_, _, curr_sys, curr_user)) = times { Some(CpuInfo { prev_sys, prev_user, curr_sys, curr_user, }) } else { None }; let disk_info = if let Some((curr_read, curr_write)) = io { Some(DiskInfo { prev_read, prev_write, curr_read, curr_write, }) } else { None }; let user = get_user(handle); let groups = get_groups(handle); let priority = get_priority(handle); let curr_time = Instant::now(); let interval = curr_time.saturating_duration_since(prev_time); let mut all_ok = true; all_ok &= command.is_some(); all_ok &= cpu_info.is_some(); all_ok &= memory_info.is_some(); all_ok &= disk_info.is_some(); all_ok &= user.is_some(); all_ok &= groups.is_some(); all_ok &= thread.is_some(); if all_ok { let (proc_cmd, proc_env, proc_cwd) = match unsafe { get_process_params(handle) } { Ok(pp) => (pp.0, pp.1, pp.2), Err(_) => (vec![], vec![], PathBuf::new()), }; let command = command.unwrap_or_default(); let ppid = ppid.unwrap_or(0); let cpu_info = cpu_info.unwrap_or_default(); let memory_info = memory_info.unwrap_or_default(); let disk_info = disk_info.unwrap_or_default(); let user = user.unwrap_or_else(|| SidName { sid: vec![], name: None, domainname: None, }); let groups = groups.unwrap_or_default(); let thread = thread.unwrap_or_default(); let proc = ProcessInfo { pid, command, ppid, start_time, cpu_info, memory_info, disk_info, user, groups, priority, thread, interval, cmd: proc_cmd, environ: proc_env, cwd: proc_cwd, }; ret.push(proc); } unsafe { let _ = CloseHandle(handle); } } } ret } fn set_privilege() -> bool { unsafe { let handle = GetCurrentProcess(); let mut token: HANDLE = zeroed(); let ret = OpenProcessToken(handle, TOKEN_ADJUST_PRIVILEGES, &mut token); if ret.is_err() { return false; } let mut tps: TOKEN_PRIVILEGES = zeroed(); tps.PrivilegeCount = 1; if LookupPrivilegeValueW(PCWSTR::null(), SE_DEBUG_NAME, &mut tps.Privileges[0].Luid) .is_err() { return false; } tps.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; if AdjustTokenPrivileges(token, FALSE.into(), Some(&tps), 0, None, None).is_err() { return false; } true } } fn get_pids() -> Vec<i32> { let dword_size = size_of::<u32>(); let mut pids: Vec<u32> = Vec::with_capacity(10192); let mut cb_needed = 0; unsafe { pids.set_len(10192); let result = K32EnumProcesses( pids.as_mut_ptr(), (dword_size * pids.len()) as u32, &mut cb_needed, ); if !result.as_bool() { return Vec::new(); } let pids_len = cb_needed / dword_size as u32; pids.set_len(pids_len as usize); } pids.iter().map(|x| *x as i32).collect() } fn get_ppid_threads() -> (HashMap<i32, i32>, HashMap<i32, i32>) { let mut ppids = HashMap::new(); let mut threads = HashMap::new(); unsafe { let Ok(snapshot) = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) else { return (ppids, threads); }; let mut entry: PROCESSENTRY32 = zeroed(); entry.dwSize = size_of::<PROCESSENTRY32>() as u32; let mut not_the_end = Process32First(snapshot, &mut entry); while not_the_end.is_ok() { ppids.insert(entry.th32ProcessID as i32, entry.th32ParentProcessID as i32); threads.insert(entry.th32ProcessID as i32, entry.cntThreads as i32); not_the_end = Process32Next(snapshot, &mut entry); } let _ = CloseHandle(snapshot); } (ppids, threads) } fn get_handle(pid: i32) -> Option<HANDLE> { if pid == 0 { return None; } let handle = unsafe { OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE.into(), pid as u32, ) } .ok(); match handle { Some(h) if h.is_invalid() => None, h => h, } } fn get_times(handle: HANDLE) -> Option<(u64, u64, u64, u64)> { unsafe { let mut start: FILETIME = zeroed(); let mut exit: FILETIME = zeroed(); let mut sys: FILETIME = zeroed(); let mut user: FILETIME = zeroed(); let ret = GetProcessTimes( handle, &mut start as *mut FILETIME, &mut exit as *mut FILETIME, &mut sys as *mut FILETIME, &mut user as *mut FILETIME, ); let start = (u64::from(start.dwHighDateTime) << 32) | u64::from(start.dwLowDateTime); let exit = (u64::from(exit.dwHighDateTime) << 32) | u64::from(exit.dwLowDateTime); let sys = (u64::from(sys.dwHighDateTime) << 32) | u64::from(sys.dwLowDateTime); let user = (u64::from(user.dwHighDateTime) << 32) | u64::from(user.dwLowDateTime); if ret.is_ok() { Some((start, exit, sys, user)) } else { None } } } fn get_memory_info(handle: HANDLE) -> Option<MemoryInfo> { unsafe { let mut pmc: PROCESS_MEMORY_COUNTERS_EX = zeroed(); let ret = GetProcessMemoryInfo( handle, &mut pmc as *mut PROCESS_MEMORY_COUNTERS_EX as *mut c_void as *mut PROCESS_MEMORY_COUNTERS, size_of::<PROCESS_MEMORY_COUNTERS_EX>() as u32, ); if ret.is_ok() { let info = MemoryInfo { page_fault_count: u64::from(pmc.PageFaultCount), peak_working_set_size: pmc.PeakWorkingSetSize as u64, working_set_size: pmc.WorkingSetSize as u64, quota_peak_paged_pool_usage: pmc.QuotaPeakPagedPoolUsage as u64, quota_paged_pool_usage: pmc.QuotaPagedPoolUsage as u64, quota_peak_non_paged_pool_usage: pmc.QuotaPeakNonPagedPoolUsage as u64, quota_non_paged_pool_usage: pmc.QuotaNonPagedPoolUsage as u64, page_file_usage: pmc.PagefileUsage as u64, peak_page_file_usage: pmc.PeakPagefileUsage as u64, private_usage: pmc.PrivateUsage as u64, }; Some(info) } else { None } } } fn get_command(handle: HANDLE) -> Option<String> { unsafe { let mut exe_buf = [0u16; MAX_PATH as usize + 1]; let h_mod = HMODULE::default(); let ret = GetModuleBaseNameW(handle, h_mod.into(), exe_buf.as_mut_slice()); let mut pos = 0; for x in exe_buf.iter() { if *x == 0 { break; } pos += 1; } if ret != 0 { Some(String::from_utf16_lossy(&exe_buf[..pos])) } else { None } } } trait RtlUserProcessParameters { fn get_cmdline(&self, handle: HANDLE) -> Result<Vec<u16>, &'static str>; fn get_cwd(&self, handle: HANDLE) -> Result<Vec<u16>, &'static str>; fn get_environ(&self, handle: HANDLE) -> Result<Vec<u16>, &'static str>; } macro_rules! impl_RtlUserProcessParameters { ($t:ty) => { impl RtlUserProcessParameters for $t { fn get_cmdline(&self, handle: HANDLE) -> Result<Vec<u16>, &'static str> { let ptr = self.CommandLine.Buffer; let size = self.CommandLine.Length; unsafe { get_process_data(handle, ptr as _, size as _) } } fn get_cwd(&self, handle: HANDLE) -> Result<Vec<u16>, &'static str> { let ptr = self.CurrentDirectory.DosPath.Buffer; let size = self.CurrentDirectory.DosPath.Length; unsafe { get_process_data(handle, ptr as _, size as _) } } fn get_environ(&self, handle: HANDLE) -> Result<Vec<u16>, &'static str> { let ptr = self.Environment; unsafe { let size = get_region_size(handle, ptr as _)?; get_process_data(handle, ptr as _, size as _) } } } }; } impl_RtlUserProcessParameters!(RTL_USER_PROCESS_PARAMETERS32); impl_RtlUserProcessParameters!(RTL_USER_PROCESS_PARAMETERS); unsafe fn null_terminated_wchar_to_string(slice: &[u16]) -> String { match slice.iter().position(|&x| x == 0) { Some(pos) => OsString::from_wide(&slice[..pos]) .to_string_lossy() .into_owned(), None => OsString::from_wide(slice).to_string_lossy().into_owned(), } } unsafe fn get_process_data( handle: HANDLE, ptr: *const c_void, size: usize, ) -> Result<Vec<u16>, &'static str> { let mut buffer: Vec<u16> = Vec::with_capacity(size / 2 + 1); let mut bytes_read = 0; unsafe { if ReadProcessMemory( handle, ptr, buffer.as_mut_ptr().cast(), size, Some(&mut bytes_read), ) .is_err() { return Err("Unable to read process data"); } // Documentation states that the function fails if not all data is accessible. if bytes_read != size { return Err("ReadProcessMemory returned unexpected number of bytes read"); } buffer.set_len(size / 2); buffer.push(0); } Ok(buffer) } unsafe fn get_region_size(handle: HANDLE, ptr: *const c_void) -> Result<usize, &'static str> { unsafe { let mut meminfo = MaybeUninit::<MEMORY_BASIC_INFORMATION>::uninit(); if VirtualQueryEx( handle, Some(ptr), meminfo.as_mut_ptr().cast(), size_of::<MEMORY_BASIC_INFORMATION>(), ) == 0 { return Err("Unable to read process memory information"); } let meminfo = meminfo.assume_init(); Ok((meminfo.RegionSize as isize - ptr.offset_from(meminfo.BaseAddress)) as usize) } } unsafe fn ph_query_process_variable_size( process_handle: HANDLE, process_information_class: PROCESSINFOCLASS, ) -> Option<Vec<u16>> { unsafe { let mut return_length = MaybeUninit::<u32>::uninit(); if let Err(err) = NtQueryInformationProcess( process_handle, process_information_class, std::ptr::null_mut(), 0, return_length.as_mut_ptr() as *mut _, ) .ok() && ![ STATUS_BUFFER_OVERFLOW.into(), STATUS_BUFFER_TOO_SMALL.into(), STATUS_INFO_LENGTH_MISMATCH.into(), ] .contains(&err.code()) { return None; } let mut return_length = return_length.assume_init(); let buf_len = (return_length as usize) / 2; let mut buffer: Vec<u16> = Vec::with_capacity(buf_len + 1); if NtQueryInformationProcess( process_handle, process_information_class, buffer.as_mut_ptr() as *mut _, return_length, &mut return_length as *mut _, ) .is_err() { return None; } buffer.set_len(buf_len); buffer.push(0); Some(buffer) } } unsafe fn get_cmdline_from_buffer(buffer: PCWSTR) -> Vec<String> { unsafe { // Get argc and argv from the command line let mut argc = MaybeUninit::<i32>::uninit(); let argv_p = CommandLineToArgvW(buffer, argc.as_mut_ptr()); if argv_p.is_null() { return Vec::new(); } let argc = argc.assume_init(); let argv = std::slice::from_raw_parts(argv_p, argc as usize); let mut res = Vec::new(); for arg in argv { res.push(String::from_utf16_lossy(arg.as_wide())); } let _err = LocalFree(HLOCAL(argv_p as _).into()); res } } unsafe fn get_process_params( handle: HANDLE, ) -> Result<(Vec<String>, Vec<String>, PathBuf), &'static str> { unsafe { if !cfg!(target_pointer_width = "64") { return Err("Non 64 bit targets are not supported"); } // First check if target process is running in wow64 compatibility emulator let mut pwow32info = MaybeUninit::<*const c_void>::uninit(); if NtQueryInformationProcess( handle, ProcessWow64Information, pwow32info.as_mut_ptr().cast(), size_of::<*const c_void>() as u32, null_mut(), ) .is_err() { return Err("Unable to check WOW64 information about the process"); } let pwow32info = pwow32info.assume_init(); if pwow32info.is_null() { // target is a 64 bit process let mut pbasicinfo = MaybeUninit::<PROCESS_BASIC_INFORMATION>::uninit(); if NtQueryInformationProcess( handle, ProcessBasicInformation, pbasicinfo.as_mut_ptr().cast(), size_of::<PROCESS_BASIC_INFORMATION>() as u32, null_mut(), ) .is_err() { return Err("Unable to get basic process information"); } let pinfo = pbasicinfo.assume_init(); let mut peb = MaybeUninit::<PEB>::uninit(); if ReadProcessMemory( handle, pinfo.PebBaseAddress.cast(), peb.as_mut_ptr().cast(), size_of::<PEB>(), None, ) .is_err() { return Err("Unable to read process PEB"); } let peb = peb.assume_init(); let mut proc_params = MaybeUninit::<RTL_USER_PROCESS_PARAMETERS>::uninit(); if ReadProcessMemory( handle, peb.ProcessParameters.cast(), proc_params.as_mut_ptr().cast(), size_of::<RTL_USER_PROCESS_PARAMETERS>(), None, ) .is_err() { return Err("Unable to read process parameters"); } let proc_params = proc_params.assume_init(); return Ok(( get_cmd_line(&proc_params, handle), get_proc_env(&proc_params, handle), get_cwd(&proc_params, handle), )); } // target is a 32 bit process in wow64 mode let mut peb32 = MaybeUninit::<PEB32>::uninit(); if ReadProcessMemory( handle, pwow32info, peb32.as_mut_ptr().cast(), size_of::<PEB32>(), None, ) .is_err() { return Err("Unable to read PEB32"); } let peb32 = peb32.assume_init(); let mut proc_params = MaybeUninit::<RTL_USER_PROCESS_PARAMETERS32>::uninit(); if ReadProcessMemory( handle, peb32.ProcessParameters as *mut _, proc_params.as_mut_ptr().cast(), size_of::<RTL_USER_PROCESS_PARAMETERS32>(), None, ) .is_err() { return Err("Unable to read 32 bit process parameters"); } let proc_params = proc_params.assume_init(); Ok(( get_cmd_line(&proc_params, handle), get_proc_env(&proc_params, handle), get_cwd(&proc_params, handle), )) } } static WINDOWS_8_1_OR_NEWER: LazyLock<bool> = LazyLock::new(|| unsafe { let mut version_info: OSVERSIONINFOEXW = MaybeUninit::zeroed().assume_init(); version_info.dwOSVersionInfoSize = std::mem::size_of::<OSVERSIONINFOEXW>() as u32; if RtlGetVersion((&mut version_info as *mut OSVERSIONINFOEXW).cast()).is_err() { return true; } // Windows 8.1 is 6.3 version_info.dwMajorVersion > 6 || version_info.dwMajorVersion == 6 && version_info.dwMinorVersion >= 3 }); fn get_cmd_line<T: RtlUserProcessParameters>(params: &T, handle: HANDLE) -> Vec<String> { if *WINDOWS_8_1_OR_NEWER { get_cmd_line_new(handle) } else { get_cmd_line_old(params, handle) } } #[allow(clippy::cast_ptr_alignment)] fn get_cmd_line_new(handle: HANDLE) -> Vec<String> { unsafe { if let Some(buffer) = ph_query_process_variable_size(handle, ProcessCommandLineInformation) { let buffer = (*(buffer.as_ptr() as *const UNICODE_STRING)).Buffer; get_cmdline_from_buffer(PCWSTR::from_raw(buffer.as_ptr())) } else { Vec::new() } } } fn get_cmd_line_old<T: RtlUserProcessParameters>(params: &T, handle: HANDLE) -> Vec<String> { match params.get_cmdline(handle) { Ok(buffer) => unsafe { get_cmdline_from_buffer(PCWSTR::from_raw(buffer.as_ptr())) }, Err(_e) => Vec::new(), } } fn get_proc_env<T: RtlUserProcessParameters>(params: &T, handle: HANDLE) -> Vec<String> { match params.get_environ(handle) { Ok(buffer) => { let equals = "=" .encode_utf16() .next() .expect("unable to get next utf16 value"); let raw_env = buffer; let mut result = Vec::new(); let mut begin = 0; while let Some(offset) = raw_env[begin..].iter().position(|&c| c == 0) { let end = begin + offset; if raw_env[begin..end].contains(&equals) { result.push( OsString::from_wide(&raw_env[begin..end]) .to_string_lossy() .into_owned(), ); begin = end + 1; } else { break; } } result } Err(_e) => Vec::new(), } } fn get_cwd<T: RtlUserProcessParameters>(params: &T, handle: HANDLE) -> PathBuf { match params.get_cwd(handle) { Ok(buffer) => unsafe { PathBuf::from(null_terminated_wchar_to_string(buffer.as_slice())) }, Err(_e) => PathBuf::new(), } } fn get_io(handle: HANDLE) -> Option<(u64, u64)> { unsafe { let mut io: IO_COUNTERS = zeroed(); let ret = GetProcessIoCounters(handle, &mut io); if ret.is_ok() { Some((io.ReadTransferCount, io.WriteTransferCount)) } else { None } } } #[derive(Clone)] pub struct SidName { pub sid: Vec<u64>, pub name: Option<String>, pub domainname: Option<String>, } fn get_user(handle: HANDLE) -> Option<SidName> { unsafe { let mut token: HANDLE = zeroed(); let ret = OpenProcessToken(handle, TOKEN_QUERY, &mut token); if ret.is_err() { return None; } let mut cb_needed = 0; let _ = GetTokenInformation( token, TokenUser, Some(ptr::null::<c_void>() as *mut c_void), 0, &mut cb_needed, ); let mut buf: Vec<u8> = Vec::with_capacity(cb_needed as usize); let ret = GetTokenInformation( token, TokenUser, Some(buf.as_mut_ptr() as *mut c_void), cb_needed, &mut cb_needed, ); buf.set_len(cb_needed as usize); if ret.is_err() { return None; } #[allow(clippy::cast_ptr_alignment)] let token_user = buf.as_ptr() as *const TOKEN_USER; let psid = (*token_user).User.Sid; let sid = get_sid(psid); let (name, domainname) = if let Some((x, y)) = get_name_cached(psid) { (Some(x), Some(y)) } else { (None, None) }; Some(SidName { sid, name, domainname, }) } } fn get_groups(handle: HANDLE) -> Option<Vec<SidName>> { unsafe { let mut token: HANDLE = zeroed(); let ret = OpenProcessToken(handle, TOKEN_QUERY, &mut token); if ret.is_err() { return None; } let mut cb_needed = 0; let _ = GetTokenInformation( token, TokenGroups, Some(ptr::null::<c_void>() as *mut c_void), 0, &mut cb_needed, ); let mut buf: Vec<u8> = Vec::with_capacity(cb_needed as usize); let ret = GetTokenInformation( token, TokenGroups, Some(buf.as_mut_ptr() as *mut c_void), cb_needed, &mut cb_needed, ); buf.set_len(cb_needed as usize); if ret.is_err() { return None; } #[allow(clippy::cast_ptr_alignment)] let token_groups = buf.as_ptr() as *const TOKEN_GROUPS; let mut ret = Vec::new(); let sa = (*token_groups).Groups.as_ptr(); for i in 0..(*token_groups).GroupCount { let psid = (*sa.offset(i as isize)).Sid; let sid = get_sid(psid); let (name, domainname) = if let Some((x, y)) = get_name_cached(psid) { (Some(x), Some(y)) } else { (None, None) }; let sid_name = SidName { sid, name, domainname, }; ret.push(sid_name); } Some(ret) } } fn get_sid(psid: PSID) -> Vec<u64> { unsafe { let mut ret = Vec::new(); let psid = psid.0 as *const SID; let mut ia = 0; ia |= u64::from((*psid).IdentifierAuthority.Value[0]) << 40; ia |= u64::from((*psid).IdentifierAuthority.Value[1]) << 32; ia |= u64::from((*psid).IdentifierAuthority.Value[2]) << 24; ia |= u64::from((*psid).IdentifierAuthority.Value[3]) << 16; ia |= u64::from((*psid).IdentifierAuthority.Value[4]) << 8; ia |= u64::from((*psid).IdentifierAuthority.Value[5]); ret.push(u64::from((*psid).Revision)); ret.push(ia); let cnt = (*psid).SubAuthorityCount; let sa = (*psid).SubAuthority.as_ptr(); for i in 0..cnt { ret.push(u64::from(*sa.offset(i as isize))); } ret } } thread_local!( pub static NAME_CACHE: RefCell<HashMap<*mut c_void, Option<(String, String)>>> = RefCell::new(HashMap::new()); ); fn get_name_cached(psid: PSID) -> Option<(String, String)> { NAME_CACHE.with(|c| { let mut c = c.borrow_mut(); if let Some(x) = c.get(&psid.0) { x.clone() } else { let x = get_name(psid); c.insert(psid.0, x.clone()); x } }) } fn get_name(psid: PSID) -> Option<(String, String)> { unsafe { let mut cc_name = 0; let mut cc_domainname = 0; let mut pe_use = SID_NAME_USE::default(); let _ = LookupAccountSidW( None, psid, None, &mut cc_name, None, &mut cc_domainname, &mut pe_use, ); if cc_name == 0 || cc_domainname == 0 { return None; } let mut name: Vec<u16> = Vec::with_capacity(cc_name as usize); let mut domainname: Vec<u16> = Vec::with_capacity(cc_domainname as usize); name.set_len(cc_name as usize); domainname.set_len(cc_domainname as usize); if LookupAccountSidW( None, psid, PWSTR::from_raw(name.as_mut_ptr()).into(), &mut cc_name, PWSTR::from_raw(domainname.as_mut_ptr()).into(), &mut cc_domainname, &mut pe_use, ) .is_err() { return None; } let name = from_wide_ptr(name.as_ptr()); let domainname = from_wide_ptr(domainname.as_ptr()); Some((name, domainname)) } } fn from_wide_ptr(ptr: *const u16) -> String { unsafe { assert!(!ptr.is_null()); let len = (0..isize::MAX) .position(|i| *ptr.offset(i) == 0) .unwrap_or_default(); let slice = std::slice::from_raw_parts(ptr, len); OsString::from_wide(slice).to_string_lossy().into_owned() } } fn get_priority(handle: HANDLE) -> u32 { unsafe { GetPriorityClass(handle) } } impl ProcessInfo { /// PID of process pub fn pid(&self) -> i32 { self.pid } /// Parent PID of process pub fn ppid(&self) -> i32 { self.ppid } /// Name of command pub fn name(&self) -> String { self.command.clone() } /// Full name of command, with arguments pub fn command(&self) -> String { self.cmd.join(" ") } pub fn environ(&self) -> Vec<String> { self.environ.clone() } pub fn cwd(&self) -> String { self.cwd.display().to_string() } /// Get the status of the process pub fn status(&self) -> String { "unknown".to_string() } /// CPU usage as a percent of total pub fn cpu_usage(&self) -> f64 { let curr_time = self.cpu_info.curr_sys + self.cpu_info.curr_user; let prev_time = self.cpu_info.prev_sys + self.cpu_info.prev_user; let usage_ms = curr_time.saturating_sub(prev_time) / 10000u64; let interval_ms = self.interval.as_secs() * 1000 + u64::from(self.interval.subsec_millis()); usage_ms as f64 * 100.0 / interval_ms as f64 } /// Memory size in number of bytes pub fn mem_size(&self) -> u64 { self.memory_info.working_set_size } /// Virtual memory size in bytes pub fn virtual_size(&self) -> u64 { self.memory_info.private_usage } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-system/src/exit_status.rs
crates/nu-system/src/exit_status.rs
use std::process; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ExitStatus { Exited(i32), #[cfg(unix)] Signaled { signal: i32, core_dumped: bool, }, } impl ExitStatus { pub fn code(self) -> i32 { match self { ExitStatus::Exited(code) => code, #[cfg(unix)] ExitStatus::Signaled { signal, .. } => -signal, } } } #[cfg(unix)] impl From<process::ExitStatus> for ExitStatus { fn from(status: process::ExitStatus) -> Self { use std::os::unix::process::ExitStatusExt; match (status.code(), status.signal()) { (Some(code), None) => Self::Exited(code), (None, Some(signal)) => Self::Signaled { signal, core_dumped: status.core_dumped(), }, (None, None) => { debug_assert!(false, "ExitStatus should have either a code or a signal"); Self::Exited(-1) } (Some(code), Some(signal)) => { // Should be unreachable, as `code()` will be `None` if `signal()` is `Some` // according to the docs for `ExitStatus::code`. debug_assert!( false, "ExitStatus cannot have both a code ({code}) and a signal ({signal})" ); Self::Signaled { signal, core_dumped: status.core_dumped(), } } } } } #[cfg(not(unix))] impl From<process::ExitStatus> for ExitStatus { fn from(status: process::ExitStatus) -> Self { let code = status.code(); debug_assert!( code.is_some(), "`ExitStatus::code` cannot return `None` on windows" ); Self::Exited(code.unwrap_or(-1)) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-system/src/freebsd.rs
crates/nu-system/src/freebsd.rs
use itertools::{EitherOrBoth, Itertools}; use libc::{ CTL_HW, CTL_KERN, KERN_PROC, KERN_PROC_ALL, KERN_PROC_ARGS, TDF_IDLETD, c_char, kinfo_proc, sysctl, }; use std::{ ffi::CStr, io, mem::{self, MaybeUninit}, ptr, time::{Duration, Instant}, }; #[derive(Debug)] pub struct ProcessInfo { pub pid: i32, pub ppid: i32, pub name: String, pub argv: Vec<u8>, pub stat: c_char, pub percent_cpu: f64, pub mem_resident: u64, // in bytes pub mem_virtual: u64, // in bytes } pub fn collect_proc(interval: Duration, _with_thread: bool) -> Vec<ProcessInfo> { compare_procs(interval).unwrap_or_else(|err| { log::warn!("Failed to get processes: {}", err); vec![] }) } fn compare_procs(interval: Duration) -> io::Result<Vec<ProcessInfo>> { let pagesize = get_pagesize()? as u64; // Compare two full snapshots of all of the processes over the interval let now = Instant::now(); let procs_a = get_procs()?; std::thread::sleep(interval); let procs_b = get_procs()?; let true_interval = Instant::now().saturating_duration_since(now); let true_interval_sec = true_interval.as_secs_f64(); // Group all of the threads in each process together let a_grouped = procs_a.into_iter().group_by(|proc| proc.ki_pid); let b_grouped = procs_b.into_iter().group_by(|proc| proc.ki_pid); // Join the processes between the two snapshots Ok(a_grouped .into_iter() .merge_join_by(b_grouped.into_iter(), |(pid_a, _), (pid_b, _)| { pid_a.cmp(pid_b) }) .map(|threads| { // Join the threads between the two snapshots for the process let mut threads = { let (left, right) = threads.left_and_right(); left.into_iter() .flat_map(|(_, threads)| threads) .merge_join_by( right.into_iter().flat_map(|(_, threads)| threads), |thread_a, thread_b| thread_a.ki_tid.cmp(&thread_b.ki_tid), ) .peekable() }; // Pick the later process entry of the first thread to use for basic process information let proc = match threads.peek().ok_or(io::ErrorKind::NotFound)? { EitherOrBoth::Both(_, b) => b, EitherOrBoth::Left(a) => a, EitherOrBoth::Right(b) => b, } .clone(); // Skip over the idle process. It always appears with high CPU usage when the // system is idle if proc.ki_tdflags as u64 & TDF_IDLETD as u64 != 0 { return Err(io::ErrorKind::NotFound.into()); } // Aggregate all of the threads that exist in both snapshots and sum their runtime. let (runtime_a, runtime_b) = threads .flat_map(|t| t.both()) .fold((0., 0.), |(runtime_a, runtime_b), (a, b)| { let runtime_in_seconds = |proc: &kinfo_proc| proc.ki_runtime as f64 /* µsec */ / 1_000_000.0; ( runtime_a + runtime_in_seconds(&a), runtime_b + runtime_in_seconds(&b), ) }); // The percentage CPU is the ratio of how much runtime occurred for the process out of // the true measured interval that occurred. let percent_cpu = 100. * (runtime_b - runtime_a).max(0.) / true_interval_sec; let info = ProcessInfo { pid: proc.ki_pid, ppid: proc.ki_ppid, name: read_cstr(&proc.ki_comm).to_string_lossy().into_owned(), argv: get_proc_args(proc.ki_pid)?, stat: proc.ki_stat, percent_cpu, mem_resident: proc.ki_rssize.max(0) as u64 * pagesize, mem_virtual: proc.ki_size.max(0) as u64, }; Ok(info) }) // Remove errors from the list - probably just processes that are gone now .flat_map(|result: io::Result<_>| result.ok()) .collect()) } fn check(err: libc::c_int) -> std::io::Result<()> { if err < 0 { Err(io::Error::last_os_error()) } else { Ok(()) } } /// This is a bounds-checked way to read a `CStr` from a slice of `c_char` fn read_cstr(slice: &[libc::c_char]) -> &CStr { unsafe { // SAFETY: ensure that c_char and u8 are the same size mem::transmute::<libc::c_char, u8>(0); let slice: &[u8] = mem::transmute(slice); CStr::from_bytes_until_nul(slice).unwrap_or_default() } } fn get_procs() -> io::Result<Vec<libc::kinfo_proc>> { // To understand what's going on here, see the sysctl(3) manpage for FreeBSD. unsafe { const STRUCT_SIZE: usize = mem::size_of::<libc::kinfo_proc>(); let ctl_name = [CTL_KERN, KERN_PROC, KERN_PROC_ALL]; // First, try to figure out how large a buffer we need to allocate // (calling with NULL just tells us that) let mut data_len = 0; check(sysctl( ctl_name.as_ptr(), ctl_name.len() as u32, ptr::null_mut(), &mut data_len, ptr::null(), 0, ))?; // data_len will be set in bytes, so divide by the size of the structure let expected_len = data_len.div_ceil(STRUCT_SIZE); // Now allocate the Vec and set data_len to the real number of bytes allocated let mut vec: Vec<libc::kinfo_proc> = Vec::with_capacity(expected_len); data_len = vec.capacity() * STRUCT_SIZE; // Call sysctl() again to put the result in the vec check(sysctl( ctl_name.as_ptr(), ctl_name.len() as u32, vec.as_mut_ptr() as *mut libc::c_void, &mut data_len, ptr::null(), 0, ))?; // If that was ok, we can set the actual length of the vec to whatever // data_len was changed to, since that should now all be properly initialized data. let true_len = data_len.div_ceil(STRUCT_SIZE); vec.set_len(true_len); // Sort the procs by pid and then tid before using them vec.sort_by_key(|p| (p.ki_pid, p.ki_tid)); Ok(vec) } } fn get_proc_args(pid: i32) -> io::Result<Vec<u8>> { unsafe { let ctl_name = [CTL_KERN, KERN_PROC, KERN_PROC_ARGS, pid]; // First, try to figure out how large a buffer we need to allocate // (calling with NULL just tells us that) let mut data_len = 0; check(sysctl( ctl_name.as_ptr(), ctl_name.len() as u32, ptr::null_mut(), &mut data_len, ptr::null(), 0, ))?; // Now allocate the Vec and set data_len to the real number of bytes allocated let mut vec: Vec<u8> = Vec::with_capacity(data_len); data_len = vec.capacity(); // Call sysctl() again to put the result in the vec check(sysctl( ctl_name.as_ptr(), ctl_name.len() as u32, vec.as_mut_ptr() as *mut libc::c_void, &mut data_len, ptr::null(), 0, ))?; // If that was ok, we can set the actual length of the vec to whatever // data_len was changed to, since that should now all be properly initialized data. vec.set_len(data_len); Ok(vec) } } /// For getting simple values from the sysctl interface /// /// # Safety /// `T` needs to be of the structure that is expected to be returned by `sysctl` for the given /// `ctl_name` sequence and will then be assumed to be of correct layout. /// Thus only use it for primitive types or well defined fixed size types. For variable length /// arrays that can be returned from `sysctl` use it directly (or write a proper wrapper handling /// capacity management) /// /// # Panics /// If the size of the returned data diverges from the size of the expected `T` unsafe fn get_ctl<T>(ctl_name: &[i32]) -> io::Result<T> { let mut value: MaybeUninit<T> = MaybeUninit::uninit(); let mut value_len = mem::size_of_val(&value); // SAFETY: lengths to the pointers is provided, uninitialized data with checked length provided // Only assume initialized when the written data doesn't diverge in length, layout is the // safety responsibility of the caller. check(unsafe { sysctl( ctl_name.as_ptr(), ctl_name.len() as u32, value.as_mut_ptr() as *mut libc::c_void, &mut value_len, ptr::null(), 0, ) })?; assert_eq!( value_len, mem::size_of_val(&value), "Data requested from from `sysctl` diverged in size from the expected return type. For variable length data you need to manually truncate the data to the valid returned size!" ); Ok(unsafe { value.assume_init() }) } fn get_pagesize() -> io::Result<libc::c_int> { // not in libc for some reason const HW_PAGESIZE: i32 = 7; unsafe { get_ctl(&[CTL_HW, HW_PAGESIZE]) } } impl ProcessInfo { /// PID of process pub fn pid(&self) -> i32 { self.pid } /// Parent PID of process pub fn ppid(&self) -> i32 { self.ppid } /// Name of command pub fn name(&self) -> String { let argv_name = self .argv .split(|b| *b == 0) .next() .map(String::from_utf8_lossy) .unwrap_or_default() .into_owned(); if !argv_name.is_empty() { argv_name } else { // Just use the command name alone. self.name.clone() } } /// Full name of command, with arguments pub fn command(&self) -> String { if let Some(last_nul) = self.argv.iter().rposition(|b| *b == 0) { // The command string is NUL separated // Take the string up to the last NUL, then replace the NULs with spaces String::from_utf8_lossy(&self.argv[0..last_nul]).replace("\0", " ") } else { // The argv is empty, so use the name instead self.name() } } /// Get the status of the process pub fn status(&self) -> String { match self.stat { libc::SIDL | libc::SRUN => "Running", libc::SSLEEP => "Sleeping", libc::SSTOP => "Stopped", libc::SWAIT => "Waiting", libc::SLOCK => "Locked", libc::SZOMB => "Zombie", _ => "Unknown", } .into() } /// CPU usage as a percent of total pub fn cpu_usage(&self) -> f64 { self.percent_cpu } /// Memory size in number of bytes pub fn mem_size(&self) -> u64 { self.mem_resident } /// Virtual memory size in bytes pub fn virtual_size(&self) -> u64 { self.mem_virtual } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-system/src/os_info.rs
crates/nu-system/src/os_info.rs
pub fn get_os_name() -> &'static str { std::env::consts::OS } pub fn get_os_arch() -> &'static str { std::env::consts::ARCH } pub fn get_os_family() -> &'static str { std::env::consts::FAMILY } pub fn get_kernel_version() -> String { match sysinfo::System::kernel_version() { Some(v) => v, None => "unknown".to_string(), } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-system/examples/sys_demo.rs
crates/nu-system/examples/sys_demo.rs
fn main() { #[cfg(any( target_os = "android", target_os = "linux", target_os = "macos", target_os = "windows" ))] { let cores = std::thread::available_parallelism() .map(|p| p.get()) .unwrap_or(1); for run in 1..=10 { for proc in nu_system::collect_proc(std::time::Duration::from_millis(100), false) { if proc.cpu_usage() > 0.00001 { println!( "{} - {} - {} - {} - {:.2}% - {}M - {}M - {} procs", run, proc.pid(), proc.name(), proc.status(), proc.cpu_usage() / cores as f64, proc.mem_size() / (1024 * 1024), proc.virtual_size() / (1024 * 1024), cores, ) } } std::thread::sleep(std::time::Duration::from_millis(1000)); } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-table/src/lib.rs
crates/nu-table/src/lib.rs
#![doc = include_str!("../README.md")] mod table; mod table_theme; mod types; mod unstructured_table; mod util; pub mod common; pub use common::{StringResult, TableResult}; pub use nu_color_config::TextStyle; pub use table::{NuRecords, NuRecordsValue, NuTable}; pub use table_theme::TableTheme; pub use types::{CollapsedTable, ExpandedTable, JustTable, TableOpts, TableOutput}; pub use unstructured_table::UnstructuredTable; pub use util::*;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-table/src/unstructured_table.rs
crates/nu-table/src/unstructured_table.rs
use nu_color_config::StyleComputer; use nu_protocol::{Config, Record, Span, TableIndent, Value}; use tabled::{ grid::{ ansi::ANSIStr, config::{Borders, CompactMultilineConfig}, dimension::{DimensionPriority, PoolTableDimension}, }, settings::{Alignment, Color, Padding, TableOption}, tables::{PoolTable, TableValue}, }; use crate::{TableTheme, is_color_empty, string_width, string_wrap}; /// UnstructuredTable has a recursive table representation of nu_protocol::Value. /// /// It doesn't support alignment and a proper width control (although it's possible to achieve). pub struct UnstructuredTable { value: TableValue, } impl UnstructuredTable { pub fn new(value: Value, config: &Config) -> Self { let value = convert_nu_value_to_table_value(value, config); Self { value } } pub fn truncate(&mut self, theme: &TableTheme, width: usize) -> bool { let mut available = width; let has_vertical = theme.as_full().borders_has_left(); if has_vertical { available = available.saturating_sub(2); } truncate_table_value(&mut self.value, has_vertical, available).is_none() } pub fn draw(self, theme: &TableTheme, indent: TableIndent, style: &StyleComputer) -> String { build_table(self.value, style, theme, indent) } } fn build_table( val: TableValue, style: &StyleComputer, theme: &TableTheme, indent: TableIndent, ) -> String { let mut table = PoolTable::from(val); let mut theme = theme.as_full().clone(); theme.set_horizontal_lines(Default::default()); table.with(Padding::new(indent.left, indent.right, 0, 0)); table.with(*theme.get_borders()); table.with(Alignment::left()); table.with(PoolTableDimension::new( DimensionPriority::Last, DimensionPriority::Last, )); if let Some(color) = get_border_color(style) && !is_color_empty(&color) { return build_table_with_border_color(table, color); } table.to_string() } fn convert_nu_value_to_table_value(value: Value, config: &Config) -> TableValue { match value { Value::Record { val, .. } => build_vertical_map(val.into_owned(), config), Value::List { vals, .. } => { let rebuild_array_as_map = is_valid_record(&vals) && count_columns_in_record(&vals) > 0; if rebuild_array_as_map { build_map_from_record(vals, config) } else { build_vertical_array(vals, config) } } value => build_string_value(value, config), } } fn build_string_value(value: Value, config: &Config) -> TableValue { const MAX_STRING_WIDTH: usize = 50; const WRAP_STRING_WIDTH: usize = 30; let mut text = value.to_abbreviated_string(config); if string_width(&text) > MAX_STRING_WIDTH { text = string_wrap(&text, WRAP_STRING_WIDTH, false); } TableValue::Cell(text) } fn build_vertical_map(record: Record, config: &Config) -> TableValue { let max_key_width = record .iter() .map(|(k, _)| string_width(k)) .max() .unwrap_or(0); let mut rows = Vec::with_capacity(record.len()); for (mut key, value) in record { string_append_to_width(&mut key, max_key_width); let value = convert_nu_value_to_table_value(value, config); let row = TableValue::Row(vec![TableValue::Cell(key), value]); rows.push(row); } TableValue::Column(rows) } fn string_append_to_width(key: &mut String, max: usize) { let width = string_width(key); let rest = max - width; key.extend(std::iter::repeat_n(' ', rest)); } fn build_vertical_array(vals: Vec<Value>, config: &Config) -> TableValue { let map = vals .into_iter() .map(|val| convert_nu_value_to_table_value(val, config)) .collect(); TableValue::Column(map) } fn is_valid_record(vals: &[Value]) -> bool { if vals.is_empty() { return true; } let first_value = match &vals[0] { Value::Record { val, .. } => val, _ => return false, }; for val in &vals[1..] { match val { Value::Record { val, .. } => { let equal = val.columns().eq(first_value.columns()); if !equal { return false; } } _ => return false, } } true } fn count_columns_in_record(vals: &[Value]) -> usize { match vals.iter().next() { Some(Value::Record { val, .. }) => val.len(), _ => 0, } } fn build_map_from_record(vals: Vec<Value>, config: &Config) -> TableValue { // assumes that we have a valid record structure (checked by is_valid_record) let head = get_columns_in_record(&vals); let mut list = Vec::with_capacity(head.len()); for col in head { list.push(TableValue::Column(vec![TableValue::Cell(col)])); } for val in vals { let val = get_as_record(val); for (i, (_, val)) in val.into_owned().into_iter().enumerate() { let value = convert_nu_value_to_table_value(val, config); let list = get_table_value_column_mut(&mut list[i]); list.push(value); } } TableValue::Row(list) } fn get_table_value_column_mut(val: &mut TableValue) -> &mut Vec<TableValue> { match val { TableValue::Column(row) => row, _ => { unreachable!(); } } } fn get_as_record(val: Value) -> nu_utils::SharedCow<Record> { match val { Value::Record { val, .. } => val, _ => unreachable!(), } } fn get_columns_in_record(vals: &[Value]) -> Vec<String> { match vals.iter().next() { Some(Value::Record { val, .. }) => val.columns().cloned().collect(), _ => vec![], } } fn truncate_table_value( value: &mut TableValue, has_vertical: bool, available: usize, ) -> Option<usize> { const MIN_CONTENT_WIDTH: usize = 10; const TRUNCATE_CELL_WIDTH: usize = 3; const PAD: usize = 2; match value { TableValue::Row(row) => { if row.is_empty() { return Some(PAD); } if row.len() == 1 { return truncate_table_value(&mut row[0], has_vertical, available); } let count_cells = row.len(); let mut row_width = 0; let mut i = 0; let mut last_used_width = 0; for cell in row.iter_mut() { let vertical = (has_vertical && i + 1 != count_cells) as usize; if available < row_width + vertical { break; } let available = available - row_width - vertical; let width = match truncate_table_value(cell, has_vertical, available) { Some(width) => width, None => break, }; row_width += width + vertical; last_used_width = row_width; i += 1; } if i == row.len() { return Some(row_width); } if i == 0 { if available >= PAD + TRUNCATE_CELL_WIDTH { *value = TableValue::Cell(String::from("...")); return Some(PAD + TRUNCATE_CELL_WIDTH); } else { return None; } } let available = available - row_width; let has_space_empty_cell = available >= PAD + TRUNCATE_CELL_WIDTH; if has_space_empty_cell { row[i] = TableValue::Cell(String::from("...")); row.truncate(i + 1); row_width += PAD + TRUNCATE_CELL_WIDTH; } else if i == 0 { return None; } else { row[i - 1] = TableValue::Cell(String::from("...")); row.truncate(i); row_width -= last_used_width; row_width += PAD + TRUNCATE_CELL_WIDTH; } Some(row_width) } TableValue::Column(column) => { let mut max_width = PAD; for cell in column.iter_mut() { let width = truncate_table_value(cell, has_vertical, available)?; max_width = std::cmp::max(max_width, width); } Some(max_width) } TableValue::Cell(text) => { if available <= PAD { return None; } let available = available - PAD; let width = string_width(text); if width > available { if available > MIN_CONTENT_WIDTH { *text = string_wrap(text, available, false); Some(available + PAD) } else if available >= 3 { *text = String::from("..."); Some(3 + PAD) } else { // situation where we have too little space None } } else { Some(width + PAD) } } } } fn build_table_with_border_color(mut table: PoolTable, color: Color) -> String { // NOTE: We have this function presizely because of color_into_ansistr internals // color must be alive why we build table let color = color_into_ansistr(&color); table.with(SetBorderColor(color)); table.to_string() } fn color_into_ansistr(color: &Color) -> ANSIStr<'static> { // # SAFETY // // It's perfectly save to do cause table does not store the reference internally. // We just need this unsafe section to cope with some limitations of [`PoolTable`]. // Mitigation of this is definitely on a todo list. let prefix = color.get_prefix(); let suffix = color.get_suffix(); let prefix: &'static str = unsafe { std::mem::transmute(prefix) }; let suffix: &'static str = unsafe { std::mem::transmute(suffix) }; ANSIStr::new(prefix, suffix) } struct SetBorderColor(ANSIStr<'static>); impl<R, D> TableOption<R, CompactMultilineConfig, D> for SetBorderColor { fn change(self, _: &mut R, cfg: &mut CompactMultilineConfig, _: &mut D) { let borders = Borders::filled(self.0); cfg.set_borders_color(borders); } } fn get_border_color(style: &StyleComputer<'_>) -> Option<Color> { // color_config closures for "separator" are just given a null. let color = style.compute("separator", &Value::nothing(Span::unknown())); let color = color.paint(" ").to_string(); let color = Color::try_from(color); color.ok() }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-table/src/table.rs
crates/nu-table/src/table.rs
// TODO: Stop building `tabled -e` when it's clear we are out of terminal // TODO: Stop building `tabled` when it's clear we are out of terminal // NOTE: TODO the above we could expose something like [`WidthCtrl`] in which case we could also laverage the width list build right away. // currently it seems like we do recacalculate it for `table -e`? // TODO: (not hard) We could properly handle dimension - we already do it for width - just need to do height as well // TODO: (need to check) Maybe Vec::with_dimension and insert "Iterators" would be better instead of preallocated Vec<Vec<>> and index. use std::cmp::{max, min}; use nu_ansi_term::Style; use nu_color_config::TextStyle; use nu_protocol::{TableIndent, TrimStrategy}; use tabled::{ Table, builder::Builder, grid::{ ansi::ANSIBuf, config::{ AlignmentHorizontal, ColoredConfig, Entity, Indent, Position, Sides, SpannedConfig, }, dimension::{CompleteDimension, PeekableGridDimension}, records::{ IterRecords, PeekableRecords, vec_records::{Cell, Text, VecRecords}, }, }, settings::{ Alignment, CellOption, Color, Padding, TableOption, Width, formatting::AlignmentStrategy, object::{Columns, Rows}, themes::ColumnNames, width::Truncate, }, }; use crate::{convert_style, is_color_empty, table_theme::TableTheme}; const EMPTY_COLUMN_TEXT: &str = "..."; const EMPTY_COLUMN_TEXT_WIDTH: usize = 3; pub type NuRecords = VecRecords<NuRecordsValue>; pub type NuRecordsValue = Text<String>; /// NuTable is a table rendering implementation. #[derive(Debug, Clone)] pub struct NuTable { data: Vec<Vec<NuRecordsValue>>, widths: Vec<usize>, heights: Vec<usize>, count_rows: usize, count_cols: usize, styles: Styles, config: TableConfig, } impl NuTable { /// Creates an empty [`NuTable`] instance. pub fn new(count_rows: usize, count_cols: usize) -> Self { Self { data: vec![vec![Text::default(); count_cols]; count_rows], widths: vec![2; count_cols], heights: vec![0; count_rows], count_rows, count_cols, styles: Styles { cfg: ColoredConfig::default(), alignments: CellConfiguration { data: AlignmentHorizontal::Left, index: AlignmentHorizontal::Right, header: AlignmentHorizontal::Center, }, colors: CellConfiguration::default(), }, config: TableConfig { theme: TableTheme::basic(), trim: TrimStrategy::truncate(None), structure: TableStructure::new(false, false, false), indent: TableIndent::new(1, 1), header_on_border: false, expand: false, border_color: None, }, } } /// Return amount of rows. pub fn count_rows(&self) -> usize { self.count_rows } /// Return amount of columns. pub fn count_columns(&self) -> usize { self.count_cols } pub fn create(text: String) -> NuRecordsValue { Text::new(text) } pub fn insert_value(&mut self, pos: (usize, usize), value: NuRecordsValue) { let width = value.width() + indent_sum(self.config.indent); let height = value.count_lines(); self.widths[pos.1] = max(self.widths[pos.1], width); self.heights[pos.0] = max(self.heights[pos.0], height); self.data[pos.0][pos.1] = value; } pub fn insert(&mut self, pos: (usize, usize), text: String) { let text = Text::new(text); let pad = indent_sum(self.config.indent); let width = text.width() + pad; let height = text.count_lines(); self.widths[pos.1] = max(self.widths[pos.1], width); self.heights[pos.0] = max(self.heights[pos.0], height); self.data[pos.0][pos.1] = text; } pub fn set_row(&mut self, index: usize, row: Vec<NuRecordsValue>) { assert_eq!(self.data[index].len(), row.len()); for (i, text) in row.iter().enumerate() { let pad = indent_sum(self.config.indent); let width = text.width() + pad; let height = text.count_lines(); self.widths[i] = max(self.widths[i], width); self.heights[index] = max(self.heights[index], height); } self.data[index] = row; } pub fn pop_column(&mut self, count: usize) { self.count_cols -= count; self.widths.truncate(self.count_cols); for (row, height) in self.data.iter_mut().zip(self.heights.iter_mut()) { row.truncate(self.count_cols); let row_height = *height; let mut new_height = 0; for cell in row.iter() { let height = cell.count_lines(); if height == row_height { new_height = height; break; } new_height = max(new_height, height); } *height = new_height; } // set to default styles of the popped columns for i in 0..count { let col = self.count_cols + i; for row in 0..self.count_rows { self.styles .cfg .set_alignment_horizontal(Entity::Cell(row, col), self.styles.alignments.data); self.styles .cfg .set_color(Entity::Cell(row, col), ANSIBuf::default()); } } } pub fn push_column(&mut self, text: String) { let value = Text::new(text); let pad = indent_sum(self.config.indent); let width = value.width() + pad; let height = value.count_lines(); self.widths.push(width); for row in 0..self.count_rows { self.heights[row] = max(self.heights[row], height); } for row in &mut self.data[..] { row.push(value.clone()); } self.count_cols += 1; } pub fn insert_style(&mut self, pos: (usize, usize), style: TextStyle) { if let Some(style) = style.color_style && !style.is_plain() { let style = convert_style(style); self.styles.cfg.set_color(pos.into(), style.into()); } let alignment = convert_alignment(style.alignment); if alignment != self.styles.alignments.data { self.styles .cfg .set_alignment_horizontal(pos.into(), alignment); } } pub fn set_header_style(&mut self, style: TextStyle) { if let Some(style) = style.color_style && !style.is_plain() { let style = convert_style(style); self.styles.colors.header = style; } self.styles.alignments.header = convert_alignment(style.alignment); } pub fn set_index_style(&mut self, style: TextStyle) { if let Some(style) = style.color_style && !style.is_plain() { let style = convert_style(style); self.styles.colors.index = style; } self.styles.alignments.index = convert_alignment(style.alignment); } pub fn set_data_style(&mut self, style: TextStyle) { if let Some(style) = style.color_style && !style.is_plain() { let style = convert_style(style); self.styles.cfg.set_color(Entity::Global, style.into()); } let alignment = convert_alignment(style.alignment); self.styles .cfg .set_alignment_horizontal(Entity::Global, alignment); self.styles.alignments.data = alignment; } // NOTE: Crusial to be called before data changes (todo fix interface) pub fn set_indent(&mut self, indent: TableIndent) { self.config.indent = indent; let pad = indent_sum(indent); for w in &mut self.widths { *w = pad; } } pub fn set_theme(&mut self, theme: TableTheme) { self.config.theme = theme; } pub fn set_structure(&mut self, index: bool, header: bool, footer: bool) { self.config.structure = TableStructure::new(index, header, footer); } pub fn set_border_header(&mut self, on: bool) { self.config.header_on_border = on; } pub fn set_trim(&mut self, strategy: TrimStrategy) { self.config.trim = strategy; } pub fn set_strategy(&mut self, expand: bool) { self.config.expand = expand; } pub fn set_border_color(&mut self, color: Style) { self.config.border_color = (!color.is_plain()).then_some(color); } pub fn clear_border_color(&mut self) { self.config.border_color = None; } // NOTE: BE CAREFUL TO KEEP WIDTH UNCHANGED // TODO: fix interface pub fn get_records_mut(&mut self) -> &mut [Vec<NuRecordsValue>] { &mut self.data } pub fn clear_all_colors(&mut self) { self.clear_border_color(); let cfg = std::mem::take(&mut self.styles.cfg); self.styles.cfg = ColoredConfig::new(cfg.into_inner()); } /// Converts a table to a String. /// /// It returns None in case where table cannot be fit to a terminal width. pub fn draw(self, termwidth: usize) -> Option<String> { build_table(self, termwidth) } /// Converts a table to a String. /// /// It returns None in case where table cannot be fit to a terminal width. pub fn draw_unchecked(self, termwidth: usize) -> Option<String> { build_table_unchecked(self, termwidth) } /// Return a total table width. pub fn total_width(&self) -> usize { let config = create_config(&self.config.theme, false, None); get_total_width2(&self.widths, &config) } } // NOTE: Must never be called from nu-table - made only for tests // FIXME: remove it? // #[cfg(test)] impl From<Vec<Vec<Text<String>>>> for NuTable { fn from(value: Vec<Vec<Text<String>>>) -> Self { let count_rows = value.len(); let count_cols = if value.is_empty() { 0 } else { value[0].len() }; let mut t = Self::new(count_rows, count_cols); for (i, row) in value.into_iter().enumerate() { t.set_row(i, row); } table_recalculate_widths(&mut t); t } } fn table_recalculate_widths(t: &mut NuTable) { let pad = indent_sum(t.config.indent); t.widths = build_width(&t.data, t.count_cols, t.count_rows, pad); } #[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Copy, Hash)] struct CellConfiguration<Value> { index: Value, header: Value, data: Value, } #[derive(Debug, Clone, PartialEq, Eq)] struct Styles { cfg: ColoredConfig, colors: CellConfiguration<Color>, alignments: CellConfiguration<AlignmentHorizontal>, } #[derive(Debug, Clone)] pub struct TableConfig { theme: TableTheme, trim: TrimStrategy, border_color: Option<Style>, expand: bool, structure: TableStructure, header_on_border: bool, indent: TableIndent, } #[derive(Debug, Clone, Copy)] struct TableStructure { with_index: bool, with_header: bool, with_footer: bool, } impl TableStructure { fn new(with_index: bool, with_header: bool, with_footer: bool) -> Self { Self { with_index, with_header, with_footer, } } } #[derive(Debug, Clone)] struct HeadInfo { values: Vec<String>, align: AlignmentHorizontal, #[allow(dead_code)] align_index: AlignmentHorizontal, color: Option<Color>, } impl HeadInfo { fn new( values: Vec<String>, align: AlignmentHorizontal, align_index: AlignmentHorizontal, color: Option<Color>, ) -> Self { Self { values, align, align_index, color, } } } fn build_table_unchecked(mut t: NuTable, termwidth: usize) -> Option<String> { if t.count_columns() == 0 || t.count_rows() == 0 { return Some(String::new()); } let widths = std::mem::take(&mut t.widths); let config = create_config(&t.config.theme, false, None); let totalwidth = get_total_width2(&t.widths, &config); let widths = WidthEstimation::new(widths.clone(), widths, totalwidth, false, false); let head = remove_header_if(&mut t); table_insert_footer_if(&mut t); draw_table(t, widths, head, termwidth) } fn build_table(mut t: NuTable, termwidth: usize) -> Option<String> { if t.count_columns() == 0 || t.count_rows() == 0 { return Some(String::new()); } let widths = table_truncate(&mut t, termwidth)?; let head = remove_header_if(&mut t); table_insert_footer_if(&mut t); draw_table(t, widths, head, termwidth) } fn remove_header_if(t: &mut NuTable) -> Option<HeadInfo> { if !is_header_on_border(t) { return None; } let head = remove_header(t); t.config.structure.with_header = false; Some(head) } fn is_header_on_border(t: &NuTable) -> bool { let is_configured = t.config.structure.with_header && t.config.header_on_border; let has_horizontal = t.config.theme.as_base().borders_has_top() || t.config.theme.as_base().get_horizontal_line(1).is_some(); is_configured && has_horizontal } fn table_insert_footer_if(t: &mut NuTable) { let with_footer = t.config.structure.with_header && t.config.structure.with_footer; if !with_footer { return; } duplicate_row(&mut t.data, 0); if !t.heights.is_empty() { t.heights.push(t.heights[0]); } } fn table_truncate(t: &mut NuTable, termwidth: usize) -> Option<WidthEstimation> { let widths = maybe_truncate_columns(&mut t.data, t.widths.clone(), &t.config, termwidth); if widths.needed.is_empty() { return None; } // reset style for last column which is a trail one if widths.trail { let col = widths.needed.len() - 1; for row in 0..t.count_rows { t.styles .cfg .set_alignment_horizontal(Entity::Cell(row, col), t.styles.alignments.data); t.styles .cfg .set_color(Entity::Cell(row, col), ANSIBuf::default()); } } Some(widths) } fn remove_header(t: &mut NuTable) -> HeadInfo { // move settings by one row down for row in 1..t.data.len() { for col in 0..t.count_cols { let from = Position::new(row, col); let to = Position::new(row - 1, col); let alignment = *t.styles.cfg.get_alignment_horizontal(from); if alignment != t.styles.alignments.data { t.styles.cfg.set_alignment_horizontal(to.into(), alignment); } let color = t.styles.cfg.get_color(from); if let Some(color) = color && !color.is_empty() { let color = color.clone(); t.styles.cfg.set_color(to.into(), color); } } } let head = t .data .remove(0) .into_iter() .map(|s| s.to_string()) .collect(); // drop height row t.heights.remove(0); // WE NEED TO RELCULATE WIDTH. // TODO: cause we have configuration beforehand we can just not calculate it in? // Why we do it exactly?? table_recalculate_widths(t); let color = get_color_if_exists(&t.styles.colors.header); let alignment = t.styles.alignments.header; let alignment_index = if t.config.structure.with_index { t.styles.alignments.index } else { t.styles.alignments.header }; t.styles.alignments.header = AlignmentHorizontal::Center; t.styles.colors.header = Color::empty(); HeadInfo::new(head, alignment, alignment_index, color) } fn draw_table( t: NuTable, width: WidthEstimation, head: Option<HeadInfo>, termwidth: usize, ) -> Option<String> { let mut structure = t.config.structure; structure.with_footer = structure.with_footer && head.is_none(); let sep_color = t.config.border_color; let data = t.data; let mut table = Builder::from_vec(data).build(); set_styles(&mut table, t.styles, &structure); set_indent(&mut table, t.config.indent); load_theme(&mut table, &t.config.theme, &structure, sep_color); truncate_table(&mut table, &t.config, width, termwidth, t.heights); table_set_border_header(&mut table, head, &t.config); let string = table.to_string(); Some(string) } fn set_styles(table: &mut Table, styles: Styles, structure: &TableStructure) { table.with(styles.cfg); align_table(table, styles.alignments, structure); colorize_table(table, styles.colors, structure); } fn table_set_border_header(table: &mut Table, head: Option<HeadInfo>, cfg: &TableConfig) { let head = match head { Some(head) => head, None => return, }; let theme = &cfg.theme; let with_footer = cfg.structure.with_footer; if !theme.as_base().borders_has_top() { let line = theme.as_base().get_horizontal_line(1); if let Some(line) = line.cloned() { table.get_config_mut().insert_horizontal_line(0, line); if with_footer { let last_row = table.count_rows(); table .get_config_mut() .insert_horizontal_line(last_row, line); } }; } // todo: Move logic to SetLineHeaders - so it be faster - cleaner if with_footer { let last_row = table.count_rows(); table.with(SetLineHeaders::new(head.clone(), last_row, cfg.indent)); } table.with(SetLineHeaders::new(head, 0, cfg.indent)); } fn truncate_table( table: &mut Table, cfg: &TableConfig, width: WidthEstimation, termwidth: usize, heights: Vec<usize>, ) { let trim = cfg.trim.clone(); let pad = indent_sum(cfg.indent); let ctrl = DimensionCtrl::new(termwidth, width, trim, cfg.expand, pad, heights); table.with(ctrl); } fn indent_sum(indent: TableIndent) -> usize { indent.left + indent.right } fn set_indent(table: &mut Table, indent: TableIndent) { table.with(Padding::new(indent.left, indent.right, 0, 0)); } struct DimensionCtrl { width: WidthEstimation, trim_strategy: TrimStrategy, max_width: usize, expand: bool, pad: usize, heights: Vec<usize>, } impl DimensionCtrl { fn new( max_width: usize, width: WidthEstimation, trim_strategy: TrimStrategy, expand: bool, pad: usize, heights: Vec<usize>, ) -> Self { Self { width, trim_strategy, max_width, expand, pad, heights, } } } #[derive(Debug, Clone)] struct WidthEstimation { original: Vec<usize>, needed: Vec<usize>, #[allow(dead_code)] total: usize, truncate: bool, trail: bool, } impl WidthEstimation { fn new( original: Vec<usize>, needed: Vec<usize>, total: usize, truncate: bool, trail: bool, ) -> Self { Self { original, needed, total, truncate, trail, } } } impl TableOption<NuRecords, ColoredConfig, CompleteDimension> for DimensionCtrl { fn change(self, recs: &mut NuRecords, cfg: &mut ColoredConfig, dims: &mut CompleteDimension) { if self.width.truncate { width_ctrl_truncate(self, recs, cfg, dims); return; } if self.expand { width_ctrl_expand(self, recs, cfg, dims); return; } // NOTE: just an optimization; to not recalculate it internally dims.set_heights(self.heights); dims.set_widths(self.width.needed); } fn hint_change(&self) -> Option<Entity> { // NOTE: // Because we are assuming that: // len(lines(wrapped(string))) >= len(lines(string)) // // Only truncation case must be relaclucated in term of height. if self.width.truncate && matches!(self.trim_strategy, TrimStrategy::Truncate { .. }) { Some(Entity::Row(0)) } else { None } } } fn width_ctrl_expand( ctrl: DimensionCtrl, recs: &mut NuRecords, cfg: &mut ColoredConfig, dims: &mut CompleteDimension, ) { dims.set_heights(ctrl.heights); let opt = Width::increase(ctrl.max_width); TableOption::<NuRecords, _, _>::change(opt, recs, cfg, dims); } fn width_ctrl_truncate( ctrl: DimensionCtrl, recs: &mut NuRecords, cfg: &mut ColoredConfig, dims: &mut CompleteDimension, ) { let mut heights = ctrl.heights; // todo: maybe general for loop better for (col, (&width, width_original)) in ctrl .width .needed .iter() .zip(ctrl.width.original) .enumerate() { if width == width_original { continue; } let width = width - ctrl.pad; match &ctrl.trim_strategy { TrimStrategy::Wrap { try_to_keep_words } => { let wrap = Width::wrap(width).keep_words(*try_to_keep_words); CellOption::<NuRecords, _>::change(wrap, recs, cfg, Entity::Column(col)); // NOTE: An optimization to have proper heights without going over all the data again. // We are going only for all rows in changed columns for (row, row_height) in heights.iter_mut().enumerate() { let height = recs.count_lines(Position::new(row, col)); *row_height = max(*row_height, height); } } TrimStrategy::Truncate { suffix } => { let mut truncate = Width::truncate(width); if let Some(suffix) = suffix { truncate = truncate.suffix(suffix).suffix_try_color(true); } CellOption::<NuRecords, _>::change(truncate, recs, cfg, Entity::Column(col)); } } } dims.set_heights(heights); dims.set_widths(ctrl.width.needed); } fn align_table( table: &mut Table, alignments: CellConfiguration<AlignmentHorizontal>, structure: &TableStructure, ) { table.with(AlignmentStrategy::PerLine); if structure.with_header { table.modify(Rows::first(), AlignmentStrategy::PerCell); table.modify(Rows::first(), Alignment::from(alignments.header)); if structure.with_footer { table.modify(Rows::last(), AlignmentStrategy::PerCell); table.modify(Rows::last(), Alignment::from(alignments.header)); } } if structure.with_index { table.modify(Columns::first(), Alignment::from(alignments.index)); } } fn colorize_table(table: &mut Table, styles: CellConfiguration<Color>, structure: &TableStructure) { if structure.with_index && !is_color_empty(&styles.index) { table.modify(Columns::first(), styles.index); } if structure.with_header && !is_color_empty(&styles.header) { table.modify(Rows::first(), styles.header.clone()); } if structure.with_header && structure.with_footer && !is_color_empty(&styles.header) { table.modify(Rows::last(), styles.header); } } fn load_theme( table: &mut Table, theme: &TableTheme, structure: &TableStructure, sep_color: Option<Style>, ) { let with_header = table.count_rows() > 1 && structure.with_header; let with_footer = with_header && structure.with_footer; let mut theme = theme.as_base().clone(); if !with_header { let borders = *theme.get_borders(); theme.remove_horizontal_lines(); theme.set_borders(borders); } else if with_footer { theme_copy_horizontal_line(&mut theme, 1, table.count_rows() - 1); } table.with(theme); if let Some(style) = sep_color { let color = convert_style(style); let color = ANSIBuf::from(color); table.get_config_mut().set_border_color_default(color); } } fn maybe_truncate_columns( data: &mut Vec<Vec<NuRecordsValue>>, widths: Vec<usize>, cfg: &TableConfig, termwidth: usize, ) -> WidthEstimation { const TERMWIDTH_THRESHOLD: usize = 120; let pad = cfg.indent.left + cfg.indent.right; let preserve_content = termwidth > TERMWIDTH_THRESHOLD; if preserve_content { truncate_columns_by_columns(data, widths, &cfg.theme, pad, termwidth) } else { truncate_columns_by_content(data, widths, &cfg.theme, pad, termwidth) } } // VERSION where we are showing AS LITTLE COLUMNS AS POSSIBLE but WITH AS MUCH CONTENT AS POSSIBLE. fn truncate_columns_by_content( data: &mut Vec<Vec<NuRecordsValue>>, widths: Vec<usize>, theme: &TableTheme, pad: usize, termwidth: usize, ) -> WidthEstimation { const MIN_ACCEPTABLE_WIDTH: usize = 5; const TRAILING_COLUMN_WIDTH: usize = EMPTY_COLUMN_TEXT_WIDTH; let trailing_column_width = TRAILING_COLUMN_WIDTH + pad; let min_column_width = MIN_ACCEPTABLE_WIDTH + pad; let count_columns = data[0].len(); let config = create_config(theme, false, None); let widths_original = widths; let mut widths = vec![]; let borders = config.get_borders(); let vertical = borders.has_vertical() as usize; let mut width = borders.has_left() as usize + borders.has_right() as usize; let mut truncate_pos = 0; for (i, &column_width) in widths_original.iter().enumerate() { let mut next_move = column_width; if i > 0 { next_move += vertical; } if width + next_move > termwidth { break; } widths.push(column_width); width += next_move; truncate_pos += 1; } if truncate_pos == count_columns { return WidthEstimation::new(widths_original, widths, width, false, false); } let is_last_column = truncate_pos + 1 == count_columns; if truncate_pos == 0 && !is_last_column { if termwidth > width { let available = termwidth - width; if available >= min_column_width + vertical + trailing_column_width { truncate_rows(data, 1); let first_col_width = available - (vertical + trailing_column_width); widths.push(first_col_width); width += first_col_width; push_empty_column(data); widths.push(trailing_column_width); width += trailing_column_width + vertical; return WidthEstimation::new(widths_original, widths, width, true, true); } } return WidthEstimation::new(widths_original, widths, width, false, false); } let available = termwidth - width; let can_fit_last_column = available >= min_column_width + vertical; if is_last_column && can_fit_last_column { let w = available - vertical; widths.push(w); width += w + vertical; return WidthEstimation::new(widths_original, widths, width, true, false); } // special case where the last column is smaller then a trailing column let is_almost_last_column = truncate_pos + 2 == count_columns; if is_almost_last_column { let next_column_width = widths_original[truncate_pos + 1]; let has_space_for_two_columns = available >= min_column_width + vertical + next_column_width + vertical; if !is_last_column && has_space_for_two_columns { let rest = available - vertical - next_column_width - vertical; widths.push(rest); width += rest + vertical; widths.push(next_column_width); width += next_column_width + vertical; return WidthEstimation::new(widths_original, widths, width, true, false); } } let has_space_for_two_columns = available >= min_column_width + vertical + trailing_column_width + vertical; if !is_last_column && has_space_for_two_columns { truncate_rows(data, truncate_pos + 1); let rest = available - vertical - trailing_column_width - vertical; widths.push(rest); width += rest + vertical; push_empty_column(data); widths.push(trailing_column_width); width += trailing_column_width + vertical; return WidthEstimation::new(widths_original, widths, width, true, true); } if available >= trailing_column_width + vertical { truncate_rows(data, truncate_pos); push_empty_column(data); widths.push(trailing_column_width); width += trailing_column_width + vertical; return WidthEstimation::new(widths_original, widths, width, false, true); } let last_width = widths.last().cloned().expect("ok"); let can_truncate_last = last_width > min_column_width; if can_truncate_last { let rest = last_width - min_column_width; let maybe_available = available + rest; if maybe_available >= trailing_column_width + vertical { truncate_rows(data, truncate_pos); let left = maybe_available - trailing_column_width - vertical; let new_last_width = min_column_width + left; widths[truncate_pos - 1] = new_last_width; width -= last_width; width += new_last_width; push_empty_column(data); widths.push(trailing_column_width); width += trailing_column_width + vertical; return WidthEstimation::new(widths_original, widths, width, true, true); } } truncate_rows(data, truncate_pos - 1); let w = widths.pop().expect("ok"); width -= w; push_empty_column(data); widths.push(trailing_column_width); width += trailing_column_width; let has_only_trail = widths.len() == 1; let is_enough_space = width <= termwidth; if has_only_trail || !is_enough_space { // nothing to show anyhow return WidthEstimation::new(widths_original, vec![], width, false, true); } WidthEstimation::new(widths_original, widths, width, false, true) } // VERSION where we are showing AS MANY COLUMNS AS POSSIBLE but as a side affect they MIGHT CONTAIN AS LITTLE CONTENT AS POSSIBLE // // TODO: Currently there's no prioritization of anything meaning all columns are equal // But I'd suggest to try to give a little more space for left most columns // // So for example for instead of columns [10, 10, 10] // We would get [15, 10, 5] // // Point being of the column needs more space we do can give it a little more based on it's distance from the start. // Percentage wise. fn truncate_columns_by_columns( data: &mut Vec<Vec<NuRecordsValue>>, widths: Vec<usize>, theme: &TableTheme, pad: usize, termwidth: usize, ) -> WidthEstimation { const MIN_ACCEPTABLE_WIDTH: usize = 10; const TRAILING_COLUMN_WIDTH: usize = EMPTY_COLUMN_TEXT_WIDTH; let trailing_column_width = TRAILING_COLUMN_WIDTH + pad; let min_column_width = MIN_ACCEPTABLE_WIDTH + pad; let count_columns = data[0].len(); let config = create_config(theme, false, None); let widths_original = widths; let mut widths = vec![]; let borders = config.get_borders(); let vertical = borders.has_vertical() as usize; let mut width = borders.has_left() as usize + borders.has_right() as usize; let mut truncate_pos = 0; for (i, &width_orig) in widths_original.iter().enumerate() { let use_width = min(min_column_width, width_orig); let mut next_move = use_width; if i > 0 { next_move += vertical; } if width + next_move > termwidth { break; } widths.push(use_width); width += next_move; truncate_pos += 1; } if truncate_pos == 0 { return WidthEstimation::new(widths_original, widths, width, false, false); } let mut available = termwidth - width; if available > 0 { for i in 0..truncate_pos { let used_width = widths[i]; let col_width = widths_original[i]; if used_width < col_width { let need = col_width - used_width; let take = min(available, need); available -= take; widths[i] += take; width += take; if available == 0 {
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
true
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-table/src/util.rs
crates/nu-table/src/util.rs
use nu_color_config::StyleComputer; use tabled::{ grid::{ ansi::{ANSIBuf, ANSIStr}, records::vec_records::Text, util::string::get_text_width, }, settings::{ Color, width::{Truncate, Wrap}, }, }; use crate::common::get_leading_trailing_space_style; pub fn string_width(text: &str) -> usize { get_text_width(text) } pub fn string_wrap(text: &str, width: usize, keep_words: bool) -> String { if text.is_empty() { return String::new(); } let text_width = string_width(text); if text_width <= width { return text.to_owned(); } Wrap::wrap(text, width, keep_words) } pub fn string_expand(text: &str, width: usize) -> String { use std::{borrow::Cow, iter::repeat_n}; use tabled::grid::util::string::{get_line_width, get_lines}; get_lines(text) .map(|line| { let length = get_line_width(&line); if length < width { let mut line = line.into_owned(); let remain = width - length; line.extend(repeat_n(' ', remain)); Cow::Owned(line) } else { line } }) .collect::<Vec<_>>() .join("\n") } pub fn string_truncate(text: &str, width: usize) -> String { let line = match text.lines().next() { Some(line) => line, None => return String::new(), }; Truncate::truncate(line, width).into_owned() } pub fn clean_charset(text: &str) -> String { // TODO: We could make an optimization to take a String and modify it // We could check if there was any changes and if not make no allocations at all and don't change the origin. // Why it's not done... // Cause I am not sure how the `if` in a loop will affect performance. // So it's better be profiled, but likely the optimization be worth it. // At least because it's a base case where we won't change anything.... // allocating at least the text size, // in most cases the buf will be a copy of text anyhow. // // but yes sometimes we will alloc more then necessary. // We could shrink it but...it will be another realloc which make no scense. let mut buf = String::with_capacity(text.len()); // note: (Left just in case) // note: This check could be added in order to cope with emojie issue. // if c < ' ' && c != '\u{1b}' { // continue; // } for c in text.chars() { match c { '\r' => continue, '\t' => { buf.push(' '); buf.push(' '); buf.push(' '); buf.push(' '); } c => { buf.push(c); } } } buf } pub fn colorize_space(data: &mut [Vec<Text<String>>], style_computer: &StyleComputer<'_>) { let style = match get_leading_trailing_space_style(style_computer).color_style { Some(color) => color, None => return, }; let style = ANSIBuf::from(convert_style(style)); let style = style.as_ref(); if style.is_empty() { return; } colorize_list(data, style, style); } pub fn colorize_space_str(text: &mut String, style_computer: &StyleComputer<'_>) { let style = match get_leading_trailing_space_style(style_computer).color_style { Some(color) => color, None => return, }; let style = ANSIBuf::from(convert_style(style)); let style = style.as_ref(); if style.is_empty() { return; } *text = colorize_space_one(text, style, style); } fn colorize_list(data: &mut [Vec<Text<String>>], lead: ANSIStr<'_>, trail: ANSIStr<'_>) { for row in data.iter_mut() { for cell in row { let buf = colorize_space_one(cell.as_ref(), lead, trail); *cell = Text::new(buf); } } } fn colorize_space_one(text: &str, lead: ANSIStr<'_>, trail: ANSIStr<'_>) -> String { use fancy_regex::Captures; use fancy_regex::Regex; use std::sync::LazyLock; static RE_LEADING: LazyLock<Regex> = LazyLock::new(|| { Regex::new(r"(?m)(?P<beginsp>^\s+)").expect("error with leading space regex") }); static RE_TRAILING: LazyLock<Regex> = LazyLock::new(|| { Regex::new(r"(?m)(?P<endsp>\s+$)").expect("error with trailing space regex") }); let mut buf = text.to_owned(); if !lead.is_empty() { buf = RE_LEADING .replace_all(&buf, |cap: &Captures| { let spaces = cap.get(1).expect("valid").as_str(); format!("{}{}{}", lead.get_prefix(), spaces, lead.get_suffix()) }) .into_owned(); } if !trail.is_empty() { buf = RE_TRAILING .replace_all(&buf, |cap: &Captures| { let spaces = cap.get(1).expect("valid").as_str(); format!("{}{}{}", trail.get_prefix(), spaces, trail.get_suffix()) }) .into_owned(); } buf } pub fn convert_style(style: nu_ansi_term::Style) -> Color { Color::new(style.prefix().to_string(), style.suffix().to_string()) } pub fn is_color_empty(c: &Color) -> bool { c.get_prefix().is_empty() && c.get_suffix().is_empty() }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-table/src/common.rs
crates/nu-table/src/common.rs
use crate::{TableOutput, TableTheme, clean_charset, colorize_space_str, string_wrap}; use nu_color_config::{Alignment, StyleComputer, TextStyle}; use nu_protocol::{Config, FooterMode, ShellError, Span, TableMode, TrimStrategy, Value}; use nu_utils::terminal_size; pub type NuText = (String, TextStyle); pub type TableResult = Result<Option<TableOutput>, ShellError>; pub type StringResult = Result<Option<String>, ShellError>; pub const INDEX_COLUMN_NAME: &str = "index"; pub fn configure_table( out: &mut TableOutput, config: &Config, comp: &StyleComputer, mode: TableMode, ) { let with_footer = is_footer_needed(config, out); let theme = load_theme(mode); out.table.set_theme(theme); out.table .set_structure(out.with_index, out.with_header, with_footer); out.table.set_trim(config.table.trim.clone()); out.table .set_border_header(config.table.header_on_separator); out.table.set_border_color(lookup_separator_color(comp)); } fn is_footer_needed(config: &Config, out: &TableOutput) -> bool { let mut count_rows = out.table.count_rows(); if config.table.footer_inheritance { count_rows = out.count_rows; } with_footer(config, out.with_header, count_rows) } pub fn nu_value_to_string_colored(val: &Value, cfg: &Config, comp: &StyleComputer) -> String { let (mut text, style) = nu_value_to_string(val, cfg, comp); let is_string = matches!(val, Value::String { .. }); if is_string { text = clean_charset(&text); } if let Some(color) = style.color_style { text = color.paint(text).to_string(); } if is_string { colorize_space_str(&mut text, comp); } text } pub fn nu_value_to_string(val: &Value, cfg: &Config, style: &StyleComputer) -> NuText { let float_precision = cfg.float_precision as usize; let text = val.to_abbreviated_string(cfg); make_styled_value(text, val, float_precision, style) } // todo: Expose a method which returns just style pub fn nu_value_to_string_clean(val: &Value, cfg: &Config, style_comp: &StyleComputer) -> NuText { let (text, style) = nu_value_to_string(val, cfg, style_comp); let mut text = clean_charset(&text); colorize_space_str(&mut text, style_comp); (text, style) } pub fn error_sign(text: String, style_computer: &StyleComputer) -> (String, TextStyle) { // Though holes are not the same as null, the closure for "empty" is passed a null anyway. let style = style_computer.compute("empty", &Value::nothing(Span::unknown())); (text, TextStyle::with_style(Alignment::Center, style)) } pub fn wrap_text(text: &str, width: usize, config: &Config) -> String { let keep_words = config.table.trim == TrimStrategy::wrap(true); string_wrap(text, width, keep_words) } pub fn get_header_style(style_computer: &StyleComputer) -> TextStyle { TextStyle::with_style( Alignment::Center, style_computer.compute("header", &Value::string("", Span::unknown())), ) } pub fn get_index_style(style_computer: &StyleComputer) -> TextStyle { TextStyle::with_style( Alignment::Right, style_computer.compute("row_index", &Value::string("", Span::unknown())), ) } pub fn get_leading_trailing_space_style(style_computer: &StyleComputer) -> TextStyle { TextStyle::with_style( Alignment::Right, style_computer.compute( "leading_trailing_space_bg", &Value::string("", Span::unknown()), ), ) } pub fn get_value_style(value: &Value, config: &Config, style_computer: &StyleComputer) -> NuText { match value { // Float precision is required here. Value::Float { val, .. } => ( format!("{:.prec$}", val, prec = config.float_precision as usize), style_computer.style_primitive(value), ), _ => ( value.to_abbreviated_string(config), style_computer.style_primitive(value), ), } } pub fn get_empty_style(text: String, style_computer: &StyleComputer) -> NuText { ( text, TextStyle::with_style( Alignment::Right, style_computer.compute("empty", &Value::nothing(Span::unknown())), ), ) } fn make_styled_value( text: String, value: &Value, float_precision: usize, style_computer: &StyleComputer, ) -> NuText { match value { Value::Float { .. } => { // set dynamic precision from config let precise_number = match convert_with_precision(&text, float_precision) { Ok(num) => num, Err(e) => e.to_string(), }; (precise_number, style_computer.style_primitive(value)) } _ => (text, style_computer.style_primitive(value)), } } fn convert_with_precision(val: &str, precision: usize) -> Result<String, ShellError> { // vall will always be a f64 so convert it with precision formatting let val_float = match val.trim().parse::<f64>() { Ok(f) => f, Err(e) => { return Err(ShellError::GenericError { error: format!("error converting string [{}] to f64", &val), msg: "".into(), span: None, help: Some(e.to_string()), inner: vec![], }); } }; Ok(format!("{val_float:.precision$}")) } pub fn load_theme(mode: TableMode) -> TableTheme { match mode { TableMode::Basic => TableTheme::basic(), TableMode::Thin => TableTheme::thin(), TableMode::Light => TableTheme::light(), TableMode::Compact => TableTheme::compact(), TableMode::WithLove => TableTheme::with_love(), TableMode::CompactDouble => TableTheme::compact_double(), TableMode::Rounded => TableTheme::rounded(), TableMode::Reinforced => TableTheme::reinforced(), TableMode::Heavy => TableTheme::heavy(), TableMode::None => TableTheme::none(), TableMode::Psql => TableTheme::psql(), TableMode::Markdown => TableTheme::markdown(), TableMode::Dots => TableTheme::dots(), TableMode::Restructured => TableTheme::restructured(), TableMode::AsciiRounded => TableTheme::ascii_rounded(), TableMode::BasicCompact => TableTheme::basic_compact(), TableMode::Single => TableTheme::single(), TableMode::Double => TableTheme::double(), } } fn lookup_separator_color(style_computer: &StyleComputer) -> nu_ansi_term::Style { style_computer.compute("separator", &Value::nothing(Span::unknown())) } fn with_footer(config: &Config, with_header: bool, count_records: usize) -> bool { with_header && need_footer(config, count_records as u64) } fn need_footer(config: &Config, count_records: u64) -> bool { match config.footer_mode { // Only show the footer if there are more than RowCount rows FooterMode::RowCount(limit) => count_records > limit, // Always show the footer FooterMode::Always => true, // Never show the footer FooterMode::Never => false, // Calculate the screen height and row count, if screen height is larger than row count, don't show footer FooterMode::Auto => { let (_width, height) = match terminal_size() { Ok((w, h)) => (w as u64, h as u64), _ => (0, 0), }; height <= count_records } } } pub fn check_value(value: &Value) -> Result<(), ShellError> { match value { Value::Error { error, .. } => Err(*error.clone()), _ => Ok(()), } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-table/src/table_theme.rs
crates/nu-table/src/table_theme.rs
use tabled::settings::{ style::{HorizontalLine, Style}, themes::Theme, }; #[derive(Debug, Clone)] pub struct TableTheme { base: Theme, full: Theme, } impl TableTheme { fn new(base: impl Into<Theme>, full: impl Into<Theme>) -> Self { Self { base: base.into(), full: full.into(), } } pub fn basic() -> TableTheme { Self::new(Style::ascii(), Style::ascii()) } pub fn thin() -> TableTheme { Self::new(Style::modern(), Style::modern()) } pub fn light() -> TableTheme { let mut theme = Theme::from_style(Style::blank()); theme.insert_horizontal_line(1, HorizontalLine::new('─').intersection('─')); Self::new(theme, Style::modern()) } pub fn psql() -> TableTheme { Self::new(Style::psql(), Style::psql()) } pub fn markdown() -> TableTheme { Self::new(Style::markdown(), Style::markdown()) } pub fn dots() -> TableTheme { let theme = Style::dots().remove_horizontal(); Self::new(theme, Style::dots()) } pub fn restructured() -> TableTheme { Self::new(Style::re_structured_text(), Style::re_structured_text()) } pub fn ascii_rounded() -> TableTheme { Self::new(Style::ascii_rounded(), Style::ascii_rounded()) } pub fn basic_compact() -> TableTheme { let theme = Style::ascii().remove_horizontal(); Self::new(theme, Style::ascii()) } pub fn compact() -> TableTheme { let hline = HorizontalLine::inherit(Style::modern().remove_left().remove_right()); let theme = Style::modern() .remove_left() .remove_right() .remove_horizontal() .horizontals([(1, hline)]); Self::new(theme, Style::modern()) } pub fn with_love() -> TableTheme { let theme = Style::empty() .top('❤') .bottom('❤') .vertical('❤') .horizontals([(1, HorizontalLine::new('❤').intersection('❤'))]); let full_theme = Style::empty() .top('❤') .bottom('❤') .vertical('❤') .horizontal('❤') .left('❤') .right('❤') .intersection_top('❤') .corner_top_left('❤') .corner_top_right('❤') .intersection_bottom('❤') .corner_bottom_left('❤') .corner_bottom_right('❤') .intersection_right('❤') .intersection_left('❤') .intersection('❤'); Self::new(theme, full_theme) } pub fn compact_double() -> TableTheme { let hline = HorizontalLine::inherit(Style::extended()) .remove_left() .remove_right(); let theme = Style::extended() .remove_left() .remove_right() .remove_horizontal() .horizontals([(1, hline)]); Self::new(theme, Style::extended()) } pub fn rounded() -> TableTheme { let full = Style::modern() .corner_top_left('╭') .corner_top_right('╮') .corner_bottom_left('╰') .corner_bottom_right('╯'); Self::new(Style::rounded(), full) } pub fn reinforced() -> TableTheme { let full = Style::modern() .corner_top_left('┏') .corner_top_right('┓') .corner_bottom_left('┗') .corner_bottom_right('┛'); Self::new(full.clone().remove_horizontal(), full) } pub fn heavy() -> TableTheme { let theme = Style::empty() .top('━') .bottom('━') .vertical('┃') .left('┃') .right('┃') .intersection_top('┳') .intersection_bottom('┻') .corner_top_left('┏') .corner_top_right('┓') .corner_bottom_left('┗') .corner_bottom_right('┛') .horizontals([(1, HorizontalLine::full('━', '╋', '┣', '┫'))]); let full = theme .clone() .remove_horizontals() .horizontal('━') .intersection_left('┣') .intersection_right('┫') .intersection('╋'); Self::new(theme, full) } pub fn single() -> TableTheme { let full = Style::modern() .corner_top_left('┌') .corner_top_right('┐') .corner_bottom_left('└') .corner_bottom_right('┘'); Self::new(Style::sharp(), full) } pub fn double() -> TableTheme { let hline = HorizontalLine::inherit(Style::extended()); let theme = Style::extended() .remove_horizontal() .horizontals([(1, hline)]); Self::new(theme, Style::extended()) } pub fn none() -> TableTheme { Self::new(Style::blank(), Style::blank()) } pub fn as_full(&self) -> &Theme { &self.full } pub fn as_base(&self) -> &Theme { &self.base } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-table/src/types/general.rs
crates/nu-table/src/types/general.rs
use nu_color_config::TextStyle; use nu_engine::column::get_columns; use nu_protocol::{Config, Record, ShellError, Value}; use crate::{ NuRecordsValue, NuTable, StringResult, TableOpts, TableOutput, TableResult, clean_charset, colorize_space, common::{ INDEX_COLUMN_NAME, NuText, check_value, configure_table, get_empty_style, get_header_style, get_index_style, get_value_style, nu_value_to_string_colored, }, types::has_index, }; pub struct JustTable; impl JustTable { pub fn table(input: Vec<Value>, opts: TableOpts<'_>) -> StringResult { list_table(input, opts) } pub fn kv_table(record: Record, opts: TableOpts<'_>) -> StringResult { kv_table(record, opts) } } fn list_table(input: Vec<Value>, opts: TableOpts<'_>) -> Result<Option<String>, ShellError> { let output = create_table(input, &opts)?; let mut out = match output { Some(out) => out, None => return Ok(None), }; // TODO: It would be WAY more effitient to do right away instead of second pass over the data. colorize_space(out.table.get_records_mut(), &opts.style_computer); configure_table(&mut out, opts.config, &opts.style_computer, opts.mode); let table = out.table.draw(opts.width); Ok(table) } fn get_key_style(topts: &TableOpts<'_>) -> TextStyle { get_header_style(&topts.style_computer).alignment(nu_color_config::Alignment::Left) } fn kv_table(record: Record, opts: TableOpts<'_>) -> StringResult { let mut table = NuTable::new(record.len(), 2); table.set_index_style(get_key_style(&opts)); table.set_indent(opts.config.table.padding); for (i, (key, value)) in record.into_iter().enumerate() { opts.signals.check(&opts.span)?; let value = nu_value_to_string_colored(&value, opts.config, &opts.style_computer); table.insert((i, 0), key); table.insert((i, 1), value); } let mut out = TableOutput::from_table(table, false, true); configure_table(&mut out, opts.config, &opts.style_computer, opts.mode); let table = out.table.draw(opts.width); Ok(table) } fn create_table(input: Vec<Value>, opts: &TableOpts<'_>) -> TableResult { if input.is_empty() { return Ok(None); } let headers = get_columns(&input); let with_index = has_index(opts, &headers); let with_header = !headers.is_empty(); let row_offset = opts.index_offset; let table = match (with_header, with_index) { (true, true) => create_table_with_header_and_index(input, headers, row_offset, opts)?, (true, false) => create_table_with_header(input, headers, opts)?, (false, true) => create_table_with_no_header_and_index(input, row_offset, opts)?, (false, false) => create_table_with_no_header(input, opts)?, }; let table = table.map(|table| TableOutput::from_table(table, with_header, with_index)); Ok(table) } fn create_table_with_header( input: Vec<Value>, headers: Vec<String>, opts: &TableOpts<'_>, ) -> Result<Option<NuTable>, ShellError> { let count_rows = input.len() + 1; let count_columns = headers.len(); let mut table = NuTable::new(count_rows, count_columns); table.set_header_style(get_header_style(&opts.style_computer)); table.set_index_style(get_index_style(&opts.style_computer)); table.set_indent(opts.config.table.padding); for (row, item) in input.into_iter().enumerate() { opts.signals.check(&opts.span)?; check_value(&item)?; for (col, header) in headers.iter().enumerate() { let (text, style) = get_string_value_with_header(&item, header, opts); let pos = (row + 1, col); table.insert(pos, text); table.insert_style(pos, style); } } let headers = collect_headers(headers, false); table.set_row(0, headers); Ok(Some(table)) } fn create_table_with_header_and_index( input: Vec<Value>, headers: Vec<String>, row_offset: usize, opts: &TableOpts<'_>, ) -> Result<Option<NuTable>, ShellError> { let head = collect_headers(headers, true); let count_rows = input.len() + 1; let count_columns = head.len(); let mut table = NuTable::new(count_rows, count_columns); table.set_header_style(get_header_style(&opts.style_computer)); table.set_index_style(get_index_style(&opts.style_computer)); table.set_indent(opts.config.table.padding); table.set_row(0, head.clone()); for (row, item) in input.into_iter().enumerate() { opts.signals.check(&opts.span)?; check_value(&item)?; let text = get_table_row_index(&item, opts.config, row, row_offset); table.insert((row + 1, 0), text); for (col, head) in head.iter().enumerate().skip(1) { let (text, style) = get_string_value_with_header(&item, head.as_ref(), opts); let pos = (row + 1, col); table.insert(pos, text); table.insert_style(pos, style); } } Ok(Some(table)) } fn create_table_with_no_header( input: Vec<Value>, opts: &TableOpts<'_>, ) -> Result<Option<NuTable>, ShellError> { let mut table = NuTable::new(input.len(), 1); table.set_index_style(get_index_style(&opts.style_computer)); table.set_indent(opts.config.table.padding); for (row, item) in input.into_iter().enumerate() { opts.signals.check(&opts.span)?; check_value(&item)?; let (text, style) = get_string_value(&item, opts); table.insert((row, 0), text); table.insert_style((row, 0), style); } Ok(Some(table)) } fn create_table_with_no_header_and_index( input: Vec<Value>, row_offset: usize, opts: &TableOpts<'_>, ) -> Result<Option<NuTable>, ShellError> { let mut table = NuTable::new(input.len(), 1 + 1); table.set_index_style(get_index_style(&opts.style_computer)); table.set_indent(opts.config.table.padding); for (row, item) in input.into_iter().enumerate() { opts.signals.check(&opts.span)?; check_value(&item)?; let index = get_table_row_index(&item, opts.config, row, row_offset); let (value, style) = get_string_value(&item, opts); table.insert((row, 0), index); table.insert((row, 1), value); table.insert_style((row, 1), style); } Ok(Some(table)) } fn get_string_value_with_header(item: &Value, header: &str, opts: &TableOpts) -> NuText { match item { Value::Record { val, .. } => match val.get(header) { Some(value) => get_string_value(value, opts), None => get_empty_style( opts.config.table.missing_value_symbol.clone(), &opts.style_computer, ), }, value => get_string_value(value, opts), } } fn get_string_value(item: &Value, opts: &TableOpts) -> NuText { let (mut text, style) = get_value_style(item, opts.config, &opts.style_computer); let is_string = matches!(item, Value::String { .. }); if is_string { text = clean_charset(&text); } (text, style) } fn get_table_row_index(item: &Value, config: &Config, row: usize, offset: usize) -> String { match item { Value::Record { val, .. } => val .get(INDEX_COLUMN_NAME) .map(|value| value.to_expanded_string("", config)) .unwrap_or_else(|| (row + offset).to_string()), _ => (row + offset).to_string(), } } fn collect_headers(headers: Vec<String>, index: bool) -> Vec<NuRecordsValue> { // The header with the INDEX is removed from the table headers since // it is added to the natural table index let length = if index { headers.len() + 1 } else { headers.len() }; let mut v = Vec::with_capacity(length); if index { v.insert(0, NuRecordsValue::new("#".into())); } for text in headers { // Only filter out the INDEX column when we're adding our own index column if index && text == INDEX_COLUMN_NAME { continue; } v.push(NuRecordsValue::new(text)); } v }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-table/src/types/expanded.rs
crates/nu-table/src/types/expanded.rs
use std::cmp::max; use nu_color_config::{Alignment, StyleComputer, TextStyle}; use nu_engine::column::get_columns; use nu_protocol::{Config, Record, ShellError, Span, Value}; use tabled::grid::records::vec_records::Cell; use crate::{ NuTable, TableOpts, TableOutput, common::{ INDEX_COLUMN_NAME, NuText, StringResult, TableResult, check_value, configure_table, error_sign, get_header_style, get_index_style, load_theme, nu_value_to_string, nu_value_to_string_clean, nu_value_to_string_colored, wrap_text, }, string_width, types::has_index, }; #[derive(Debug, Clone)] pub struct ExpandedTable { expand_limit: Option<usize>, flatten: bool, flatten_sep: String, } impl ExpandedTable { pub fn new(expand_limit: Option<usize>, flatten: bool, flatten_sep: String) -> Self { Self { expand_limit, flatten, flatten_sep, } } pub fn build_value(self, item: &Value, opts: TableOpts<'_>) -> NuText { let cfg = Cfg { opts, format: self }; let cell = expand_entry(item, cfg); (cell.text, cell.style) } pub fn build_map(self, record: &Record, opts: TableOpts<'_>) -> StringResult { let cfg = Cfg { opts, format: self }; expanded_table_kv(record, cfg).map(|cell| cell.map(|cell| cell.text)) } pub fn build_list(self, vals: &[Value], opts: TableOpts<'_>) -> StringResult { let cfg = Cfg { opts, format: self }; let output = expand_list(vals, cfg.clone())?; let mut output = match output { Some(out) => out, None => return Ok(None), }; configure_table( &mut output, cfg.opts.config, &cfg.opts.style_computer, cfg.opts.mode, ); maybe_expand_table(output, cfg.opts.width) } } #[derive(Debug, Clone)] struct Cfg<'a> { opts: TableOpts<'a>, format: ExpandedTable, } #[derive(Debug, Clone)] struct CellOutput { text: String, style: TextStyle, size: usize, is_expanded: bool, } impl CellOutput { fn new(text: String, style: TextStyle, size: usize, is_expanded: bool) -> Self { Self { text, style, size, is_expanded, } } fn clean(text: String, size: usize, is_expanded: bool) -> Self { Self::new(text, Default::default(), size, is_expanded) } fn text(text: String) -> Self { Self::styled((text, Default::default())) } fn styled(text: NuText) -> Self { Self::new(text.0, text.1, 1, false) } } type CellResult = Result<Option<CellOutput>, ShellError>; fn expand_list(input: &[Value], cfg: Cfg<'_>) -> TableResult { const SPLIT_LINE_SPACE: usize = 1; const MIN_CELL_WIDTH: usize = 3; const TRUNCATE_CONTENT_WIDTH: usize = 3; if input.is_empty() { return Ok(None); } let pad_width = cfg.opts.config.table.padding.left + cfg.opts.config.table.padding.right; let extra_width = pad_width + SPLIT_LINE_SPACE; let truncate_column_width = TRUNCATE_CONTENT_WIDTH + pad_width; // 2 - split lines let mut available_width = cfg .opts .width .saturating_sub(SPLIT_LINE_SPACE + SPLIT_LINE_SPACE); if available_width < MIN_CELL_WIDTH { return Ok(None); } let headers = get_columns(input); let with_index = has_index(&cfg.opts, &headers); // The header with the INDEX is removed from the table headers since // it is added to the natural table index (only when with_index is true) let headers: Vec<_> = headers .into_iter() .filter(|header| !with_index || header != INDEX_COLUMN_NAME) .collect(); let with_header = !headers.is_empty(); let row_offset = cfg.opts.index_offset; let mut total_rows = 0usize; if !with_index && !with_header { if available_width <= extra_width { // it means we have no space left for actual content; // which means there's no point in index itself if it was even used. // so we do not print it. return Ok(None); } available_width -= pad_width; let mut table = NuTable::new(input.len(), 1); table.set_index_style(get_index_style(&cfg.opts.style_computer)); table.set_header_style(get_header_style(&cfg.opts.style_computer)); table.set_indent(cfg.opts.config.table.padding); for (row, item) in input.iter().enumerate() { cfg.opts.signals.check(&cfg.opts.span)?; check_value(item)?; let inner_cfg = cfg_expand_reset_table(cfg.clone(), available_width); let cell = expand_entry(item, inner_cfg); table.insert((row, 0), cell.text); table.insert_style((row, 0), cell.style); total_rows = total_rows.saturating_add(cell.size); } return Ok(Some(TableOutput::new(table, false, false, total_rows))); } if !with_header && with_index { let mut table = NuTable::new(input.len(), 2); table.set_index_style(get_index_style(&cfg.opts.style_computer)); table.set_header_style(get_header_style(&cfg.opts.style_computer)); table.set_indent(cfg.opts.config.table.padding); let mut index_column_width = 0; for (row, item) in input.iter().enumerate() { cfg.opts.signals.check(&cfg.opts.span)?; check_value(item)?; let index = row + row_offset; let index_value = item .as_record() .ok() .and_then(|val| val.get(INDEX_COLUMN_NAME)) .map(|value| value.to_expanded_string("", cfg.opts.config)) .unwrap_or_else(|| index.to_string()); let index_value = NuTable::create(index_value); let index_width = index_value.width(); if available_width <= index_width + extra_width + pad_width { // NOTE: we don't wanna wrap index; so we return return Ok(None); } table.insert_value((row, 0), index_value); index_column_width = max(index_column_width, index_width); } available_width -= index_column_width + extra_width + pad_width; for (row, item) in input.iter().enumerate() { cfg.opts.signals.check(&cfg.opts.span)?; check_value(item)?; let inner_cfg = cfg_expand_reset_table(cfg.clone(), available_width); let cell = expand_entry(item, inner_cfg); table.insert((row, 1), cell.text); table.insert_style((row, 1), cell.style); total_rows = total_rows.saturating_add(cell.size); } return Ok(Some(TableOutput::new(table, false, true, total_rows))); } // NOTE: redefine to not break above logic (fixme) let mut available_width = cfg.opts.width - SPLIT_LINE_SPACE; let mut table = NuTable::new(input.len() + 1, headers.len() + with_index as usize); table.set_index_style(get_index_style(&cfg.opts.style_computer)); table.set_header_style(get_header_style(&cfg.opts.style_computer)); table.set_indent(cfg.opts.config.table.padding); let mut widths = Vec::new(); if with_index { table.insert((0, 0), String::from("#")); let mut index_column_width = 1; for (row, item) in input.iter().enumerate() { cfg.opts.signals.check(&cfg.opts.span)?; check_value(item)?; let index = row + row_offset; let index_value = item .as_record() .ok() .and_then(|val| val.get(INDEX_COLUMN_NAME)) .map(|value| value.to_expanded_string("", cfg.opts.config)) .unwrap_or_else(|| index.to_string()); let index_value = NuTable::create(index_value); let index_width = index_value.width(); table.insert_value((row + 1, 0), index_value); index_column_width = max(index_column_width, index_width); } if available_width <= index_column_width + extra_width { // NOTE: we don't wanna wrap index; so we return return Ok(None); } available_width -= index_column_width + extra_width; widths.push(index_column_width); } let count_columns = headers.len(); let mut truncate = false; let mut rendered_column = 0; for (col, header) in headers.into_iter().enumerate() { let column = col + with_index as usize; if available_width <= extra_width { table.pop_column(table.count_columns() - column); truncate = true; break; } let mut available = available_width - extra_width; // We want to reserver some space for next column // If we can't fit it in it will be popped anyhow. let is_prelast_column = col + 2 == count_columns; let is_last_column = col + 1 == count_columns; if is_prelast_column { let need_width = MIN_CELL_WIDTH + SPLIT_LINE_SPACE; if available > need_width { available -= need_width; } } else if !is_last_column { let need_width: usize = truncate_column_width + SPLIT_LINE_SPACE; if available > need_width { available -= need_width; } } let mut total_column_rows = 0usize; let mut column_width = 0; for (row, item) in input.iter().enumerate() { cfg.opts.signals.check(&cfg.opts.span)?; check_value(item)?; let inner_cfg = cfg_expand_reset_table(cfg.clone(), available); let cell = expand_entry_with_header(item, &header, inner_cfg); // TODO: optimize cause when we expand we alrready know the width (most of the time or all) let mut value = NuTable::create(cell.text); let mut value_width = value.width(); if value_width > available { // NOTE: // most likely it was emojie which we are not sure about what to do // so we truncate it just in case // // most likely width is 1 value = NuTable::create(String::from("\u{FFFD}")); value_width = 1; } column_width = max(column_width, value_width); table.insert_value((row + 1, column), value); table.insert_style((row + 1, column), cell.style); total_column_rows = total_column_rows.saturating_add(cell.size); } let mut head_width = string_width(&header); let mut header = header; if head_width > available { header = wrap_text(&header, available, cfg.opts.config); head_width = available; } table.insert((0, column), header); column_width = max(column_width, head_width); assert!(column_width <= available); widths.push(column_width); available_width -= column_width + extra_width; rendered_column += 1; total_rows = std::cmp::max(total_rows, total_column_rows); } if truncate { if rendered_column == 0 { // it means that no actual data was rendered, there might be only index present, // so there's no point in rendering the table. // // It's actually quite important in case it's called recursively, // cause we will back up to the basic table view as a string e.g. '[table 123 columns]'. // // But potentially if its reached as a 1st called function we might would love to see the index. return Ok(None); } if available_width < truncate_column_width { // back up by removing last column. // it's LIKELY that removing only 1 column will leave us enough space for a shift column. while let Some(width) = widths.pop() { table.pop_column(1); available_width += width + pad_width; if !widths.is_empty() { available_width += SPLIT_LINE_SPACE; } if available_width > truncate_column_width { break; } } } // this must be a RARE case or even NEVER happen, // but we do check it just in case. if available_width < truncate_column_width { return Ok(None); } let is_last_column = widths.len() == count_columns; if !is_last_column { table.push_column(String::from("...")); widths.push(3); } } Ok(Some(TableOutput::new(table, true, with_index, total_rows))) } fn expanded_table_kv(record: &Record, cfg: Cfg<'_>) -> CellResult { let theme = load_theme(cfg.opts.mode); let theme = theme.as_base(); let key_width = record .columns() .map(|col| string_width(col)) .max() .unwrap_or(0); let count_borders = theme.borders_has_vertical() as usize + theme.borders_has_right() as usize + theme.borders_has_left() as usize; let pad = cfg.opts.config.table.padding.left + cfg.opts.config.table.padding.right; if key_width + count_borders + pad + pad > cfg.opts.width { return Ok(None); } let value_width = cfg.opts.width - key_width - count_borders - pad - pad; let mut total_rows = 0usize; let mut table = NuTable::new(record.len(), 2); table.set_index_style(get_key_style(&cfg)); table.set_indent(cfg.opts.config.table.padding); for (i, (key, value)) in record.iter().enumerate() { cfg.opts.signals.check(&cfg.opts.span)?; let cell = match expand_value(value, value_width, &cfg)? { Some(val) => val, None => return Ok(None), }; let value = cell.text; let mut key = key.to_owned(); // we want to have a key being aligned to 2nd line, // we could use Padding for it but, // the easiest way to do so is just push a new_line char before let is_key_on_next_line = !key.is_empty() && cell.is_expanded && theme.borders_has_top(); if is_key_on_next_line { key.insert(0, '\n'); } table.insert((i, 0), key); table.insert((i, 1), value); total_rows = total_rows.saturating_add(cell.size); } let mut out = TableOutput::new(table, false, true, total_rows); configure_table( &mut out, cfg.opts.config, &cfg.opts.style_computer, cfg.opts.mode, ); maybe_expand_table(out, cfg.opts.width) .map(|value| value.map(|value| CellOutput::clean(value, total_rows, false))) } // the flag is used as an optimization to not do `value.lines().count()` search. fn expand_value(value: &Value, width: usize, cfg: &Cfg<'_>) -> CellResult { if is_limit_reached(cfg) { let value = value_to_string_clean(value, cfg); return Ok(Some(CellOutput::clean(value, 1, false))); } let span = value.span(); match value { Value::List { vals, .. } => { let inner_cfg = cfg_expand_reset_table(cfg_expand_next_level(cfg.clone(), span), width); let table = expand_list(vals, inner_cfg)?; match table { Some(mut out) => { table_apply_config(&mut out, cfg); let value = out.table.draw_unchecked(width); match value { Some(value) => Ok(Some(CellOutput::clean(value, out.count_rows, true))), None => Ok(None), } } None => { // it means that the list is empty let value = value_to_wrapped_string(value, cfg, width); Ok(Some(CellOutput::text(value))) } } } Value::Record { val: record, .. } => { if record.is_empty() { // Like list case return styled string instead of empty value let value = value_to_wrapped_string(value, cfg, width); return Ok(Some(CellOutput::text(value))); } let inner_cfg = cfg_expand_reset_table(cfg_expand_next_level(cfg.clone(), span), width); let result = expanded_table_kv(record, inner_cfg)?; match result { Some(result) => Ok(Some(CellOutput::clean(result.text, result.size, true))), None => { let value = value_to_wrapped_string(value, cfg, width); Ok(Some(CellOutput::text(value))) } } } _ => { let value = value_to_wrapped_string_clean(value, cfg, width); Ok(Some(CellOutput::text(value))) } } } fn get_key_style(cfg: &Cfg<'_>) -> TextStyle { get_header_style(&cfg.opts.style_computer).alignment(Alignment::Left) } fn expand_entry_with_header(item: &Value, header: &str, cfg: Cfg<'_>) -> CellOutput { match item { Value::Record { val, .. } => match val.get(header) { Some(val) => expand_entry(val, cfg), None => CellOutput::styled(error_sign( cfg.opts.config.table.missing_value_symbol.clone(), &cfg.opts.style_computer, )), }, _ => expand_entry(item, cfg), } } fn expand_entry(item: &Value, cfg: Cfg<'_>) -> CellOutput { if is_limit_reached(&cfg) { let value = nu_value_to_string_clean(item, cfg.opts.config, &cfg.opts.style_computer); let value = nutext_wrap(value, &cfg); return CellOutput::styled(value); } let span = item.span(); match &item { Value::Record { val: record, .. } => { if record.is_empty() { let value = nu_value_to_string(item, cfg.opts.config, &cfg.opts.style_computer); let value = nutext_wrap(value, &cfg); return CellOutput::styled(value); } // we verify what is the structure of a Record cause it might represent let inner_cfg = cfg_expand_next_level(cfg.clone(), span); let table = expanded_table_kv(record, inner_cfg); match table { Ok(Some(table)) => table, _ => { let value = nu_value_to_string(item, cfg.opts.config, &cfg.opts.style_computer); let value = nutext_wrap(value, &cfg); CellOutput::styled(value) } } } Value::List { vals, .. } => { if cfg.format.flatten && is_simple_list(vals) { let value = list_to_string( vals, cfg.opts.config, &cfg.opts.style_computer, &cfg.format.flatten_sep, ); return CellOutput::text(value); } let inner_cfg = cfg_expand_next_level(cfg.clone(), span); let table = expand_list(vals, inner_cfg); let mut out = match table { Ok(Some(out)) => out, _ => { let value = nu_value_to_string(item, cfg.opts.config, &cfg.opts.style_computer); let value = nutext_wrap(value, &cfg); return CellOutput::styled(value); } }; table_apply_config(&mut out, &cfg); let table = out.table.draw_unchecked(cfg.opts.width); match table { Some(table) => CellOutput::clean(table, out.count_rows, false), None => { let value = nu_value_to_string(item, cfg.opts.config, &cfg.opts.style_computer); let value = nutext_wrap(value, &cfg); CellOutput::styled(value) } } } _ => { let value = nu_value_to_string_clean(item, cfg.opts.config, &cfg.opts.style_computer); let value = nutext_wrap(value, &cfg); CellOutput::styled(value) } } } fn nutext_wrap(mut text: NuText, cfg: &Cfg<'_>) -> NuText { let width = string_width(&text.0); if width > cfg.opts.width { text.0 = wrap_text(&text.0, cfg.opts.width, cfg.opts.config); } text } fn is_limit_reached(cfg: &Cfg<'_>) -> bool { matches!(cfg.format.expand_limit, Some(0)) } fn is_simple_list(vals: &[Value]) -> bool { vals.iter() .all(|v| !matches!(v, Value::Record { .. } | Value::List { .. })) } fn list_to_string( vals: &[Value], config: &Config, style_computer: &StyleComputer, sep: &str, ) -> String { let mut buf = String::new(); for (i, value) in vals.iter().enumerate() { if i > 0 { buf.push_str(sep); } let (text, _) = nu_value_to_string_clean(value, config, style_computer); buf.push_str(&text); } buf } fn maybe_expand_table(mut out: TableOutput, term_width: usize) -> StringResult { let total_width = out.table.total_width(); if total_width < term_width { const EXPAND_THRESHOLD: f32 = 0.80; let used_percent = total_width as f32 / term_width as f32; let need_expansion = total_width < term_width && used_percent > EXPAND_THRESHOLD; if need_expansion { out.table.set_strategy(true); } } let table = out.table.draw_unchecked(term_width); Ok(table) } fn table_apply_config(out: &mut TableOutput, cfg: &Cfg<'_>) { configure_table( out, cfg.opts.config, &cfg.opts.style_computer, cfg.opts.mode, ) } fn value_to_string(value: &Value, cfg: &Cfg<'_>) -> String { nu_value_to_string(value, cfg.opts.config, &cfg.opts.style_computer).0 } fn value_to_string_clean(value: &Value, cfg: &Cfg<'_>) -> String { nu_value_to_string_clean(value, cfg.opts.config, &cfg.opts.style_computer).0 } fn value_to_wrapped_string(value: &Value, cfg: &Cfg<'_>, value_width: usize) -> String { wrap_text(&value_to_string(value, cfg), value_width, cfg.opts.config) } fn value_to_wrapped_string_clean(value: &Value, cfg: &Cfg<'_>, value_width: usize) -> String { let text = nu_value_to_string_colored(value, cfg.opts.config, &cfg.opts.style_computer); wrap_text(&text, value_width, cfg.opts.config) } fn cfg_expand_next_level(mut cfg: Cfg<'_>, span: Span) -> Cfg<'_> { cfg.opts.span = span; if let Some(deep) = cfg.format.expand_limit.as_mut() { *deep -= 1 } cfg } fn cfg_expand_reset_table(mut cfg: Cfg<'_>, width: usize) -> Cfg<'_> { cfg.opts.width = width; cfg.opts.index_offset = 0; cfg }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-table/src/types/collapse.rs
crates/nu-table/src/types/collapse.rs
use nu_ansi_term::Style; use nu_color_config::StyleComputer; use nu_protocol::{Config, Value}; use nu_utils::SharedCow; use crate::{ StringResult, TableOpts, UnstructuredTable, common::{get_index_style, load_theme, nu_value_to_string_clean}, }; pub struct CollapsedTable; impl CollapsedTable { pub fn build(value: Value, opts: TableOpts<'_>) -> StringResult { collapsed_table(value, opts) } } fn collapsed_table(mut value: Value, opts: TableOpts<'_>) -> StringResult { colorize_value(&mut value, opts.config, &opts.style_computer); let mut table = UnstructuredTable::new(value, opts.config); let theme = load_theme(opts.mode); let is_empty = table.truncate(&theme, opts.width); if is_empty { return Ok(None); } let table = table.draw(&theme, opts.config.table.padding, &opts.style_computer); Ok(Some(table)) } fn colorize_value(value: &mut Value, config: &Config, style_computer: &StyleComputer) { // todo: Remove recursion? match value { Value::Record { val, .. } => { let style = get_index_style(style_computer); // Take ownership of the record and reassign to &mut // We do this to have owned keys through `.into_iter` let record = std::mem::take(val); *val = SharedCow::new( record .into_owned() .into_iter() .map(|(mut header, mut val)| { colorize_value(&mut val, config, style_computer); header = colorize_text(&header, style.color_style).unwrap_or(header); (header, val) }) .collect(), ); } Value::List { vals, .. } => { for val in vals { colorize_value(val, config, style_computer); } } value => { let (text, style) = nu_value_to_string_clean(value, config, style_computer); if let Some(text) = colorize_text(&text, style.color_style) { *value = Value::string(text, value.span()); } } } } fn colorize_text(text: &str, color: Option<Style>) -> Option<String> { if let Some(color) = color && !color.is_plain() { return Some(color.paint(text).to_string()); } None }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-table/src/types/mod.rs
crates/nu-table/src/types/mod.rs
use nu_color_config::StyleComputer; use nu_protocol::{Config, Signals, Span, TableIndexMode, TableMode}; use crate::{NuTable, common::INDEX_COLUMN_NAME}; mod collapse; mod expanded; mod general; pub use collapse::CollapsedTable; pub use expanded::ExpandedTable; pub use general::JustTable; pub struct TableOutput { /// A table structure. pub table: NuTable, /// A flag whether a header was present in the table. pub with_header: bool, /// A flag whether a index was present in the table. pub with_index: bool, /// The value may be bigger then table.count_rows(), /// Specifically in case of expanded table we collect the whole structure size here. pub count_rows: usize, } impl TableOutput { pub fn new(table: NuTable, with_header: bool, with_index: bool, count_rows: usize) -> Self { Self { table, with_header, with_index, count_rows, } } pub fn from_table(table: NuTable, with_header: bool, with_index: bool) -> Self { let count_rows = table.count_rows(); Self::new(table, with_header, with_index, count_rows) } } #[derive(Debug, Clone)] pub struct TableOpts<'a> { pub signals: &'a Signals, pub config: &'a Config, pub style_computer: std::rc::Rc<StyleComputer<'a>>, pub span: Span, pub width: usize, pub mode: TableMode, pub index_offset: usize, pub index_remove: bool, } impl<'a> TableOpts<'a> { #[allow(clippy::too_many_arguments)] pub fn new( config: &'a Config, style_computer: StyleComputer<'a>, signals: &'a Signals, span: Span, width: usize, mode: TableMode, index_offset: usize, index_remove: bool, ) -> Self { let style_computer = std::rc::Rc::new(style_computer); Self { signals, config, style_computer, span, width, mode, index_offset, index_remove, } } } fn has_index(opts: &TableOpts<'_>, headers: &[String]) -> bool { let with_index = match opts.config.table.index_mode { TableIndexMode::Always => true, TableIndexMode::Never => false, TableIndexMode::Auto => headers.iter().any(|header| header == INDEX_COLUMN_NAME), }; with_index && !opts.index_remove }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-table/tests/expand.rs
crates/nu-table/tests/expand.rs
mod common; use common::{TestCase, create_row, create_table}; use nu_table::TableTheme as theme; #[test] fn test_expand() { let table = create_table( vec![create_row(4); 3], TestCase::new(50).theme(theme::rounded()).header().expand(), ); assert_eq!( table.unwrap(), "╭────────────┬───────────┬───────────┬───────────╮\n\ │ 0 │ 1 │ 2 │ 3 │\n\ ├────────────┼───────────┼───────────┼───────────┤\n\ │ 0 │ 1 │ 2 │ 3 │\n\ │ 0 │ 1 │ 2 │ 3 │\n\ ╰────────────┴───────────┴───────────┴───────────╯" ); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-table/tests/constrains.rs
crates/nu-table/tests/constrains.rs
mod common; use nu_protocol::TrimStrategy; use nu_table::{NuTable, TableTheme as theme}; use common::{TestCase, create_row, test_table}; use tabled::grid::records::vec_records::Text; #[test] fn data_and_header_has_different_size_doesnt_work() { let mut table = NuTable::from(vec![create_row(5), create_row(5), create_row(5)]); table.set_theme(theme::heavy()); table.set_structure(false, true, false); let table = table.draw(usize::MAX); assert_eq!( table.as_deref(), Some( "┏━━━┳━━━┳━━━┳━━━┳━━━┓\n\ ┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃ 4 ┃\n\ ┣━━━╋━━━╋━━━╋━━━╋━━━┫\n\ ┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃ 4 ┃\n\ ┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃ 4 ┃\n\ ┗━━━┻━━━┻━━━┻━━━┻━━━┛" ) ); let mut table = NuTable::from(vec![create_row(5), create_row(5), create_row(5)]); table.set_theme(theme::heavy()); table.set_structure(false, true, false); let table = table.draw(usize::MAX); assert_eq!( table.as_deref(), Some( "┏━━━┳━━━┳━━━┳━━━┳━━━┓\n\ ┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃ 4 ┃\n\ ┣━━━╋━━━╋━━━╋━━━╋━━━┫\n\ ┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃ 4 ┃\n\ ┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃ 4 ┃\n\ ┗━━━┻━━━┻━━━┻━━━┻━━━┛" ) ); } #[test] fn termwidth_too_small() { let tests = [ TrimStrategy::truncate(None), TrimStrategy::truncate(Some(String::from("**"))), TrimStrategy::truncate(Some(String::from(""))), TrimStrategy::wrap(false), TrimStrategy::wrap(true), ]; let data = vec![create_row(5), create_row(5), create_row(5)]; for case in tests { for i in 0..10 { let mut table = NuTable::from(data.clone()); table.set_theme(theme::heavy()); table.set_structure(false, true, false); table.set_trim(case.clone()); let table = table.draw(i); assert!(table.is_none()); } } } #[test] fn wrap_test() { for test in 0..15 { test_trim(&[(test, None)], TrimStrategy::wrap(false)); } let tests = [ ( 15, Some( "┏━━━━━━━┳━━━━━┓\n\ ┃ 123 4 ┃ ... ┃\n\ ┃ 5678 ┃ ┃\n\ ┣━━━━━━━╋━━━━━┫\n\ ┃ 0 ┃ ... ┃\n\ ┃ 0 ┃ ... ┃\n\ ┗━━━━━━━┻━━━━━┛", ), ), ( 21, Some( "┏━━━━━━━━━━━┳━━━━━┓\n\ ┃ 123 45678 ┃ ... ┃\n\ ┣━━━━━━━━━━━╋━━━━━┫\n\ ┃ 0 ┃ ... ┃\n\ ┃ 0 ┃ ... ┃\n\ ┗━━━━━━━━━━━┻━━━━━┛", ), ), ( 29, Some( "┏━━━━━━━━━━━┳━━━━━━━━━┳━━━━━┓\n\ ┃ 123 45678 ┃ qweqw e ┃ ... ┃\n\ ┃ ┃ qwe ┃ ┃\n\ ┣━━━━━━━━━━━╋━━━━━━━━━╋━━━━━┫\n\ ┃ 0 ┃ 1 ┃ ... ┃\n\ ┃ 0 ┃ 1 ┃ ... ┃\n\ ┗━━━━━━━━━━━┻━━━━━━━━━┻━━━━━┛", ), ), ( 49, Some( "┏━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━┓\n\ ┃ 123 45678 ┃ qweqw eqwe ┃ xxx xx xx x xx ┃ ... ┃\n\ ┃ ┃ ┃ x xx xx ┃ ┃\n\ ┣━━━━━━━━━━━╋━━━━━━━━━━━━╋━━━━━━━━━━━━━━━━╋━━━━━┫\n\ ┃ 0 ┃ 1 ┃ 2 ┃ ... ┃\n\ ┃ 0 ┃ 1 ┃ 2 ┃ ... ┃\n\ ┗━━━━━━━━━━━┻━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━┻━━━━━┛", ), ), ]; test_trim(&tests, TrimStrategy::wrap(false)); let single_tests = [ ( 15, Some( "┏━━━━━━━━━━━━┓\n\ ┃ 0 2 4 6 8 ┃\n\ ┃ 0 2 4 6 8 ┃\n\ ┃ 0 ┃\n\ ┗━━━━━━━━━━━━┛", ), ), ( 21, Some( "┏━━━━━━━━━━━━━━━━━━┓\n\ ┃ 0 2 4 6 8 0 2 4 ┃\n\ ┃ 6 8 0 ┃\n\ ┗━━━━━━━━━━━━━━━━━━┛", ), ), ( 40, Some( "┏━━━━━━━━━━━━━━━━━━━━━━━┓\n\ ┃ 0 2 4 6 8 0 2 4 6 8 0 ┃\n\ ┗━━━━━━━━━━━━━━━━━━━━━━━┛", ), ), ]; test_trim_single(&single_tests, TrimStrategy::wrap(false)); } #[test] fn wrap_keep_words_test() { for test in 0..15 { test_trim(&[(test, None)], TrimStrategy::wrap(true)); } let tests = [ ( 15, Some( "┏━━━━━━━┳━━━━━┓\n\ ┃ 123 ┃ ... ┃\n\ ┃ 45678 ┃ ┃\n\ ┣━━━━━━━╋━━━━━┫\n\ ┃ 0 ┃ ... ┃\n\ ┃ 0 ┃ ... ┃\n\ ┗━━━━━━━┻━━━━━┛", ), ), ( 15, Some( "┏━━━━━━━┳━━━━━┓\n\ ┃ 123 ┃ ... ┃\n\ ┃ 45678 ┃ ┃\n\ ┣━━━━━━━╋━━━━━┫\n\ ┃ 0 ┃ ... ┃\n\ ┃ 0 ┃ ... ┃\n\ ┗━━━━━━━┻━━━━━┛", ), ), ( 21, Some( "┏━━━━━━━━━━━┳━━━━━┓\n\ ┃ 123 45678 ┃ ... ┃\n\ ┣━━━━━━━━━━━╋━━━━━┫\n\ ┃ 0 ┃ ... ┃\n\ ┃ 0 ┃ ... ┃\n\ ┗━━━━━━━━━━━┻━━━━━┛", ), ), ( 29, Some( "┏━━━━━━━━━━━┳━━━━━━━━━┳━━━━━┓\n\ ┃ 123 45678 ┃ qweqw ┃ ... ┃\n\ ┃ ┃ eqwe ┃ ┃\n\ ┣━━━━━━━━━━━╋━━━━━━━━━╋━━━━━┫\n\ ┃ 0 ┃ 1 ┃ ... ┃\n\ ┃ 0 ┃ 1 ┃ ... ┃\n\ ┗━━━━━━━━━━━┻━━━━━━━━━┻━━━━━┛", ), ), ( 49, Some( "┏━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━┓\n\ ┃ 123 45678 ┃ qweqw eqwe ┃ xxx xx xx x xx ┃ ... ┃\n\ ┃ ┃ ┃ x xx xx ┃ ┃\n\ ┣━━━━━━━━━━━╋━━━━━━━━━━━━╋━━━━━━━━━━━━━━━━╋━━━━━┫\n\ ┃ 0 ┃ 1 ┃ 2 ┃ ... ┃\n\ ┃ 0 ┃ 1 ┃ 2 ┃ ... ┃\n\ ┗━━━━━━━━━━━┻━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━┻━━━━━┛", ), ), ]; test_trim(&tests, TrimStrategy::wrap(true)); } #[test] fn truncate_test() { for test in 0..15 { test_trim(&[(test, None)], TrimStrategy::wrap(true)); } let tests = [ ( 15, Some( "┏━━━━━━━┳━━━━━┓\n\ ┃ 123 4 ┃ ... ┃\n\ ┣━━━━━━━╋━━━━━┫\n\ ┃ 0 ┃ ... ┃\n\ ┃ 0 ┃ ... ┃\n\ ┗━━━━━━━┻━━━━━┛", ), ), ( 21, Some( "┏━━━━━━━━━━━┳━━━━━┓\n\ ┃ 123 45678 ┃ ... ┃\n\ ┣━━━━━━━━━━━╋━━━━━┫\n\ ┃ 0 ┃ ... ┃\n\ ┃ 0 ┃ ... ┃\n\ ┗━━━━━━━━━━━┻━━━━━┛", ), ), ( 29, Some( "┏━━━━━━━━━━━┳━━━━━━━━━┳━━━━━┓\n\ ┃ 123 45678 ┃ qweqw e ┃ ... ┃\n\ ┣━━━━━━━━━━━╋━━━━━━━━━╋━━━━━┫\n\ ┃ 0 ┃ 1 ┃ ... ┃\n\ ┃ 0 ┃ 1 ┃ ... ┃\n\ ┗━━━━━━━━━━━┻━━━━━━━━━┻━━━━━┛", ), ), ( 49, Some( "┏━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━┓\n\ ┃ 123 45678 ┃ qweqw eqwe ┃ xxx xx xx x xx ┃ ... ┃\n\ ┣━━━━━━━━━━━╋━━━━━━━━━━━━╋━━━━━━━━━━━━━━━━╋━━━━━┫\n\ ┃ 0 ┃ 1 ┃ 2 ┃ ... ┃\n\ ┃ 0 ┃ 1 ┃ 2 ┃ ... ┃\n\ ┗━━━━━━━━━━━┻━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━┻━━━━━┛", ), ), ]; test_trim(&tests, TrimStrategy::truncate(None)); } #[test] fn truncate_with_suffix_test() { for test in 0..15 { test_trim(&[(test, None)], TrimStrategy::wrap(true)); } let tests = [ ( 15, Some( "┏━━━━━━━┳━━━━━┓\n\ ┃ 12... ┃ ... ┃\n\ ┣━━━━━━━╋━━━━━┫\n\ ┃ 0 ┃ ... ┃\n\ ┃ 0 ┃ ... ┃\n\ ┗━━━━━━━┻━━━━━┛", ), ), ( 21, Some( "┏━━━━━━━━━━━┳━━━━━┓\n\ ┃ 123 45678 ┃ ... ┃\n\ ┣━━━━━━━━━━━╋━━━━━┫\n\ ┃ 0 ┃ ... ┃\n\ ┃ 0 ┃ ... ┃\n\ ┗━━━━━━━━━━━┻━━━━━┛", ), ), ( 29, Some( "┏━━━━━━━━━━━┳━━━━━━━━━┳━━━━━┓\n\ ┃ 123 45678 ┃ qweq... ┃ ... ┃\n\ ┣━━━━━━━━━━━╋━━━━━━━━━╋━━━━━┫\n\ ┃ 0 ┃ 1 ┃ ... ┃\n\ ┃ 0 ┃ 1 ┃ ... ┃\n\ ┗━━━━━━━━━━━┻━━━━━━━━━┻━━━━━┛", ), ), ( 49, Some( "┏━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━┓\n\ ┃ 123 45678 ┃ qweqw eqwe ┃ xxx xx xx x... ┃ ... ┃\n\ ┣━━━━━━━━━━━╋━━━━━━━━━━━━╋━━━━━━━━━━━━━━━━╋━━━━━┫\n\ ┃ 0 ┃ 1 ┃ 2 ┃ ... ┃\n\ ┃ 0 ┃ 1 ┃ 2 ┃ ... ┃\n\ ┗━━━━━━━━━━━┻━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━┻━━━━━┛", ), ), ]; test_trim(&tests, TrimStrategy::truncate(Some(String::from("...")))); } #[test] fn width_control_test_0() { let data = vec![ vec![ common::cell( "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ); 16 ], vec![ common::cell( "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy" ); 16 ], vec![ common::cell( "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" ); 16 ], ]; let tests = [ ( 20, "┏━━━━━━━━━━━━┳━━━━━┓\n\ ┃ xxxxxxx... ┃ ... ┃\n\ ┣━━━━━━━━━━━━╋━━━━━┫\n\ ┃ yyyyyyy... ┃ ... ┃\n\ ┃ zzzzzzz... ┃ ... ┃\n\ ┗━━━━━━━━━━━━┻━━━━━┛", ), ( 119, "┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━┓\n\ ┃ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx... ┃ ... ┃\n\ ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╋━━━━━┫\n\ ┃ yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy... ┃ ... ┃\n\ ┃ zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz... ┃ ... ┃\n\ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┻━━━━━┛", ), ( 120, "┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━┓\n\ ┃ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx... ┃ ... ┃\n\ ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╋━━━━━┫\n\ ┃ yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy... ┃ ... ┃\n\ ┃ zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz... ┃ ... ┃\n\ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┻━━━━━┛", ), ( 121, "┏━━━━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━┓\n\ ┃ xxxxxxxxxx... ┃ xxxxxxx... ┃ xxxxxxx... ┃ xxxxxxx... ┃ xxxxxxx... ┃ xxxxxxx... ┃ xxxxxxx... ┃ xxxxxxx... ┃ ... ┃\n\ ┣━━━━━━━━━━━━━━━╋━━━━━━━━━━━━╋━━━━━━━━━━━━╋━━━━━━━━━━━━╋━━━━━━━━━━━━╋━━━━━━━━━━━━╋━━━━━━━━━━━━╋━━━━━━━━━━━━╋━━━━━┫\n\ ┃ yyyyyyyyyy... ┃ yyyyyyy... ┃ yyyyyyy... ┃ yyyyyyy... ┃ yyyyyyy... ┃ yyyyyyy... ┃ yyyyyyy... ┃ yyyyyyy... ┃ ... ┃\n\ ┃ zzzzzzzzzz... ┃ zzzzzzz... ┃ zzzzzzz... ┃ zzzzzzz... ┃ zzzzzzz... ┃ zzzzzzz... ┃ zzzzzzz... ┃ zzzzzzz... ┃ ... ┃\n\ ┗━━━━━━━━━━━━━━━┻━━━━━━━━━━━━┻━━━━━━━━━━━━┻━━━━━━━━━━━━┻━━━━━━━━━━━━┻━━━━━━━━━━━━┻━━━━━━━━━━━━┻━━━━━━━━━━━━┻━━━━━┛", ), ( 150, "┏━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━┓\n\ ┃ xxxxxxxxxxxxx... ┃ xxxxxxx... ┃ xxxxxxx... ┃ xxxxxxx... ┃ xxxxxxx... ┃ xxxxxxx... ┃ xxxxxxx... ┃ xxxxxxx... ┃ xxxxxxx... ┃ xxxxxxx... ┃ ... ┃\n\ ┣━━━━━━━━━━━━━━━━━━╋━━━━━━━━━━━━╋━━━━━━━━━━━━╋━━━━━━━━━━━━╋━━━━━━━━━━━━╋━━━━━━━━━━━━╋━━━━━━━━━━━━╋━━━━━━━━━━━━╋━━━━━━━━━━━━╋━━━━━━━━━━━━╋━━━━━┫\n\ ┃ yyyyyyyyyyyyy... ┃ yyyyyyy... ┃ yyyyyyy... ┃ yyyyyyy... ┃ yyyyyyy... ┃ yyyyyyy... ┃ yyyyyyy... ┃ yyyyyyy... ┃ yyyyyyy... ┃ yyyyyyy... ┃ ... ┃\n\ ┃ zzzzzzzzzzzzz... ┃ zzzzzzz... ┃ zzzzzzz... ┃ zzzzzzz... ┃ zzzzzzz... ┃ zzzzzzz... ┃ zzzzzzz... ┃ zzzzzzz... ┃ zzzzzzz... ┃ zzzzzzz... ┃ ... ┃\n\ ┗━━━━━━━━━━━━━━━━━━┻━━━━━━━━━━━━┻━━━━━━━━━━━━┻━━━━━━━━━━━━┻━━━━━━━━━━━━┻━━━━━━━━━━━━┻━━━━━━━━━━━━┻━━━━━━━━━━━━┻━━━━━━━━━━━━┻━━━━━━━━━━━━┻━━━━━┛", ), ( usize::MAX, "┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n\ ┃ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ┃ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ┃ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ┃ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ┃ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ┃ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ┃ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ┃ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ┃ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ┃ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ┃ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ┃ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ┃ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ┃ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ┃ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ┃ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ┃\n\
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
true
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-table/tests/style.rs
crates/nu-table/tests/style.rs
mod common; use common::{TestCase, create_row as row}; use nu_table::{NuTable, TableTheme as theme}; use tabled::grid::records::vec_records::Text; #[test] fn test_rounded() { assert_eq!( create_table(vec![row(4); 3], true, theme::rounded()), "╭───┬───┬───┬───╮\n\ │ 0 │ 1 │ 2 │ 3 │\n\ ├───┼───┼───┼───┤\n\ │ 0 │ 1 │ 2 │ 3 │\n\ │ 0 │ 1 │ 2 │ 3 │\n\ ╰───┴───┴───┴───╯" ); assert_eq!( create_table(vec![row(4); 2], true, theme::rounded()), "╭───┬───┬───┬───╮\n\ │ 0 │ 1 │ 2 │ 3 │\n\ ├───┼───┼───┼───┤\n\ │ 0 │ 1 │ 2 │ 3 │\n\ ╰───┴───┴───┴───╯" ); assert_eq!( create_table(vec![row(4); 1], true, theme::rounded()), "╭───┬───┬───┬───╮\n\ │ 0 │ 1 │ 2 │ 3 │\n\ ╰───┴───┴───┴───╯" ); assert_eq!( create_table(vec![row(4); 1], false, theme::rounded()), "╭───┬───┬───┬───╮\n\ │ 0 │ 1 │ 2 │ 3 │\n\ ╰───┴───┴───┴───╯" ); assert_eq!( create_table(vec![row(4); 2], false, theme::rounded()), "╭───┬───┬───┬───╮\n\ │ 0 │ 1 │ 2 │ 3 │\n\ │ 0 │ 1 │ 2 │ 3 │\n\ ╰───┴───┴───┴───╯" ); assert_eq!(create_table_with_size(vec![], true, theme::rounded()), ""); } #[test] fn test_basic() { assert_eq!( create_table(vec![row(4); 3], true, theme::basic()), "+---+---+---+---+\n\ | 0 | 1 | 2 | 3 |\n\ +---+---+---+---+\n\ | 0 | 1 | 2 | 3 |\n\ +---+---+---+---+\n\ | 0 | 1 | 2 | 3 |\n\ +---+---+---+---+" ); assert_eq!( create_table(vec![row(4); 2], true, theme::basic()), "+---+---+---+---+\n\ | 0 | 1 | 2 | 3 |\n\ +---+---+---+---+\n\ | 0 | 1 | 2 | 3 |\n\ +---+---+---+---+" ); assert_eq!( create_table(vec![row(4); 1], true, theme::basic()), "+---+---+---+---+\n\ | 0 | 1 | 2 | 3 |\n\ +---+---+---+---+" ); assert_eq!( create_table(vec![row(4); 1], false, theme::basic()), "+---+---+---+---+\n\ | 0 | 1 | 2 | 3 |\n\ +---+---+---+---+" ); assert_eq!( create_table(vec![row(4); 2], false, theme::basic()), "+---+---+---+---+\n\ | 0 | 1 | 2 | 3 |\n\ +---+---+---+---+\n\ | 0 | 1 | 2 | 3 |\n\ +---+---+---+---+" ); assert_eq!(create_table_with_size(vec![], true, theme::basic()), ""); } #[test] fn test_reinforced() { assert_eq!( create_table(vec![row(4); 3], true, theme::reinforced()), "┏───┬───┬───┬───┓\n\ │ 0 │ 1 │ 2 │ 3 │\n\ │ 0 │ 1 │ 2 │ 3 │\n\ │ 0 │ 1 │ 2 │ 3 │\n\ ┗───┴───┴───┴───┛" ); assert_eq!( create_table(vec![row(4); 2], true, theme::reinforced()), "┏───┬───┬───┬───┓\n\ │ 0 │ 1 │ 2 │ 3 │\n\ │ 0 │ 1 │ 2 │ 3 │\n\ ┗───┴───┴───┴───┛" ); assert_eq!( create_table(vec![row(4); 1], true, theme::reinforced()), "┏───┬───┬───┬───┓\n\ │ 0 │ 1 │ 2 │ 3 │\n\ ┗───┴───┴───┴───┛" ); assert_eq!( create_table(vec![row(4); 1], false, theme::reinforced()), "┏───┬───┬───┬───┓\n\ │ 0 │ 1 │ 2 │ 3 │\n\ ┗───┴───┴───┴───┛" ); assert_eq!( create_table(vec![row(4); 2], false, theme::reinforced()), "┏───┬───┬───┬───┓\n\ │ 0 │ 1 │ 2 │ 3 │\n\ │ 0 │ 1 │ 2 │ 3 │\n\ ┗───┴───┴───┴───┛" ); assert_eq!( create_table_with_size(vec![], true, theme::reinforced()), "" ); } #[test] fn test_compact() { assert_eq!( create_table(vec![row(4); 3], true, theme::compact()), concat!( "───┬───┬───┬───\n", " 0 │ 1 │ 2 │ 3 \n", "───┼───┼───┼───\n", " 0 │ 1 │ 2 │ 3 \n", " 0 │ 1 │ 2 │ 3 \n", "───┴───┴───┴───", ) ); assert_eq!( create_table(vec![row(4); 2], true, theme::compact()), concat!( "───┬───┬───┬───\n", " 0 │ 1 │ 2 │ 3 \n", "───┼───┼───┼───\n", " 0 │ 1 │ 2 │ 3 \n", "───┴───┴───┴───", ) ); assert_eq!( create_table(vec![row(4); 1], true, theme::compact()), concat!("───┬───┬───┬───\n", " 0 │ 1 │ 2 │ 3 \n", "───┴───┴───┴───",) ); assert_eq!( create_table(vec![row(4); 1], false, theme::compact()), concat!("───┬───┬───┬───\n", " 0 │ 1 │ 2 │ 3 \n", "───┴───┴───┴───",) ); assert_eq!( create_table(vec![row(4); 2], false, theme::compact()), concat!( "───┬───┬───┬───\n", " 0 │ 1 │ 2 │ 3 \n", " 0 │ 1 │ 2 │ 3 \n", "───┴───┴───┴───", ) ); assert_eq!(create_table_with_size(vec![], true, theme::compact()), ""); } #[test] fn test_compact_double() { assert_eq!( create_table(vec![row(4); 3], true, theme::compact_double()), concat!( "═══╦═══╦═══╦═══\n", " 0 ║ 1 ║ 2 ║ 3 \n", "═══╬═══╬═══╬═══\n", " 0 ║ 1 ║ 2 ║ 3 \n", " 0 ║ 1 ║ 2 ║ 3 \n", "═══╩═══╩═══╩═══", ) ); assert_eq!( create_table(vec![row(4); 2], true, theme::compact_double()), concat!( "═══╦═══╦═══╦═══\n", " 0 ║ 1 ║ 2 ║ 3 \n", "═══╬═══╬═══╬═══\n", " 0 ║ 1 ║ 2 ║ 3 \n", "═══╩═══╩═══╩═══", ) ); assert_eq!( create_table(vec![row(4); 1], true, theme::compact_double()), concat!("═══╦═══╦═══╦═══\n", " 0 ║ 1 ║ 2 ║ 3 \n", "═══╩═══╩═══╩═══",) ); assert_eq!( create_table(vec![row(4); 1], false, theme::compact_double()), concat!("═══╦═══╦═══╦═══\n", " 0 ║ 1 ║ 2 ║ 3 \n", "═══╩═══╩═══╩═══",) ); assert_eq!( create_table(vec![row(4); 2], false, theme::compact_double()), concat!( "═══╦═══╦═══╦═══\n", " 0 ║ 1 ║ 2 ║ 3 \n", " 0 ║ 1 ║ 2 ║ 3 \n", "═══╩═══╩═══╩═══", ) ); assert_eq!( create_table_with_size(vec![], true, theme::compact_double()), "" ); } #[test] fn test_heavy() { assert_eq!( create_table(vec![row(4); 3], true, theme::heavy()), "┏━━━┳━━━┳━━━┳━━━┓\n\ ┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃\n\ ┣━━━╋━━━╋━━━╋━━━┫\n\ ┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃\n\ ┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃\n\ ┗━━━┻━━━┻━━━┻━━━┛" ); assert_eq!( create_table(vec![row(4); 2], true, theme::heavy()), "┏━━━┳━━━┳━━━┳━━━┓\n\ ┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃\n\ ┣━━━╋━━━╋━━━╋━━━┫\n\ ┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃\n\ ┗━━━┻━━━┻━━━┻━━━┛" ); assert_eq!( create_table(vec![row(4); 1], true, theme::heavy()), "┏━━━┳━━━┳━━━┳━━━┓\n\ ┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃\n\ ┗━━━┻━━━┻━━━┻━━━┛" ); assert_eq!( create_table(vec![row(4); 1], false, theme::heavy()), "┏━━━┳━━━┳━━━┳━━━┓\n\ ┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃\n\ ┗━━━┻━━━┻━━━┻━━━┛" ); assert_eq!( create_table(vec![row(4); 2], false, theme::heavy()), "┏━━━┳━━━┳━━━┳━━━┓\n\ ┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃\n\ ┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃\n\ ┗━━━┻━━━┻━━━┻━━━┛" ); assert_eq!(create_table_with_size(vec![], true, theme::heavy()), ""); } #[test] fn test_light() { assert_eq!( create_table(vec![row(4); 3], true, theme::light()), concat!( " 0 1 2 3 \n", "───────────────\n", " 0 1 2 3 \n", " 0 1 2 3 ", ) ); assert_eq!( create_table(vec![row(4); 2], true, theme::light()), concat!(" 0 1 2 3 \n", "───────────────\n", " 0 1 2 3 ") ); assert_eq!( create_table(vec![row(4); 1], true, theme::light()), " 0 1 2 3 " ); assert_eq!( create_table(vec![row(4); 1], false, theme::light()), " 0 1 2 3 " ); assert_eq!( create_table(vec![row(4); 2], false, theme::light()), concat!(" 0 1 2 3 \n", " 0 1 2 3 ") ); assert_eq!(create_table_with_size(vec![], true, theme::light()), ""); } #[test] fn test_none() { assert_eq!( create_table(vec![row(4); 3], true, theme::none()), concat!(" 0 1 2 3 \n", " 0 1 2 3 \n", " 0 1 2 3 ") ); assert_eq!( create_table(vec![row(4); 2], true, theme::none()), concat!(" 0 1 2 3 \n", " 0 1 2 3 ") ); assert_eq!( create_table(vec![row(4); 1], true, theme::none()), " 0 1 2 3 " ); assert_eq!( create_table(vec![row(4); 1], false, theme::none()), " 0 1 2 3 " ); assert_eq!( create_table(vec![row(4); 2], true, theme::none()), concat!(" 0 1 2 3 \n", " 0 1 2 3 ") ); assert_eq!(create_table_with_size(vec![], true, theme::none()), ""); } #[test] fn test_thin() { assert_eq!( create_table(vec![row(4); 3], true, theme::thin()), "┌───┬───┬───┬───┐\n\ │ 0 │ 1 │ 2 │ 3 │\n\ ├───┼───┼───┼───┤\n\ │ 0 │ 1 │ 2 │ 3 │\n\ ├───┼───┼───┼───┤\n\ │ 0 │ 1 │ 2 │ 3 │\n\ └───┴───┴───┴───┘" ); assert_eq!( create_table(vec![row(4); 2], true, theme::thin()), "┌───┬───┬───┬───┐\n\ │ 0 │ 1 │ 2 │ 3 │\n\ ├───┼───┼───┼───┤\n\ │ 0 │ 1 │ 2 │ 3 │\n\ └───┴───┴───┴───┘" ); assert_eq!( create_table(vec![row(4); 1], true, theme::thin()), "┌───┬───┬───┬───┐\n\ │ 0 │ 1 │ 2 │ 3 │\n\ └───┴───┴───┴───┘" ); assert_eq!( create_table(vec![row(4); 1], false, theme::thin()), "┌───┬───┬───┬───┐\n\ │ 0 │ 1 │ 2 │ 3 │\n\ └───┴───┴───┴───┘" ); assert_eq!( create_table(vec![row(4); 2], false, theme::thin()), "┌───┬───┬───┬───┐\n\ │ 0 │ 1 │ 2 │ 3 │\n\ ├───┼───┼───┼───┤\n\ │ 0 │ 1 │ 2 │ 3 │\n\ └───┴───┴───┴───┘" ); assert_eq!(create_table_with_size(vec![], true, theme::thin()), ""); } #[test] fn test_with_love() { assert_eq!( create_table(vec![row(4); 3], true, theme::with_love()), concat!( "❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤\n", " 0 ❤ 1 ❤ 2 ❤ 3 \n", "❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤\n", " 0 ❤ 1 ❤ 2 ❤ 3 \n", " 0 ❤ 1 ❤ 2 ❤ 3 \n", "❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤", ) ); assert_eq!( create_table(vec![row(4); 2], true, theme::with_love()), concat!( "❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤\n", " 0 ❤ 1 ❤ 2 ❤ 3 \n", "❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤\n", " 0 ❤ 1 ❤ 2 ❤ 3 \n", "❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤", ) ); assert_eq!( create_table(vec![row(4); 1], true, theme::with_love()), concat!("❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤\n", " 0 ❤ 1 ❤ 2 ❤ 3 \n", "❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤",) ); assert_eq!( create_table(vec![row(4); 1], false, theme::with_love()), concat!("❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤\n", " 0 ❤ 1 ❤ 2 ❤ 3 \n", "❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤",) ); assert_eq!( create_table(vec![row(4); 2], false, theme::with_love()), concat!( "❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤\n", " 0 ❤ 1 ❤ 2 ❤ 3 \n", " 0 ❤ 1 ❤ 2 ❤ 3 \n", "❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤", ) ); assert_eq!(create_table_with_size(vec![], true, theme::with_love()), ""); } #[test] fn test_single() { assert_eq!( create_table(vec![row(4); 3], true, theme::single()), "┌───┬───┬───┬───┐\n\ │ 0 │ 1 │ 2 │ 3 │\n\ ├───┼───┼───┼───┤\n\ │ 0 │ 1 │ 2 │ 3 │\n\ │ 0 │ 1 │ 2 │ 3 │\n\ └───┴───┴───┴───┘" ); assert_eq!( create_table(vec![row(4); 2], true, theme::single()), "┌───┬───┬───┬───┐\n\ │ 0 │ 1 │ 2 │ 3 │\n\ ├───┼───┼───┼───┤\n\ │ 0 │ 1 │ 2 │ 3 │\n\ └───┴───┴───┴───┘" ); assert_eq!( create_table(vec![row(4); 1], true, theme::single()), "┌───┬───┬───┬───┐\n\ │ 0 │ 1 │ 2 │ 3 │\n\ └───┴───┴───┴───┘" ); assert_eq!( create_table(vec![row(4); 1], false, theme::single()), "┌───┬───┬───┬───┐\n\ │ 0 │ 1 │ 2 │ 3 │\n\ └───┴───┴───┴───┘" ); assert_eq!( create_table(vec![row(4); 2], false, theme::single()), "┌───┬───┬───┬───┐\n\ │ 0 │ 1 │ 2 │ 3 │\n\ │ 0 │ 1 │ 2 │ 3 │\n\ └───┴───┴───┴───┘" ); assert_eq!(create_table_with_size(vec![], true, theme::single()), ""); } #[test] fn test_double() { assert_eq!( create_table(vec![row(4); 3], true, theme::double()), "╔═══╦═══╦═══╦═══╗\n\ ║ 0 ║ 1 ║ 2 ║ 3 ║\n\ ╠═══╬═══╬═══╬═══╣\n\ ║ 0 ║ 1 ║ 2 ║ 3 ║\n\ ║ 0 ║ 1 ║ 2 ║ 3 ║\n\ ╚═══╩═══╩═══╩═══╝" ); assert_eq!( create_table(vec![row(4); 2], true, theme::double()), "╔═══╦═══╦═══╦═══╗\n\ ║ 0 ║ 1 ║ 2 ║ 3 ║\n\ ╠═══╬═══╬═══╬═══╣\n\ ║ 0 ║ 1 ║ 2 ║ 3 ║\n\ ╚═══╩═══╩═══╩═══╝" ); assert_eq!( create_table(vec![row(4); 1], true, theme::double()), "╔═══╦═══╦═══╦═══╗\n\ ║ 0 ║ 1 ║ 2 ║ 3 ║\n\ ╚═══╩═══╩═══╩═══╝" ); assert_eq!( create_table(vec![row(4); 1], false, theme::double()), "╔═══╦═══╦═══╦═══╗\n\ ║ 0 ║ 1 ║ 2 ║ 3 ║\n\ ╚═══╩═══╩═══╩═══╝" ); assert_eq!( create_table(vec![row(4); 2], false, theme::double()), "╔═══╦═══╦═══╦═══╗\n\ ║ 0 ║ 1 ║ 2 ║ 3 ║\n\ ║ 0 ║ 1 ║ 2 ║ 3 ║\n\ ╚═══╩═══╩═══╩═══╝" ); assert_eq!(create_table_with_size(vec![], true, theme::double()), ""); } fn create_table(data: Vec<Vec<Text<String>>>, with_header: bool, theme: theme) -> String { let mut case = TestCase::new(usize::MAX).theme(theme); if with_header { case = case.header(); } common::create_table(data, case).expect("not expected to get None") } fn create_table_with_size(data: Vec<Vec<Text<String>>>, with_header: bool, theme: theme) -> String { let mut table = NuTable::from(data); table.set_theme(theme); table.set_structure(false, with_header, false); table.draw(usize::MAX).expect("not expected to get None") }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-table/tests/common.rs
crates/nu-table/tests/common.rs
#![allow(dead_code)] use nu_protocol::TrimStrategy; use nu_table::{NuTable, TableTheme, string_width}; use tabled::grid::records::vec_records::Text; #[derive(Debug, Clone)] pub struct TestCase { theme: TableTheme, with_header: bool, with_footer: bool, with_index: bool, expand: bool, strategy: TrimStrategy, termwidth: usize, expected: Option<String>, } impl TestCase { pub fn new(termwidth: usize) -> Self { Self { termwidth, expected: None, theme: TableTheme::basic(), with_header: false, with_footer: false, with_index: false, expand: false, strategy: TrimStrategy::truncate(None), } } pub fn expected(mut self, value: Option<String>) -> Self { self.expected = value; self } pub fn theme(mut self, theme: TableTheme) -> Self { self.theme = theme; self } pub fn expand(mut self) -> Self { self.expand = true; self } pub fn header(mut self) -> Self { self.with_header = true; self } pub fn footer(mut self) -> Self { self.with_footer = true; self } pub fn index(mut self) -> Self { self.with_index = true; self } pub fn trim(mut self, trim: TrimStrategy) -> Self { self.strategy = trim; self } } type Data = Vec<Vec<Text<String>>>; pub fn test_table<I>(data: Data, tests: I) where I: IntoIterator<Item = TestCase>, { for (i, test) in tests.into_iter().enumerate() { let actual = create_table(data.clone(), test.clone()); assert_eq!( actual, test.expected, "\nfail i={:?} termwidth={}", i, test.termwidth ); if let Some(table) = actual { assert!(string_width(&table) <= test.termwidth); } } } pub fn create_table(data: Data, case: TestCase) -> Option<String> { let count_rows = data.len(); let count_cols = data[0].len(); let mut table = NuTable::new(count_rows, count_cols); for (i, row) in data.into_iter().enumerate() { table.set_row(i, row); } table.set_theme(case.theme); table.set_structure(case.with_index, case.with_header, case.with_footer); table.set_trim(case.strategy); table.set_strategy(case.expand); table.draw(case.termwidth) } pub fn create_row(count_columns: usize) -> Vec<Text<String>> { let mut row = Vec::with_capacity(count_columns); for i in 0..count_columns { row.push(Text::new(i.to_string())); } row } pub fn cell(text: &str) -> Text<String> { Text::new(text.to_string()) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-table/examples/table_demo.rs
crates/nu-table/examples/table_demo.rs
use nu_ansi_term::{Color, Style}; use nu_color_config::TextStyle; use nu_table::{NuTable, TableTheme}; use tabled::grid::records::vec_records::Text; fn main() { let args: Vec<_> = std::env::args().collect(); let mut width = 0; if args.len() > 1 { width = args[1].parse::<usize>().expect("Need a width in columns"); } if width < 4 { println!("Width must be greater than or equal to 4, setting width to 80"); width = 80; } let (table_headers, row_data) = make_table_data(); let headers = to_cell_info_vec(&table_headers); let rows = to_cell_info_vec(&row_data); let mut table = NuTable::new(4, 3); table.set_row(0, headers); for i in 0..3 { table.set_row(i + 1, rows.clone()); } table.set_data_style(TextStyle::basic_left()); table.set_header_style(TextStyle::basic_center().style(Style::new().on(Color::Blue))); table.set_theme(TableTheme::rounded()); table.set_structure(false, true, false); let output_table = table .draw(width) .unwrap_or_else(|| format!("Couldn't fit table into {width} columns!")); println!("{output_table}") } fn make_table_data() -> (Vec<&'static str>, Vec<&'static str>) { let table_headers = vec![ "category", "description", "emoji", "ios_version", "unicode_version", "aliases", "tags", "category2", "description2", "emoji2", "ios_version2", "unicode_version2", "aliases2", "tags2", ]; let row_data = vec![ "Smileys & Emotion", "grinning face", "😀", "6", "6.1", "grinning", "smile", "Smileys & Emotion", "grinning face", "😀", "6", "6.1", "grinning", "smile", ]; (table_headers, row_data) } fn to_cell_info_vec(data: &[&str]) -> Vec<Text<String>> { let mut v = vec![]; for x in data { v.push(Text::new(String::from(*x))); } v }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-path/src/path.rs
crates/nu-path/src/path.rs
use crate::form::{ Absolute, Any, Canonical, IsAbsolute, MaybeRelative, PathCast, PathForm, PathJoin, PathPush, PathSet, Relative, }; use ref_cast::{RefCastCustom, ref_cast_custom}; use std::{ borrow::{Borrow, Cow}, cmp::Ordering, collections::TryReserveError, convert::Infallible, ffi::{OsStr, OsString}, fmt, fs, hash::{Hash, Hasher}, io, iter::FusedIterator, marker::PhantomData, ops::{Deref, DerefMut}, path::StripPrefixError, rc::Rc, str::FromStr, sync::Arc, }; /// A wrapper around [`std::path::Path`] with extra invariants determined by its `Form`. /// /// The possible path forms are [`Any`], [`Relative`], [`Absolute`], or [`Canonical`]. /// To learn more, view the documentation on [`PathForm`] or any of the individual forms. /// /// There are also several type aliases available, corresponding to each [`PathForm`]: /// - [`RelativePath`] (same as [`Path<Relative>`]) /// - [`AbsolutePath`] (same as [`Path<Absolute>`]) /// - [`CanonicalPath`] (same as [`Path<Canonical>`]) /// /// If the `Form` is not specified, then it defaults to [`Any`], so [`Path`] and [`Path<Any>`] /// are one in the same. /// /// # Converting to [`std::path`] types /// /// [`Path`]s with form [`Any`] cannot be easily referenced as a [`std::path::Path`] by design. /// Other Nushell crates need to account for the emulated current working directory /// before passing a path to functions in [`std`] or other third party crates. /// You can [`join`](Path::join) a [`Path`] onto an [`AbsolutePath`] or a [`CanonicalPath`]. /// This will return an [`AbsolutePathBuf`] which can be easily referenced as a [`std::path::Path`]. /// If you really mean it, you can instead use [`as_relative_std_path`](Path::as_relative_std_path) /// to get the underlying [`std::path::Path`] from a [`Path`]. /// But this may cause third-party code to use [`std::env::current_dir`] to resolve /// the path which is almost always incorrect behavior. Extra care is needed to ensure that this /// is not the case after using [`as_relative_std_path`](Path::as_relative_std_path). #[derive(RefCastCustom)] #[repr(transparent)] pub struct Path<Form = Any> { _form: PhantomData<Form>, inner: std::path::Path, } /// A path that is strictly relative. /// /// I.e., this path is guaranteed to never be absolute. /// /// [`RelativePath`]s cannot be easily converted into a [`std::path::Path`] by design. /// Other Nushell crates need to account for the emulated current working directory /// before passing a path to functions in [`std`] or other third party crates. /// You can [`join`](Path::join) a [`RelativePath`] onto an [`AbsolutePath`] or a [`CanonicalPath`]. /// This will return an [`AbsolutePathBuf`] which can be referenced as a [`std::path::Path`]. /// If you really mean it, you can use [`as_relative_std_path`](RelativePath::as_relative_std_path) /// to get the underlying [`std::path::Path`] from a [`RelativePath`]. /// But this may cause third-party code to use [`std::env::current_dir`] to resolve /// the path which is almost always incorrect behavior. Extra care is needed to ensure that this /// is not the case after using [`as_relative_std_path`](RelativePath::as_relative_std_path). /// /// # Examples /// /// [`RelativePath`]s can be created by using [`try_relative`](Path::try_relative) /// on a [`Path`], by using [`try_new`](Path::try_new), or by using /// [`strip_prefix`](Path::strip_prefix) on a [`Path`] of any form. /// /// ``` /// use nu_path::{Path, RelativePath}; /// /// let path1 = Path::new("foo.txt"); /// let path1 = path1.try_relative().unwrap(); /// /// let path2 = RelativePath::try_new("foo.txt").unwrap(); /// /// let path3 = Path::new("/prefix/foo.txt").strip_prefix("/prefix").unwrap(); /// /// assert_eq!(path1, path2); /// assert_eq!(path2, path3); /// ``` /// /// You can also use `RelativePath::try_from` or `try_into`. /// This supports attempted conversions from [`Path`] as well as types in [`std::path`]. /// /// ``` /// use nu_path::{Path, RelativePath}; /// /// let path1 = Path::new("foo.txt"); /// let path1: &RelativePath = path1.try_into().unwrap(); /// /// let path2 = std::path::Path::new("foo.txt"); /// let path2: &RelativePath = path2.try_into().unwrap(); /// /// assert_eq!(path1, path2) /// ``` pub type RelativePath = Path<Relative>; /// A path that is strictly absolute. /// /// I.e., this path is guaranteed to never be relative. /// /// # Examples /// /// [`AbsolutePath`]s can be created by using [`try_absolute`](Path::try_absolute) on a [`Path`] /// or by using [`try_new`](AbsolutePath::try_new). /// #[cfg_attr(not(windows), doc = "```")] #[cfg_attr(windows, doc = "```no_run")] /// use nu_path::{AbsolutePath, Path}; /// /// let path1 = Path::new("/foo").try_absolute().unwrap(); /// let path2 = AbsolutePath::try_new("/foo").unwrap(); /// /// assert_eq!(path1, path2); /// ``` /// /// You can also use `AbsolutePath::try_from` or `try_into`. /// This supports attempted conversions from [`Path`] as well as types in [`std::path`]. /// #[cfg_attr(not(windows), doc = "```")] #[cfg_attr(windows, doc = "```no_run")] /// use nu_path::{AbsolutePath, Path}; /// /// let path1 = Path::new("/foo"); /// let path1: &AbsolutePath = path1.try_into().unwrap(); /// /// let path2 = std::path::Path::new("/foo"); /// let path2: &AbsolutePath = path2.try_into().unwrap(); /// /// assert_eq!(path1, path2) /// ``` pub type AbsolutePath = Path<Absolute>; /// An absolute, canonical path. /// /// # Examples /// /// [`CanonicalPath`]s can only be created by using [`canonicalize`](Path::canonicalize) on /// an [`AbsolutePath`]. References to [`CanonicalPath`]s can be converted to /// [`AbsolutePath`] references using `as_ref`, [`cast`](Path::cast), /// or [`as_absolute`](CanonicalPath::as_absolute). /// /// ```no_run /// use nu_path::AbsolutePath; /// /// let path = AbsolutePath::try_new("/foo").unwrap(); /// /// let canonical = path.canonicalize().expect("canonicalization failed"); /// /// assert_eq!(path, canonical.as_absolute()); /// ``` pub type CanonicalPath = Path<Canonical>; impl<Form: PathForm> Path<Form> { /// Create a new path of any form without validating invariants. #[inline] fn new_unchecked<P: AsRef<OsStr> + ?Sized>(path: &P) -> &Self { #[ref_cast_custom] fn ref_cast<Form: PathForm>(path: &std::path::Path) -> &Path<Form>; debug_assert!(Form::invariants_satisfied(path)); ref_cast(std::path::Path::new(path)) } /// Attempt to create a new [`Path`] from a reference of another type. /// /// This is a convenience method instead of having to use `try_into` with a type annotation. /// /// # Examples /// /// ``` /// use nu_path::{AbsolutePath, RelativePath}; /// /// assert!(AbsolutePath::try_new("foo.txt").is_err()); /// assert!(RelativePath::try_new("foo.txt").is_ok()); /// ``` #[inline] pub fn try_new<'a, T>(path: &'a T) -> Result<&'a Self, <&'a T as TryInto<&'a Self>>::Error> where T: ?Sized, &'a T: TryInto<&'a Self>, { path.try_into() } /// Returns the underlying [`OsStr`] slice. /// /// # Examples /// /// ``` /// use nu_path::Path; /// /// let os_str = Path::new("foo.txt").as_os_str(); /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt")); /// ``` #[must_use] #[inline] pub fn as_os_str(&self) -> &OsStr { self.inner.as_os_str() } /// Returns a [`str`] slice if the [`Path`] is valid unicode. /// /// # Examples /// /// ``` /// use nu_path::Path; /// /// let path = Path::new("foo.txt"); /// assert_eq!(path.to_str(), Some("foo.txt")); /// ``` #[inline] pub fn to_str(&self) -> Option<&str> { self.inner.to_str() } /// Converts a [`Path`] to a `Cow<str>`. /// /// Any non-Unicode sequences are replaced with `U+FFFD REPLACEMENT CHARACTER`. /// /// # Examples /// /// Calling `to_string_lossy` on a [`Path`] with valid unicode: /// /// ``` /// use nu_path::Path; /// /// let path = Path::new("foo.txt"); /// assert_eq!(path.to_string_lossy(), "foo.txt"); /// ``` /// /// Had `path` contained invalid unicode, the `to_string_lossy` call might have returned /// `"fo�.txt"`. #[inline] pub fn to_string_lossy(&self) -> Cow<'_, str> { self.inner.to_string_lossy() } /// Converts a [`Path`] to an owned [`PathBuf`]. /// /// # Examples /// /// ``` /// use nu_path::{Path, PathBuf}; /// /// let path_buf = Path::new("foo.txt").to_path_buf(); /// assert_eq!(path_buf, PathBuf::from("foo.txt")); /// ``` #[inline] pub fn to_path_buf(&self) -> PathBuf<Form> { PathBuf::new_unchecked(self.inner.to_path_buf()) } /// Returns the [`Path`] without its final component, if there is one. /// /// This means it returns `Some("")` for relative paths with one component. /// /// Returns [`None`] if the path terminates in a root or prefix, or if it's /// the empty string. /// /// # Examples /// /// ``` /// use nu_path::Path; /// /// let path = Path::new("/foo/bar"); /// let parent = path.parent().unwrap(); /// assert_eq!(parent, Path::new("/foo")); /// /// let grand_parent = parent.parent().unwrap(); /// assert_eq!(grand_parent, Path::new("/")); /// assert_eq!(grand_parent.parent(), None); /// /// let relative_path = Path::new("foo/bar"); /// let parent = relative_path.parent(); /// assert_eq!(parent, Some(Path::new("foo"))); /// let grand_parent = parent.and_then(Path::parent); /// assert_eq!(grand_parent, Some(Path::new(""))); /// let great_grand_parent = grand_parent.and_then(Path::parent); /// assert_eq!(great_grand_parent, None); /// ``` #[must_use] #[inline] pub fn parent(&self) -> Option<&Self> { self.inner.parent().map(Self::new_unchecked) } /// Produces an iterator over a [`Path`] and its ancestors. /// /// The iterator will yield the [`Path`] that is returned if the [`parent`](Path::parent) method /// is used zero or more times. That means, the iterator will yield `&self`, /// `&self.parent().unwrap()`, `&self.parent().unwrap().parent().unwrap()` and so on. /// If the [`parent`](Path::parent) method returns [`None`], the iterator will do likewise. /// The iterator will always yield at least one value, namely `&self`. /// /// # Examples /// /// ``` /// use nu_path::Path; /// /// let mut ancestors = Path::new("/foo/bar").ancestors(); /// assert_eq!(ancestors.next(), Some(Path::new("/foo/bar"))); /// assert_eq!(ancestors.next(), Some(Path::new("/foo"))); /// assert_eq!(ancestors.next(), Some(Path::new("/"))); /// assert_eq!(ancestors.next(), None); /// /// let mut ancestors = Path::new("../foo/bar").ancestors(); /// assert_eq!(ancestors.next(), Some(Path::new("../foo/bar"))); /// assert_eq!(ancestors.next(), Some(Path::new("../foo"))); /// assert_eq!(ancestors.next(), Some(Path::new(".."))); /// assert_eq!(ancestors.next(), Some(Path::new(""))); /// assert_eq!(ancestors.next(), None); /// ``` #[inline] pub fn ancestors(&self) -> Ancestors<'_, Form> { Ancestors { _form: PhantomData, inner: self.inner.ancestors(), } } /// Returns the final component of a [`Path`], if there is one. /// /// If the path is a normal file, this is the file name. If it's the path of a directory, this /// is the directory name. /// /// Returns [`None`] if the path terminates in `..`. /// /// # Examples /// /// ``` /// use nu_path::Path; /// use std::ffi::OsStr; /// /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name()); /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name()); /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name()); /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name()); /// assert_eq!(None, Path::new("foo.txt/..").file_name()); /// assert_eq!(None, Path::new("/").file_name()); /// ``` #[must_use] #[inline] pub fn file_name(&self) -> Option<&OsStr> { self.inner.file_name() } /// Returns a relative path that, when joined onto `base`, yields `self`. /// /// # Examples /// /// ``` /// use nu_path::{Path, PathBuf}; /// /// let path = Path::new("/test/haha/foo.txt"); /// /// assert_eq!(path.strip_prefix("/").unwrap(), Path::new("test/haha/foo.txt")); /// assert_eq!(path.strip_prefix("/test").unwrap(), Path::new("haha/foo.txt")); /// assert_eq!(path.strip_prefix("/test/").unwrap(), Path::new("haha/foo.txt")); /// assert_eq!(path.strip_prefix("/test/haha/foo.txt").unwrap(), Path::new("")); /// assert_eq!(path.strip_prefix("/test/haha/foo.txt/").unwrap(), Path::new("")); /// /// assert!(path.strip_prefix("test").is_err()); /// assert!(path.strip_prefix("/haha").is_err()); /// /// let prefix = PathBuf::from("/test/"); /// assert_eq!(path.strip_prefix(prefix).unwrap(), Path::new("haha/foo.txt")); /// ``` #[inline] pub fn strip_prefix(&self, base: impl AsRef<Path>) -> Result<&RelativePath, StripPrefixError> { self.inner .strip_prefix(&base.as_ref().inner) .map(RelativePath::new_unchecked) } /// Determines whether `base` is a prefix of `self`. /// /// Only considers whole path components to match. /// /// # Examples /// /// ``` /// use nu_path::Path; /// /// let path = Path::new("/etc/passwd"); /// /// assert!(path.starts_with("/etc")); /// assert!(path.starts_with("/etc/")); /// assert!(path.starts_with("/etc/passwd")); /// assert!(path.starts_with("/etc/passwd/")); // extra slash is okay /// assert!(path.starts_with("/etc/passwd///")); // multiple extra slashes are okay /// /// assert!(!path.starts_with("/e")); /// assert!(!path.starts_with("/etc/passwd.txt")); /// /// assert!(!Path::new("/etc/foo.rs").starts_with("/etc/foo")); /// ``` #[must_use] #[inline] pub fn starts_with(&self, base: impl AsRef<Path>) -> bool { self.inner.starts_with(&base.as_ref().inner) } /// Determines whether `child` is a suffix of `self`. /// /// Only considers whole path components to match. /// /// # Examples /// /// ``` /// use nu_path::Path; /// /// let path = Path::new("/etc/resolv.conf"); /// /// assert!(path.ends_with("resolv.conf")); /// assert!(path.ends_with("etc/resolv.conf")); /// assert!(path.ends_with("/etc/resolv.conf")); /// /// assert!(!path.ends_with("/resolv.conf")); /// assert!(!path.ends_with("conf")); // use .extension() instead /// ``` #[must_use] #[inline] pub fn ends_with(&self, child: impl AsRef<Path>) -> bool { self.inner.ends_with(&child.as_ref().inner) } /// Extracts the stem (non-extension) portion of [`self.file_name`](Path::file_name). /// /// The stem is: /// /// * [`None`], if there is no file name; /// * The entire file name if there is no embedded `.`; /// * The entire file name if the file name begins with `.` and has no other `.`s within; /// * Otherwise, the portion of the file name before the final `.` /// /// # Examples /// /// ``` /// use nu_path::Path; /// /// assert_eq!("foo", Path::new("foo.rs").file_stem().unwrap()); /// assert_eq!("foo.tar", Path::new("foo.tar.gz").file_stem().unwrap()); /// ``` #[must_use] #[inline] pub fn file_stem(&self) -> Option<&OsStr> { self.inner.file_stem() } /// Extracts the extension (without the leading dot) of [`self.file_name`](Path::file_name), /// if possible. /// /// The extension is: /// /// * [`None`], if there is no file name; /// * [`None`], if there is no embedded `.`; /// * [`None`], if the file name begins with `.` and has no other `.`s within; /// * Otherwise, the portion of the file name after the final `.` /// /// # Examples /// /// ``` /// use nu_path::Path; /// /// assert_eq!("rs", Path::new("foo.rs").extension().unwrap()); /// assert_eq!("gz", Path::new("foo.tar.gz").extension().unwrap()); /// ``` #[must_use] #[inline] pub fn extension(&self) -> Option<&OsStr> { self.inner.extension() } /// Produces an iterator over the [`Component`](std::path::Component)s of the path. /// /// When parsing the path, there is a small amount of normalization: /// /// * Repeated separators are ignored, so `a/b` and `a//b` both have /// `a` and `b` as components. /// /// * Occurrences of `.` are normalized away, except if they are at the /// beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and /// `a/b` all have `a` and `b` as components, but `./a/b` starts with /// an additional [`CurDir`](std::path::Component) component. /// /// * A trailing slash is normalized away, `/a/b` and `/a/b/` are equivalent. /// /// Note that no other normalization takes place; in particular, `a/c` /// and `a/b/../c` are distinct, to account for the possibility that `b` /// is a symbolic link (so its parent isn't `a`). /// /// # Examples /// /// ``` /// use nu_path::Path; /// use std::path::Component; /// use std::ffi::OsStr; /// /// let mut components = Path::new("/tmp/foo.txt").components(); /// /// assert_eq!(components.next(), Some(Component::RootDir)); /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp")))); /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt")))); /// assert_eq!(components.next(), None) /// ``` #[inline] pub fn components(&self) -> std::path::Components<'_> { self.inner.components() } /// Produces an iterator over the path's components viewed as [`OsStr`] slices. /// /// For more information about the particulars of how the path is separated into components, /// see [`components`](Path::components). /// /// # Examples /// /// ``` /// use nu_path::Path; /// use std::ffi::OsStr; /// /// let mut it = Path::new("/tmp/foo.txt").iter(); /// assert_eq!(it.next(), Some(OsStr::new(&std::path::MAIN_SEPARATOR.to_string()))); /// assert_eq!(it.next(), Some(OsStr::new("tmp"))); /// assert_eq!(it.next(), Some(OsStr::new("foo.txt"))); /// assert_eq!(it.next(), None) /// ``` #[inline] pub fn iter(&self) -> std::path::Iter<'_> { self.inner.iter() } /// Returns an object that implements [`Display`](fmt::Display) for safely printing paths /// that may contain non-Unicode data. This may perform lossy conversion, /// depending on the platform. If you would like an implementation which escapes the path /// please use [`Debug`](fmt::Debug) instead. /// /// # Examples /// /// ``` /// use nu_path::Path; /// /// let path = Path::new("/tmp/foo.rs"); /// /// println!("{}", path.display()); /// ``` #[inline] pub fn display(&self) -> std::path::Display<'_> { self.inner.display() } /// Converts a [`Box<Path>`](Box) into a [`PathBuf`] without copying or allocating. #[inline] pub fn into_path_buf(self: Box<Self>) -> PathBuf<Form> { // Safety: `Path<Form>` is a repr(transparent) wrapper around `std::path::Path`. let ptr = Box::into_raw(self) as *mut std::path::Path; let boxed = unsafe { Box::from_raw(ptr) }; PathBuf::new_unchecked(boxed.into_path_buf()) } /// Returns a reference to the same [`Path`] in a different form. /// /// [`PathForm`]s can be converted to one another based on [`PathCast`] implementations. /// Namely, the following form conversions are possible: /// - [`Relative`], [`Absolute`], or [`Canonical`] into [`Any`]. /// - [`Canonical`] into [`Absolute`]. /// - Any form into itself. /// /// # Examples /// /// ``` /// use nu_path::{Path, RelativePath}; /// /// let relative = RelativePath::try_new("test.txt").unwrap(); /// let p: &Path = relative.cast(); /// assert_eq!(p, relative); /// ``` #[inline] pub fn cast<To>(&self) -> &Path<To> where To: PathForm, Form: PathCast<To>, { Path::new_unchecked(self) } /// Returns a reference to a path with its form as [`Any`]. /// /// # Examples /// /// ``` /// use nu_path::{Path, RelativePath}; /// /// let p = RelativePath::try_new("test.txt").unwrap(); /// assert_eq!(Path::new("test.txt"), p.as_any()); /// ``` #[inline] pub fn as_any(&self) -> &Path { Path::new_unchecked(self) } } impl Path { /// Create a new [`Path`] by wrapping a string slice. /// /// This is a cost-free conversion. /// /// # Examples /// /// ``` /// use nu_path::Path; /// /// Path::new("foo.txt"); /// ``` /// /// You can create [`Path`]s from [`String`]s, or even other [`Path`]s: /// /// ``` /// use nu_path::Path; /// /// let string = String::from("foo.txt"); /// let from_string = Path::new(&string); /// let from_path = Path::new(&from_string); /// assert_eq!(from_string, from_path); /// ``` #[inline] pub fn new<P: AsRef<OsStr> + ?Sized>(path: &P) -> &Self { Self::new_unchecked(path) } /// Returns a mutable reference to the underlying [`OsStr`] slice. /// /// # Examples /// /// ``` /// use nu_path::{Path, PathBuf}; /// /// let mut path = PathBuf::from("Foo.TXT"); /// /// assert_ne!(path, Path::new("foo.txt")); /// /// path.as_mut_os_str().make_ascii_lowercase(); /// assert_eq!(path, Path::new("foo.txt")); /// ``` #[must_use] #[inline] pub fn as_mut_os_str(&mut self) -> &mut OsStr { self.inner.as_mut_os_str() } /// Returns `true` if the [`Path`] is absolute, i.e., if it is independent of /// the current directory. /// /// * On Unix, a path is absolute if it starts with the root, /// so [`is_absolute`](Path::is_absolute) and [`has_root`](Path::has_root) are equivalent. /// /// * On Windows, a path is absolute if it has a prefix and starts with the root: /// `c:\windows` is absolute, while `c:temp` and `\temp` are not. /// /// # Examples /// /// ``` /// use nu_path::Path; /// /// assert!(!Path::new("foo.txt").is_absolute()); /// ``` #[must_use] #[inline] pub fn is_absolute(&self) -> bool { self.inner.is_absolute() } // Returns `true` if the [`Path`] is relative, i.e., not absolute. /// /// See [`is_absolute`](Path::is_absolute)'s documentation for more details. /// /// # Examples /// /// ``` /// use nu_path::Path; /// /// assert!(Path::new("foo.txt").is_relative()); /// ``` #[must_use] #[inline] pub fn is_relative(&self) -> bool { self.inner.is_relative() } /// Returns an `Ok` [`AbsolutePath`] if the [`Path`] is absolute. /// Otherwise, returns an `Err` [`RelativePath`]. /// /// # Examples /// /// ``` /// use nu_path::Path; /// /// assert!(Path::new("test.txt").try_absolute().is_err()); /// ``` #[inline] pub fn try_absolute(&self) -> Result<&AbsolutePath, &RelativePath> { if self.is_absolute() { Ok(AbsolutePath::new_unchecked(&self.inner)) } else { Err(RelativePath::new_unchecked(&self.inner)) } } /// Returns an `Ok` [`RelativePath`] if the [`Path`] is relative. /// Otherwise, returns an `Err` [`AbsolutePath`]. /// /// # Examples /// /// ``` /// use nu_path::Path; /// /// assert!(Path::new("test.txt").try_relative().is_ok()); /// ``` #[inline] pub fn try_relative(&self) -> Result<&RelativePath, &AbsolutePath> { if self.is_relative() { Ok(RelativePath::new_unchecked(&self.inner)) } else { Err(AbsolutePath::new_unchecked(&self.inner)) } } } impl<Form: PathJoin> Path<Form> { /// Creates an owned [`PathBuf`] with `path` adjoined to `self`. /// /// If `path` is absolute, it replaces the current path. /// /// See [`PathBuf::push`] for more details on what it means to adjoin a path. /// /// # Examples /// /// ``` /// use nu_path::{Path, PathBuf}; /// /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd")); /// assert_eq!(Path::new("/etc").join("/bin/sh"), PathBuf::from("/bin/sh")); /// ``` #[must_use] #[inline] pub fn join(&self, path: impl AsRef<Path>) -> PathBuf<Form::Output> { PathBuf::new_unchecked(self.inner.join(&path.as_ref().inner)) } } impl<Form: PathSet> Path<Form> { /// Creates an owned [`PathBuf`] like `self` but with the given file name. /// /// See [`PathBuf::set_file_name`] for more details. /// /// # Examples /// /// ``` /// use nu_path::{Path, PathBuf}; /// /// let path = Path::new("/tmp/foo.png"); /// assert_eq!(path.with_file_name("bar"), PathBuf::from("/tmp/bar")); /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt")); /// /// let path = Path::new("/tmp"); /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var")); /// ``` #[inline] pub fn with_file_name(&self, file_name: impl AsRef<OsStr>) -> PathBuf<Form> { PathBuf::new_unchecked(self.inner.with_file_name(file_name)) } /// Creates an owned [`PathBuf`] like `self` but with the given extension. /// /// See [`PathBuf::set_extension`] for more details. /// /// # Examples /// /// ``` /// use nu_path::{Path, PathBuf}; /// /// let path = Path::new("foo.rs"); /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt")); /// /// let path = Path::new("foo.tar.gz"); /// assert_eq!(path.with_extension(""), PathBuf::from("foo.tar")); /// assert_eq!(path.with_extension("xz"), PathBuf::from("foo.tar.xz")); /// assert_eq!(path.with_extension("").with_extension("txt"), PathBuf::from("foo.txt")); /// ``` #[inline] pub fn with_extension(&self, extension: impl AsRef<OsStr>) -> PathBuf<Form> { PathBuf::new_unchecked(self.inner.with_extension(extension)) } } impl<Form: MaybeRelative> Path<Form> { /// Returns the, potentially relative, underlying [`std::path::Path`]. /// /// # Note /// /// Caution should be taken when using this function. Nushell keeps track of an emulated current /// working directory, and using the [`std::path::Path`] returned from this method will likely /// use [`std::env::current_dir`] to resolve the path instead of using the emulated current /// working directory. /// /// Instead, you should probably join this path onto the emulated current working directory. /// Any [`AbsolutePath`] or [`CanonicalPath`] will also suffice. /// /// # Examples /// /// ``` /// use nu_path::Path; /// /// let p = Path::new("test.txt"); /// assert_eq!(std::path::Path::new("test.txt"), p.as_relative_std_path()); /// ``` #[inline] pub fn as_relative_std_path(&self) -> &std::path::Path { &self.inner } // Returns `true` if the [`Path`] has a root. /// /// * On Unix, a path has a root if it begins with `/`. /// /// * On Windows, a path has a root if it: /// * has no prefix and begins with a separator, e.g., `\windows` /// * has a prefix followed by a separator, e.g., `c:\windows` but not `c:windows` /// * has any non-disk prefix, e.g., `\\server\share` /// /// # Examples /// /// ``` /// use nu_path::Path; /// /// assert!(Path::new("/etc/passwd").has_root()); /// ``` #[must_use] #[inline] pub fn has_root(&self) -> bool { self.inner.has_root() } } impl<Form: IsAbsolute> Path<Form> { /// Returns the underlying [`std::path::Path`]. /// /// # Examples /// #[cfg_attr(not(windows), doc = "```")] #[cfg_attr(windows, doc = "```no_run")] /// use nu_path::AbsolutePath; /// /// let p = AbsolutePath::try_new("/test").unwrap(); /// assert_eq!(std::path::Path::new("/test"), p.as_std_path()); /// ``` #[inline] pub fn as_std_path(&self) -> &std::path::Path { &self.inner } /// Converts a [`Path`] to an owned [`std::path::PathBuf`]. /// /// # Examples /// #[cfg_attr(not(windows), doc = "```")] #[cfg_attr(windows, doc = "```no_run")] /// use nu_path::AbsolutePath; /// /// let path = AbsolutePath::try_new("/foo").unwrap(); /// assert_eq!(path.to_std_path_buf(), std::path::PathBuf::from("/foo")); /// ``` #[inline] pub fn to_std_path_buf(&self) -> std::path::PathBuf { self.inner.to_path_buf() } /// Queries the file system to get information about a file, directory, etc. /// /// This function will traverse symbolic links to query information about the destination file. /// /// This is an alias to [`std::fs::metadata`]. /// /// # Examples /// /// ```no_run /// use nu_path::AbsolutePath; /// /// let path = AbsolutePath::try_new("/Minas/tirith").unwrap(); /// let metadata = path.metadata().expect("metadata call failed"); /// println!("{:?}", metadata.file_type()); /// ``` #[inline] pub fn metadata(&self) -> io::Result<fs::Metadata> { self.inner.metadata() } /// Returns an iterator over the entries within a directory. /// /// The iterator will yield instances of <code>[io::Result]<[fs::DirEntry]></code>. /// New errors may be encountered after an iterator is initially constructed. /// /// This is an alias to [`std::fs::read_dir`]. /// /// # Examples /// /// ```no_run /// use nu_path::AbsolutePath; /// /// let path = AbsolutePath::try_new("/laputa").unwrap(); /// for entry in path.read_dir().expect("read_dir call failed") { /// if let Ok(entry) = entry { /// println!("{:?}", entry.path()); /// } /// } /// ``` #[inline] pub fn read_dir(&self) -> io::Result<fs::ReadDir> { self.inner.read_dir() } /// Returns `true` if the path points at an existing entity. /// /// Warning: this method may be error-prone, consider using [`try_exists`](Path::try_exists) /// instead! It also has a risk of introducing time-of-check to time-of-use (TOCTOU) bugs. /// /// This function will traverse symbolic links to query information about the destination file. /// /// If you cannot access the metadata of the file, e.g. because of a permission error /// or broken symbolic links, this will return `false`. /// /// # Examples /// /// ```no_run /// use nu_path::AbsolutePath; /// /// let path = AbsolutePath::try_new("/does_not_exist").unwrap(); /// assert!(!path.exists()); /// ``` #[must_use] #[inline] pub fn exists(&self) -> bool { self.inner.exists() } /// Returns `true` if the path exists on disk and is pointing at a regular file. /// /// This function will traverse symbolic links to query information about the destination file. /// /// If you cannot access the metadata of the file, e.g. because of a permission error /// or broken symbolic links, this will return `false`. /// /// # Examples /// /// ```no_run /// use nu_path::AbsolutePath; /// /// let path = AbsolutePath::try_new("/is_a_directory/").unwrap(); /// assert_eq!(path.is_file(), false); /// /// let path = AbsolutePath::try_new("/a_file.txt").unwrap(); /// assert_eq!(path.is_file(), true); /// ``` /// /// # See Also /// /// When the goal is simply to read from (or write to) the source, the most reliable way /// to test the source can be read (or written to) is to open it. Only using `is_file` can
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
true
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-path/src/lib.rs
crates/nu-path/src/lib.rs
#![doc = include_str!("../README.md")] mod assert_path_eq; mod components; pub mod dots; pub mod expansions; pub mod form; mod helpers; mod path; mod tilde; mod trailing_slash; pub use components::components; pub use expansions::{ canonicalize_with, expand_path, expand_path_with, expand_to_real_path, locate_in_dirs, }; pub use helpers::{cache_dir, data_dir, home_dir, is_windows_device_path, nu_config_dir}; pub use path::*; pub use tilde::expand_tilde; pub use trailing_slash::{has_trailing_slash, strip_trailing_slash};
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-path/src/dots.rs
crates/nu-path/src/dots.rs
#[cfg(windows)] use omnipath::WinPathExt; use std::path::{Component, Path, PathBuf, Prefix}; /// Normalize the path, expanding occurrences of n-dots. /// /// It performs the same normalization as `nu_path::components()`, except it also expands n-dots, /// such as "..." and "....", into multiple "..". /// /// The resulting path will use platform-specific path separators, regardless of what path separators was used in the input. pub fn expand_ndots(path: impl AsRef<Path>) -> PathBuf { // Returns whether a path component is n-dots. fn is_ndots(s: &std::ffi::OsStr) -> bool { s.as_encoded_bytes().iter().all(|c| *c == b'.') && s.len() >= 3 } let path = path.as_ref(); let mut result = PathBuf::with_capacity(path.as_os_str().len()); let mut has_special_prefix = false; for component in crate::components(path) { match component { Component::Normal(s) if is_ndots(s) => { let n = s.len(); // Push ".." to the path (n - 1) times. for _ in 0..n - 1 { result.push(".."); } } Component::Prefix(prefix) => { match prefix.kind() { Prefix::Disk(_) => { // Here, only the disk letter gets parsed as prefix, // so the following RootDir component makes sense } _ => { has_special_prefix = true; } } result.push(component) } Component::RootDir if has_special_prefix => { // Ignore; this would add a trailing backslash to the path that wasn't in the input } _ => result.push(component), } } result } /// Normalize the path, expanding occurrences of "." and "..". /// /// It performs the same normalization as `nu_path::components()`, except it also expands ".." /// when its preceding component is a normal component, ignoring the possibility of symlinks. /// In other words, it operates on the lexical structure of the path. /// /// This won't expand "/.." even though the parent directory of "/" is often /// considered to be itself. /// /// The resulting path will use platform-specific path separators, regardless of what path separators was used in the input. pub fn expand_dots(path: impl AsRef<Path>) -> PathBuf { // Check if the last component of the path is a normal component. fn last_component_is_normal(path: &Path) -> bool { matches!(path.components().next_back(), Some(Component::Normal(_))) } let path = path.as_ref(); let mut has_special_prefix = false; let mut result = PathBuf::with_capacity(path.as_os_str().len()); for component in crate::components(path) { match component { Component::ParentDir if last_component_is_normal(&result) => { result.pop(); } Component::CurDir if last_component_is_normal(&result) => { // no-op } Component::Prefix(prefix) => { match prefix.kind() { Prefix::Disk(_) => { // Here, only the disk letter gets parsed as prefix, // so the following RootDir component makes sense } _ => { has_special_prefix = true; } } result.push(component) } Component::RootDir if has_special_prefix => { // Ignore; this would add a trailing backslash to the path that wasn't in the input } _ => { let prev_component = result.components().next_back(); if prev_component == Some(Component::RootDir) && component == Component::ParentDir { continue; } result.push(component) } } } simiplified(&result) } /// Expand ndots, but only if it looks like it probably contains them, because there is some lossy /// path normalization that happens. pub fn expand_ndots_safe(path: impl AsRef<Path>) -> PathBuf { let string = path.as_ref().to_string_lossy(); // Use ndots if it contains at least `...`, since that's the minimum trigger point. // Don't use it if it contains ://, because that looks like a URL scheme and the path normalization // will mess with that. // Don't use it if it starts with `./`, as to not break golang wildcard syntax // (since generally you're probably not using `./` with ndots) if string.contains("...") && !string.contains("://") && !string.starts_with("./") { expand_ndots(path) } else { path.as_ref().to_owned() } } #[cfg(windows)] fn simiplified(path: &std::path::Path) -> PathBuf { path.to_winuser_path() .unwrap_or_else(|_| path.to_path_buf()) } #[cfg(not(windows))] fn simiplified(path: &std::path::Path) -> PathBuf { path.to_path_buf() } #[cfg(test)] mod test_expand_ndots { use super::*; use crate::assert_path_eq; #[test] fn empty_path() { let path = Path::new(""); assert_path_eq!(expand_ndots(path), ""); } #[test] fn root_dir() { let path = Path::new("/"); let expected = if cfg!(windows) { "\\" } else { "/" }; assert_path_eq!(expand_ndots(path), expected); } #[test] fn two_dots() { let path = Path::new(".."); assert_path_eq!(expand_ndots(path), ".."); } #[test] fn three_dots() { let path = Path::new("..."); let expected = if cfg!(windows) { r"..\.." } else { "../.." }; assert_path_eq!(expand_ndots(path), expected); } #[test] fn five_dots() { let path = Path::new("....."); let expected = if cfg!(windows) { r"..\..\..\.." } else { "../../../.." }; assert_path_eq!(expand_ndots(path), expected); } #[test] fn three_dots_with_trailing_slash() { let path = Path::new("/tmp/.../"); let expected = if cfg!(windows) { r"\tmp\..\..\" } else { "/tmp/../../" }; assert_path_eq!(expand_ndots(path), expected); } #[test] fn filenames_with_dots() { let path = Path::new("...foo.../"); let expected = if cfg!(windows) { r"...foo...\" } else { "...foo.../" }; assert_path_eq!(expand_ndots(path), expected); } #[test] fn multiple_ndots() { let path = Path::new("..././..."); let expected = if cfg!(windows) { r"..\..\..\.." } else { "../../../.." }; assert_path_eq!(expand_ndots(path), expected); } #[test] fn trailing_dots() { let path = Path::new("/foo/bar/.."); let expected = if cfg!(windows) { r"\foo\bar\.." } else { "/foo/bar/.." }; assert_path_eq!(expand_ndots(path), expected); } #[test] fn leading_dot_slash() { let path = Path::new("./..."); assert_path_eq!(expand_ndots_safe(path), "./..."); } #[test] fn unc_share_no_dots() { let path = Path::new(r"\\server\share"); assert_path_eq!(expand_ndots(path), path); } #[test] fn unc_file_no_dots() { let path = Path::new(r"\\server\share\dir\file.nu"); assert_path_eq!(expand_ndots(path), path); } #[test] fn verbatim_no_dots() { let path = Path::new(r"\\?\pictures\elephants"); assert_path_eq!(expand_ndots(path), path); } #[test] fn verbatim_unc_share_no_dots() { let path = Path::new(r"\\?\UNC\server\share"); assert_path_eq!(expand_ndots(path), path); } #[test] fn verbatim_unc_file_no_dots() { let path = Path::new(r"\\?\UNC\server\share\dir\file.nu"); assert_path_eq!(expand_ndots(path), path); } #[test] fn verbatim_disk_no_dots() { let path = Path::new(r"\\?\c:\"); assert_path_eq!(expand_ndots(path), path); } #[test] fn device_path_no_dots() { let path = Path::new(r"\\.\CON"); assert_path_eq!(expand_ndots(path), path); } #[test] fn disk_no_dots() { let path = Path::new(r"c:\Users\Ellie\nu_scripts"); assert_path_eq!(expand_ndots(path), path); } } #[cfg(test)] mod test_expand_dots { use super::*; use crate::assert_path_eq; #[test] fn empty_path() { let path = Path::new(""); assert_path_eq!(expand_dots(path), ""); } #[test] fn single_dot() { let path = Path::new("./"); let expected = if cfg!(windows) { r".\" } else { "./" }; assert_path_eq!(expand_dots(path), expected); } #[test] fn more_single_dots() { let path = Path::new("././."); let expected = "."; assert_path_eq!(expand_dots(path), expected); } #[test] fn double_dots() { let path = Path::new("../../.."); let expected = if cfg!(windows) { r"..\..\.." } else { "../../.." }; assert_path_eq!(expand_dots(path), expected); } #[test] fn backtrack_once() { let path = Path::new("/foo/bar/../baz/"); let expected = if cfg!(windows) { r"\foo\baz\" } else { "/foo/baz/" }; assert_path_eq!(expand_dots(path), expected); } #[test] fn backtrack_to_root() { let path = Path::new("/foo/bar/../../../../baz"); let expected = if cfg!(windows) { r"\baz" } else { "/baz" }; assert_path_eq!(expand_dots(path), expected); } #[test] fn unc_share_no_dots() { let path = Path::new(r"\\server\share"); assert_path_eq!(expand_dots(path), path); } #[test] fn unc_file_no_dots() { let path = Path::new(r"\\server\share\dir\file.nu"); assert_path_eq!(expand_dots(path), path); } #[test] #[ignore = "bug in upstream library"] fn verbatim_no_dots() { // omnipath::windows::sys::Path::to_winuser_path seems to turn this verbatim path into a device path let path = Path::new(r"\\?\pictures\elephants"); assert_path_eq!(expand_dots(path), path); } #[cfg_attr(not(windows), ignore = "only for Windows")] #[test] fn verbatim_unc_share_no_dots() { let path = Path::new(r"\\?\UNC\server\share"); let expected = Path::new(r"\\server\share"); assert_path_eq!(expand_dots(path), expected); } #[cfg_attr(not(windows), ignore = "only for Windows")] #[test] fn verbatim_unc_file_no_dots() { let path = Path::new(r"\\?\UNC\server\share\dir\file.nu"); let expected = Path::new(r"\\server\share\dir\file.nu"); assert_path_eq!(expand_dots(path), expected); } #[cfg_attr(not(windows), ignore = "only for Windows")] #[test] fn verbatim_disk_no_dots() { let path = Path::new(r"\\?\C:\"); let expected = Path::new(r"C:\"); assert_path_eq!(expand_dots(path), expected); } #[test] fn device_path_no_dots() { let path = Path::new(r"\\.\CON"); assert_path_eq!(expand_dots(path), path); } #[test] fn disk_no_dots() { let path = Path::new(r"c:\Users\Ellie\nu_scripts"); assert_path_eq!(expand_dots(path), path); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-path/src/helpers.rs
crates/nu-path/src/helpers.rs
#[cfg(windows)] use std::path::{Component, Prefix}; use std::path::{Path, PathBuf}; use crate::AbsolutePathBuf; pub fn home_dir() -> Option<AbsolutePathBuf> { dirs::home_dir().and_then(|home| AbsolutePathBuf::try_from(home).ok()) } /// Return the data directory for the current platform or XDG_DATA_HOME if specified. pub fn data_dir() -> Option<AbsolutePathBuf> { configurable_dir_path("XDG_DATA_HOME", dirs::data_dir) } /// Return the cache directory for the current platform or XDG_CACHE_HOME if specified. pub fn cache_dir() -> Option<AbsolutePathBuf> { configurable_dir_path("XDG_CACHE_HOME", dirs::cache_dir) } /// Return the nushell config directory. pub fn nu_config_dir() -> Option<AbsolutePathBuf> { configurable_dir_path("XDG_CONFIG_HOME", dirs::config_dir).map(|mut p| { p.push("nushell"); p }) } fn configurable_dir_path( name: &'static str, dir: impl FnOnce() -> Option<PathBuf>, ) -> Option<AbsolutePathBuf> { std::env::var(name) .ok() .and_then(|path| AbsolutePathBuf::try_from(path).ok()) .or_else(|| dir().and_then(|path| AbsolutePathBuf::try_from(path).ok())) .map(|path| path.canonicalize().map(Into::into).unwrap_or(path)) } // List of special paths that can be written to and/or read from, even though they // don't appear as directory entries. // See https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file // In rare circumstances, reserved paths _can_ exist as regular files in a // directory which shadow their special counterpart, so the safe way of referring // to these paths is by prefixing them with '\\.\' (this instructs the Windows APIs // to access the Win32 device namespace instead of the Win32 file namespace) // https://learn.microsoft.com/en-us/dotnet/standard/io/file-path-formats #[cfg(windows)] pub fn is_windows_device_path(path: &Path) -> bool { match path.components().next() { Some(Component::Prefix(prefix)) if matches!(prefix.kind(), Prefix::DeviceNS(_)) => { return true; } _ => {} } let special_paths: [&Path; 28] = [ Path::new("CON"), Path::new("PRN"), Path::new("AUX"), Path::new("NUL"), Path::new("COM1"), Path::new("COM2"), Path::new("COM3"), Path::new("COM4"), Path::new("COM5"), Path::new("COM6"), Path::new("COM7"), Path::new("COM8"), Path::new("COM9"), Path::new("COM¹"), Path::new("COM²"), Path::new("COM³"), Path::new("LPT1"), Path::new("LPT2"), Path::new("LPT3"), Path::new("LPT4"), Path::new("LPT5"), Path::new("LPT6"), Path::new("LPT7"), Path::new("LPT8"), Path::new("LPT9"), Path::new("LPT¹"), Path::new("LPT²"), Path::new("LPT³"), ]; if special_paths.contains(&path) { return true; } false } #[cfg(not(windows))] pub fn is_windows_device_path(_path: &Path) -> bool { false } #[cfg(test)] mod test_is_windows_device_path { use crate::is_windows_device_path; use std::path::Path; #[cfg_attr(not(windows), ignore = "only for Windows")] #[test] fn device_namespace() { assert!(is_windows_device_path(Path::new(r"\\.\CON"))) } #[cfg_attr(not(windows), ignore = "only for Windows")] #[test] fn reserved_device_name() { assert!(is_windows_device_path(Path::new(r"NUL"))) } #[cfg_attr(not(windows), ignore = "only for Windows")] #[test] fn normal_path() { assert!(!is_windows_device_path(Path::new(r"dir\file"))) } #[cfg_attr(not(windows), ignore = "only for Windows")] #[test] fn absolute_path() { assert!(!is_windows_device_path(Path::new(r"\dir\file"))) } #[cfg_attr(not(windows), ignore = "only for Windows")] #[test] fn unc_path() { assert!(!is_windows_device_path(Path::new(r"\\server\share"))) } #[cfg_attr(not(windows), ignore = "only for Windows")] #[test] fn verbatim_path() { assert!(!is_windows_device_path(Path::new(r"\\?\dir\file"))) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-path/src/form.rs
crates/nu-path/src/form.rs
use std::ffi::OsStr; mod private { use std::ffi::OsStr; // This trait should not be extended by external crates in order to uphold safety guarantees. // As such, this trait is put inside a private module to prevent external impls. // This ensures that all possible [`PathForm`]s can only be defined here and will: // - be zero sized (enforced anyways by the `repr(transparent)` on `Path`) // - have a no-op [`Drop`] implementation pub trait Sealed: 'static { fn invariants_satisfied<P: AsRef<OsStr> + ?Sized>(path: &P) -> bool; } } /// A marker trait for the different kinds of path forms. /// Each form has its own invariants that are guaranteed to be upheld. /// The list of path forms are: /// - [`Any`]: a path with no invariants. It may be a relative or an absolute path. /// - [`Relative`]: a strictly relative path. /// - [`Absolute`]: a strictly absolute path. /// - [`Canonical`]: a path that must be in canonicalized form. pub trait PathForm: private::Sealed {} impl PathForm for Any {} impl PathForm for Relative {} impl PathForm for Absolute {} impl PathForm for Canonical {} /// A path whose form is unknown. It could be a relative, absolute, or canonical path. /// /// The path is not guaranteed to be normalized. It may contain unresolved symlinks, /// trailing slashes, dot components (`..` or `.`), and repeated path separators. pub struct Any; impl private::Sealed for Any { fn invariants_satisfied<P: AsRef<OsStr> + ?Sized>(_: &P) -> bool { true } } /// A strictly relative path. /// /// The path is not guaranteed to be normalized. It may contain unresolved symlinks, /// trailing slashes, dot components (`..` or `.`), and repeated path separators. pub struct Relative; impl private::Sealed for Relative { fn invariants_satisfied<P: AsRef<OsStr> + ?Sized>(path: &P) -> bool { std::path::Path::new(path).is_relative() } } /// An absolute path. /// /// The path is not guaranteed to be normalized. It may contain unresolved symlinks, /// trailing slashes, dot components (`..` or `.`), and repeated path separators. pub struct Absolute; impl private::Sealed for Absolute { fn invariants_satisfied<P: AsRef<OsStr> + ?Sized>(path: &P) -> bool { std::path::Path::new(path).is_absolute() } } // A canonical path. // // An absolute path with all intermediate components normalized and symbolic links resolved. pub struct Canonical; impl private::Sealed for Canonical { fn invariants_satisfied<P: AsRef<OsStr> + ?Sized>(_: &P) -> bool { true } } /// A marker trait for [`PathForm`]s that may be relative paths. /// This includes only the [`Any`] and [`Relative`] path forms. pub trait MaybeRelative: PathForm {} impl MaybeRelative for Any {} impl MaybeRelative for Relative {} /// A marker trait for [`PathForm`]s that may be absolute paths. /// This includes the [`Any`], [`Absolute`], and [`Canonical`] path forms. pub trait MaybeAbsolute: PathForm {} impl MaybeAbsolute for Any {} impl MaybeAbsolute for Absolute {} impl MaybeAbsolute for Canonical {} /// A marker trait for [`PathForm`]s that are absolute paths. /// This includes only the [`Absolute`] and [`Canonical`] path forms. /// /// Only [`PathForm`]s that implement this trait can be easily converted to [`std::path::Path`] /// or [`std::path::PathBuf`]. This is to encourage/force other Nushell crates to account for /// the emulated current working directory, instead of using the [`std::env::current_dir`]. pub trait IsAbsolute: PathForm {} impl IsAbsolute for Absolute {} impl IsAbsolute for Canonical {} /// A marker trait that signifies one [`PathForm`] can be used as or trivially converted to /// another [`PathForm`]. /// /// The list of possible conversions are: /// - [`Relative`], [`Absolute`], or [`Canonical`] into [`Any`]. /// - [`Canonical`] into [`Absolute`]. /// - Any form into itself. pub trait PathCast<Form: PathForm>: PathForm {} impl<Form: PathForm> PathCast<Form> for Form {} impl PathCast<Any> for Relative {} impl PathCast<Any> for Absolute {} impl PathCast<Any> for Canonical {} impl PathCast<Absolute> for Canonical {} /// A trait used to specify the output [`PathForm`] of a path join operation. /// /// The output path forms based on the left hand side path form are as follows: /// /// | Left hand side | Output form | /// | --------------:|:------------ | /// | [`Any`] | [`Any`] | /// | [`Relative`] | [`Any`] | /// | [`Absolute`] | [`Absolute`] | /// | [`Canonical`] | [`Absolute`] | pub trait PathJoin: PathForm { type Output: PathForm; } impl PathJoin for Any { type Output = Self; } impl PathJoin for Relative { type Output = Any; } impl PathJoin for Absolute { type Output = Self; } impl PathJoin for Canonical { type Output = Absolute; } /// A marker trait for [`PathForm`]s that support setting the file name or extension. /// /// This includes the [`Any`], [`Relative`], and [`Absolute`] path forms. /// [`Canonical`] paths do not support this, since appending file names and extensions that contain /// path separators can cause the path to no longer be canonical. pub trait PathSet: PathForm {} impl PathSet for Any {} impl PathSet for Relative {} impl PathSet for Absolute {} /// A marker trait for [`PathForm`]s that support pushing paths. /// /// This includes only [`Any`] and [`Absolute`] path forms. /// Pushing onto a [`Relative`] path could cause it to become [`Absolute`], /// which is why they do not support pushing. /// In the future, a `push_rel` and/or a `try_push` method could be added as an alternative. /// Similarly, [`Canonical`] paths may become uncanonical if a path is pushed onto it. pub trait PathPush: PathSet {} impl PathPush for Any {} impl PathPush for Absolute {}
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-path/src/assert_path_eq.rs
crates/nu-path/src/assert_path_eq.rs
//! Path equality in Rust is defined by comparing their `components()`. However, //! `Path::components()` will perform its own normalization, which makes //! `assert_eq!` not suitable testing. //! //! This module provides two macros, `assert_path_eq!` and `assert_path_ne!`, //! which converts path to string before comparison. They accept PathBuf, Path, //! String, and &str as parameters. #[macro_export] macro_rules! assert_path_eq { ($left:expr, $right:expr $(,)?) => { assert_eq!( AsRef::<Path>::as_ref(&$left).to_str().unwrap(), AsRef::<Path>::as_ref(&$right).to_str().unwrap() ) }; } #[macro_export] macro_rules! assert_path_ne { ($left:expr, $right:expr $(,)?) => { assert_ne!( AsRef::<Path>::as_ref(&$left).to_str().unwrap(), AsRef::<Path>::as_ref(&$right).to_str().unwrap() ) }; } #[cfg(test)] mod test { use std::path::{Path, PathBuf}; #[test] fn assert_path_eq_works() { assert_path_eq!(PathBuf::from("/foo/bar"), Path::new("/foo/bar")); assert_path_eq!(PathBuf::from("/foo/bar"), String::from("/foo/bar")); assert_path_eq!(PathBuf::from("/foo/bar"), "/foo/bar"); assert_path_eq!(Path::new("/foo/bar"), String::from("/foo/bar")); assert_path_eq!(Path::new("/foo/bar"), "/foo/bar"); assert_path_eq!(Path::new(r"\foo\bar"), r"\foo\bar"); assert_path_ne!(PathBuf::from("/foo/bar/."), Path::new("/foo/bar")); assert_path_ne!(PathBuf::from("/foo/bar/."), String::from("/foo/bar")); assert_path_ne!(PathBuf::from("/foo/bar/."), "/foo/bar"); assert_path_ne!(Path::new("/foo/./bar"), String::from("/foo/bar")); assert_path_ne!(Path::new("/foo/./bar"), "/foo/bar"); assert_path_ne!(Path::new(r"\foo\bar"), r"/foo/bar"); assert_path_ne!(Path::new(r"/foo/bar"), r"\foo\bar"); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-path/src/trailing_slash.rs
crates/nu-path/src/trailing_slash.rs
use std::{ borrow::Cow, path::{Path, PathBuf}, }; /// Strip any trailing slashes from a non-root path. This is required in some contexts, for example /// for the `PWD` environment variable. pub fn strip_trailing_slash(path: &Path) -> Cow<'_, Path> { if has_trailing_slash(path) { // If there are, the safest thing to do is have Rust parse the path for us and build it // again. This will correctly handle a root directory, but it won't add the trailing slash. let mut out = PathBuf::with_capacity(path.as_os_str().len()); out.extend(path.components()); Cow::Owned(out) } else { // The path is safe and doesn't contain any trailing slashes. Cow::Borrowed(path) } } /// `true` if the path has a trailing slash, including if it's the root directory. #[cfg(windows)] pub fn has_trailing_slash(path: &Path) -> bool { use std::os::windows::ffi::OsStrExt; let last = path.as_os_str().encode_wide().last(); last == Some(b'\\' as u16) || last == Some(b'/' as u16) } /// `true` if the path has a trailing slash, including if it's the root directory. #[cfg(unix)] pub fn has_trailing_slash(path: &Path) -> bool { use std::os::unix::ffi::OsStrExt; let last = path.as_os_str().as_bytes().last(); last == Some(&b'/') } /// `true` if the path has a trailing slash, including if it's the root directory. #[cfg(target_arch = "wasm32")] pub fn has_trailing_slash(path: &Path) -> bool { // in the web paths are often just URLs, they are separated by forward slashes path.to_str().is_some_and(|s| s.ends_with('/')) } #[cfg(test)] mod tests { use super::*; #[cfg_attr(not(unix), ignore = "only for Unix")] #[test] fn strip_root_unix() { assert_eq!(Path::new("/"), strip_trailing_slash(Path::new("/"))); } #[cfg_attr(not(unix), ignore = "only for Unix")] #[test] fn strip_non_trailing_unix() { assert_eq!( Path::new("/foo/bar"), strip_trailing_slash(Path::new("/foo/bar")) ); } #[cfg_attr(not(unix), ignore = "only for Unix")] #[test] fn strip_trailing_unix() { assert_eq!( Path::new("/foo/bar"), strip_trailing_slash(Path::new("/foo/bar/")) ); } #[cfg_attr(not(windows), ignore = "only for Windows")] #[test] fn strip_root_windows() { assert_eq!(Path::new(r"C:\"), strip_trailing_slash(Path::new(r"C:\"))); } #[cfg_attr(not(windows), ignore = "only for Windows")] #[test] fn strip_non_trailing_windows() { assert_eq!( Path::new(r"C:\foo\bar"), strip_trailing_slash(Path::new(r"C:\foo\bar")) ); } #[cfg_attr(not(windows), ignore = "only for Windows")] #[test] fn strip_non_trailing_windows_unc() { assert_eq!( Path::new(r"\\foo\bar"), strip_trailing_slash(Path::new(r"\\foo\bar")) ); } #[cfg_attr(not(windows), ignore = "only for Windows")] #[test] fn strip_trailing_windows() { assert_eq!( Path::new(r"C:\foo\bar"), strip_trailing_slash(Path::new(r"C:\foo\bar\")) ); } #[cfg_attr(not(windows), ignore = "only for Windows")] #[test] fn strip_trailing_windows_unc() { assert_eq!( Path::new(r"\\foo\bar"), strip_trailing_slash(Path::new(r"\\foo\bar\")) ); } #[cfg_attr(not(windows), ignore = "only for Windows")] #[test] fn strip_trailing_windows_device() { assert_eq!( Path::new(r"\\.\foo"), strip_trailing_slash(Path::new(r"\\.\foo\")) ); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-path/src/tilde.rs
crates/nu-path/src/tilde.rs
#[cfg(all(unix, not(target_os = "macos"), not(target_os = "android")))] use pwd::Passwd; use std::path::{Path, PathBuf}; #[cfg(target_os = "macos")] const FALLBACK_USER_HOME_BASE_DIR: &str = "/Users"; #[cfg(target_os = "windows")] const FALLBACK_USER_HOME_BASE_DIR: &str = "C:\\Users\\"; #[cfg(all(unix, not(target_os = "macos"), not(target_os = "android")))] const FALLBACK_USER_HOME_BASE_DIR: &str = "/home"; #[cfg(all(unix, target_os = "android"))] const FALLBACK_USER_HOME_BASE_DIR: &str = "/data"; #[cfg(target_os = "android")] const TERMUX_HOME: &str = "/data/data/com.termux/files/home"; fn expand_tilde_with_home(path: impl AsRef<Path>, home: Option<PathBuf>) -> PathBuf { let path = path.as_ref(); if !path.starts_with("~") { let string = path.to_string_lossy(); let mut path_as_string = string.as_ref().bytes(); return match path_as_string.next() { Some(b'~') => expand_tilde_with_another_user_home(path), _ => path.into(), }; } let path_last_char = path.as_os_str().to_string_lossy().chars().next_back(); let need_trailing_slash = path_last_char == Some('/') || path_last_char == Some('\\'); match home { None => path.into(), Some(mut h) => { if h == Path::new("/") { // Corner case: `h` is a root directory; // don't prepend extra `/`, just drop the tilde. path.strip_prefix("~").unwrap_or(path).into() } else { if let Ok(p) = path.strip_prefix("~/") { // Corner case: `p` is empty; // Don't append extra '/', just keep `h` as is. // This happens because PathBuf.push will always // add a separator if the pushed path is relative, // even if it's empty if p != Path::new("") { h.push(p) } if need_trailing_slash { h.push(""); } } h } } } } #[cfg(not(target_arch = "wasm32"))] fn fallback_home_dir(username: &str) -> PathBuf { PathBuf::from_iter([FALLBACK_USER_HOME_BASE_DIR, username]) } #[cfg(all(unix, not(target_os = "macos"), not(target_os = "android")))] fn user_home_dir(username: &str) -> PathBuf { let passwd = Passwd::from_name(username); match &passwd.ok() { Some(Some(dir)) => PathBuf::from(&dir.dir), _ => fallback_home_dir(username), } } #[cfg(any(target_os = "android", target_os = "windows", target_os = "macos"))] fn user_home_dir(username: &str) -> PathBuf { use std::path::Component; match dirs::home_dir() { None => { // Termux always has the same home directory #[cfg(target_os = "android")] if is_termux() { return PathBuf::from(TERMUX_HOME); } fallback_home_dir(username) } Some(user) => { let mut expected_path = user; if !cfg!(target_os = "android") && expected_path .components() .next_back() .map(|last| last != Component::Normal(username.as_ref())) .unwrap_or(false) { expected_path.pop(); expected_path.push(Path::new(username)); } if expected_path.is_dir() { expected_path } else { fallback_home_dir(username) } } } } #[cfg(target_arch = "wasm32")] fn user_home_dir(_: &str) -> PathBuf { // if WASI is used, we try to get a home dir via HOME env, otherwise we don't have a home dir let home = std::env::var("HOME").unwrap_or_else(|_| "/".to_string()); PathBuf::from(home) } /// Returns true if the shell is running inside the Termux terminal emulator /// app. #[cfg(target_os = "android")] fn is_termux() -> bool { std::env::var("TERMUX_VERSION").is_ok() } fn expand_tilde_with_another_user_home(path: &Path) -> PathBuf { match path.to_str() { Some(file_path) => { let mut file = file_path.to_string(); match file_path.find(['/', '\\']) { None => { file.remove(0); user_home_dir(&file) } Some(i) => { let (pre_name, rest_of_path) = file.split_at(i); let mut name = pre_name.to_string(); let mut rest_path = rest_of_path.to_string(); rest_path.remove(0); name.remove(0); let mut path = user_home_dir(&name); path.push(Path::new(&rest_path)); path } } } None => path.to_path_buf(), } } /// Expand tilde ("~") into a home directory if it is the first path component pub fn expand_tilde(path: impl AsRef<Path>) -> PathBuf { expand_tilde_with_home(path, dirs::home_dir()) } #[cfg(test)] mod tests { use super::*; use crate::assert_path_eq; use std::path::MAIN_SEPARATOR; fn check_expanded(s: &str) { let home = Path::new("/home"); let buf = Some(PathBuf::from(home)); assert!(expand_tilde_with_home(Path::new(s), buf).starts_with(home)); // Tests the special case in expand_tilde for "/" as home let home = Path::new("/"); let buf = Some(PathBuf::from(home)); assert!(!expand_tilde_with_home(Path::new(s), buf).starts_with("//")); } fn check_not_expanded(s: &str) { let home = PathBuf::from("/home"); let expanded = expand_tilde_with_home(Path::new(s), Some(home)); assert_eq!(expanded, Path::new(s)); } #[test] fn string_with_tilde() { check_expanded("~"); } #[test] fn string_with_tilde_forward_slash() { check_expanded("~/test/"); } #[test] fn string_with_tilde_double_forward_slash() { check_expanded("~//test/"); } #[test] fn string_with_tilde_other_user() { let s = "~someone/test/"; let expected = format!("{FALLBACK_USER_HOME_BASE_DIR}/someone/test/"); assert_eq!(expand_tilde(Path::new(s)), PathBuf::from(expected)); } #[test] fn string_with_multi_byte_chars() { let s = "~あ/"; let expected = format!("{FALLBACK_USER_HOME_BASE_DIR}/あ/"); assert_eq!(expand_tilde(Path::new(s)), PathBuf::from(expected)); } #[test] fn does_not_expand_tilde_if_tilde_is_not_first_character() { check_not_expanded("1~1"); } #[test] fn path_does_not_include_trailing_separator() { let home = Path::new("/home"); let buf = Some(PathBuf::from(home)); let expanded = expand_tilde_with_home(Path::new("~"), buf); let expanded_str = expanded.to_str().unwrap(); assert!(!expanded_str.ends_with(MAIN_SEPARATOR)); } #[cfg(windows)] #[test] fn string_with_tilde_backslash() { check_expanded("~\\test/test2/test3"); } #[cfg(windows)] #[test] fn string_with_double_tilde_backslash() { check_expanded("~\\\\test\\test2/test3"); } // [TODO] Figure out how to reliably test with real users. #[test] fn user_home_dir_fallback() { let user = "nonexistent"; let expected_home = PathBuf::from_iter([FALLBACK_USER_HOME_BASE_DIR, user]); #[cfg(target_os = "android")] let expected_home = if is_termux() { PathBuf::from(TERMUX_HOME) } else { expected_home }; let actual_home = super::user_home_dir(user); assert_eq!(expected_home, actual_home, "wrong home"); } #[test] #[cfg(not(windows))] fn expand_tilde_preserve_trailing_slash() { let path = PathBuf::from("~/foo/"); let home = PathBuf::from("/home"); let actual = expand_tilde_with_home(path, Some(home)); assert_path_eq!(actual, "/home/foo/"); } #[test] #[cfg(windows)] fn expand_tilde_preserve_trailing_slash() { let path = PathBuf::from("~\\foo\\"); let home = PathBuf::from("C:\\home"); let actual = expand_tilde_with_home(path, Some(home)); assert_path_eq!(actual, "C:\\home\\foo\\"); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-path/src/components.rs
crates/nu-path/src/components.rs
//! A wrapper around `Path::components()` that preserves trailing slashes. //! //! Trailing slashes are semantically important for us. For example, POSIX says //! that path resolution should always follow the final symlink if it has //! trailing slashes. Here's a demonstration: //! //! ```sh //! mkdir foo //! ln -s foo link //! //! cp -r link bar # This copies the symlink, so bar is now a symlink to foo //! cp -r link/ baz # This copies the directory, so baz is now a directory //! ``` //! //! However, `Path::components()` normalizes trailing slashes away, and so does //! other APIs that uses `Path::components()` under the hood, such as //! `Path::parent()`. This is not ideal for path manipulation. //! //! This module provides a wrapper around `Path::components()` that produces an //! empty component when there's a trailing slash. //! //! You can reconstruct a path with a trailing slash by concatenating the //! components returned by this function using `PathBuf::push()` or //! `Path::join()`. It works because `PathBuf::push("")` will add a trailing //! slash when the original path doesn't have one. use std::{ ffi::OsStr, path::{Component, Path}, }; use crate::trailing_slash::has_trailing_slash; /// Like `Path::components()`, but produces an extra empty component at the end /// when `path` contains a trailing slash. /// /// Example: /// /// ``` /// # use std::path::{Path, Component}; /// # use std::ffi::OsStr; /// use nu_path::components; /// /// let path = Path::new("/foo/bar/"); /// let mut components = components(path); /// /// assert_eq!(components.next(), Some(Component::RootDir)); /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo")))); /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("bar")))); /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("")))); /// assert_eq!(components.next(), None); /// ``` pub fn components(path: &Path) -> impl Iterator<Item = Component<'_>> { let mut final_component = Some(Component::Normal(OsStr::new(""))); path.components().chain(std::iter::from_fn(move || { if has_trailing_slash(path) { final_component.take() } else { None } })) } #[cfg(test)] mod test { //! We'll go through every variant of Component, with or without trailing //! slashes. Then we'll try reconstructing the path on some typical use cases. use crate::assert_path_eq; use std::{ ffi::OsStr, path::{Component, Path, PathBuf}, }; #[test] fn empty_path() { let path = Path::new(""); let mut components = crate::components(path); assert_eq!(components.next(), None); } #[test] #[cfg(windows)] fn prefix_only() { let path = Path::new("C:"); let mut components = crate::components(path); assert!(matches!(components.next(), Some(Component::Prefix(_)))); assert_eq!(components.next(), None); } #[test] #[cfg(windows)] fn prefix_with_trailing_slash() { let path = Path::new("C:\\"); let mut components = crate::components(path); assert!(matches!(components.next(), Some(Component::Prefix(_)))); assert!(matches!(components.next(), Some(Component::RootDir))); assert_eq!(components.next(), Some(Component::Normal(OsStr::new("")))); assert_eq!(components.next(), None); } #[test] fn root() { let path = Path::new("/"); let mut components = crate::components(path); assert!(matches!(components.next(), Some(Component::RootDir))); assert_eq!(components.next(), Some(Component::Normal(OsStr::new("")))); assert_eq!(components.next(), None); } #[test] fn cur_dir_only() { let path = Path::new("."); let mut components = crate::components(path); assert!(matches!(components.next(), Some(Component::CurDir))); assert_eq!(components.next(), None); } #[test] fn cur_dir_with_trailing_slash() { let path = Path::new("./"); let mut components = crate::components(path); assert!(matches!(components.next(), Some(Component::CurDir))); assert_eq!(components.next(), Some(Component::Normal(OsStr::new("")))); assert_eq!(components.next(), None); } #[test] fn parent_dir_only() { let path = Path::new(".."); let mut components = crate::components(path); assert!(matches!(components.next(), Some(Component::ParentDir))); assert_eq!(components.next(), None); } #[test] fn parent_dir_with_trailing_slash() { let path = Path::new("../"); let mut components = crate::components(path); assert!(matches!(components.next(), Some(Component::ParentDir))); assert_eq!(components.next(), Some(Component::Normal(OsStr::new("")))); assert_eq!(components.next(), None); } #[test] fn normal_only() { let path = Path::new("foo"); let mut components = crate::components(path); assert_eq!( components.next(), Some(Component::Normal(OsStr::new("foo"))) ); assert_eq!(components.next(), None); } #[test] fn normal_with_trailing_slash() { let path = Path::new("foo/"); let mut components = crate::components(path); assert_eq!( components.next(), Some(Component::Normal(OsStr::new("foo"))) ); assert_eq!(components.next(), Some(Component::Normal(OsStr::new("")))); assert_eq!(components.next(), None); } #[test] #[cfg(not(windows))] fn reconstruct_unix_only() { let path = Path::new("/home/Alice"); let mut buf = PathBuf::new(); for component in crate::components(path) { buf.push(component); } assert_path_eq!(path, buf); } #[test] #[cfg(not(windows))] fn reconstruct_unix_with_trailing_slash() { let path = Path::new("/home/Alice/"); let mut buf = PathBuf::new(); for component in crate::components(path) { buf.push(component); } assert_path_eq!(path, buf); } #[test] #[cfg(windows)] fn reconstruct_windows_only() { let path = Path::new("C:\\WINDOWS\\System32"); let mut buf = PathBuf::new(); for component in crate::components(path) { buf.push(component); } assert_path_eq!(path, buf); } #[test] #[cfg(windows)] fn reconstruct_windows_with_trailing_slash() { let path = Path::new("C:\\WINDOWS\\System32\\"); let mut buf = PathBuf::new(); for component in crate::components(path) { buf.push(component); } assert_path_eq!(path, buf); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-path/src/expansions.rs
crates/nu-path/src/expansions.rs
#[cfg(windows)] use omnipath::WinPathExt; use std::io; use std::path::{Path, PathBuf}; use super::dots::{expand_dots, expand_ndots}; use super::tilde::expand_tilde; // Join a path relative to another path. Paths starting with tilde are considered as absolute. fn join_path_relative<P, Q>(path: P, relative_to: Q, expand_tilde: bool) -> PathBuf where P: AsRef<Path>, Q: AsRef<Path>, { let path = path.as_ref(); let relative_to = relative_to.as_ref(); if path == Path::new(".") { // Joining a Path with '.' appends a '.' at the end, making the prompt // more ugly - so we don't do anything, which should result in an equal // path on all supported systems. relative_to.into() } else if path.to_string_lossy().as_ref().starts_with('~') && expand_tilde { // do not end up with "/some/path/~" or "/some/path/~user" path.into() } else { relative_to.join(path) } } fn canonicalize(path: impl AsRef<Path>) -> io::Result<PathBuf> { let path = expand_tilde(path); let path = expand_ndots(path); canonicalize_path(&path) } #[cfg(windows)] fn canonicalize_path(path: &std::path::Path) -> std::io::Result<std::path::PathBuf> { path.canonicalize()?.to_winuser_path() } #[cfg(not(windows))] fn canonicalize_path(path: &std::path::Path) -> std::io::Result<std::path::PathBuf> { path.canonicalize() } /// Resolve all symbolic links and all components (tilde, ., .., ...+) and return the path in its /// absolute form. /// /// Fails under the same conditions as /// [`std::fs::canonicalize`](https://doc.rust-lang.org/std/fs/fn.canonicalize.html). /// The input path is specified relative to another path pub fn canonicalize_with<P, Q>(path: P, relative_to: Q) -> io::Result<PathBuf> where P: AsRef<Path>, Q: AsRef<Path>, { let path = join_path_relative(path, relative_to, true); canonicalize(path) } /// Resolve only path components (tilde, ., .., ...+), if possible. /// /// Doesn't convert to absolute form or use syscalls. Output may begin with "../" pub fn expand_path(path: impl AsRef<Path>, need_expand_tilde: bool) -> PathBuf { let path = if need_expand_tilde { expand_tilde(path) } else { PathBuf::from(path.as_ref()) }; let path = expand_ndots(path); expand_dots(path) } /// Resolve only path components (tilde, ., .., ...+), if possible. /// /// The function works in a "best effort" mode: It does not fail but rather returns the unexpanded /// version if the expansion is not possible. /// /// Furthermore, unlike canonicalize(), it does not use sys calls (such as readlink). /// /// Converts to absolute form but does not resolve symlinks. /// The input path is specified relative to another path pub fn expand_path_with<P, Q>(path: P, relative_to: Q, expand_tilde: bool) -> PathBuf where P: AsRef<Path>, Q: AsRef<Path>, { let path = join_path_relative(path, relative_to, expand_tilde); expand_path(path, expand_tilde) } /// Resolve to a path that is accepted by the system and no further - tilde is expanded, and ndot path components are expanded. /// /// This function will take a leading tilde path component, and expand it to the user's home directory; /// it will also expand any path elements consisting of only dots into the correct number of `..` path elements. /// It does not do any normalization except to what will be accepted by Path::open, /// and it does not touch the system at all, except for getting the home directory of the current user. pub fn expand_to_real_path<P>(path: P) -> PathBuf where P: AsRef<Path>, { let path = expand_tilde(path); expand_ndots(path) } /// Attempts to canonicalize the path against the current directory. Failing that, if /// the path is relative, it attempts all of the dirs in `dirs`. If that fails, it returns /// the original error. pub fn locate_in_dirs<I, P>( filename: impl AsRef<Path>, cwd: impl AsRef<Path>, dirs: impl FnOnce() -> I, ) -> std::io::Result<PathBuf> where I: IntoIterator<Item = P>, P: AsRef<Path>, { let filename = filename.as_ref(); let cwd = cwd.as_ref(); match canonicalize_with(filename, cwd) { Ok(path) => Ok(path), Err(err) => { // Try to find it in `dirs` first, before giving up let mut found = None; for dir in dirs() { if let Ok(path) = canonicalize_with(dir, cwd).and_then(|dir| canonicalize_with(filename, dir)) { found = Some(path); break; } } found.ok_or(err) } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-path/fuzz/fuzz_targets/path_fuzzer.rs
crates/nu-path/fuzz/fuzz_targets/path_fuzzer.rs
#![no_main] use libfuzzer_sys::fuzz_target; use nu_path::{expand_path_with, expand_tilde, expand_to_real_path}; fuzz_target!(|data: &[u8]| { if let Ok(s) = std::str::from_utf8(data) { let path = std::path::Path::new(s); // Fuzzing expand_to_real_path function let _ = expand_to_real_path(path); // Fuzzing expand_tilde function let _ = expand_tilde(path); // Fuzzing expand_path_with function // Here, we're assuming a second path for the "relative to" aspect. // For simplicity, we're just using the current directory. let current_dir = std::path::Path::new("."); let _ = expand_path_with(path, &current_dir, true); } });
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-parser/src/parse_keywords.rs
crates/nu-parser/src/parse_keywords.rs
use crate::{ exportable::Exportable, parse_block, parser::{ ArgumentParsingLevel, CallKind, compile_block, compile_block_with_id, parse_attribute, parse_redirection, redirecting_builtin_error, }, type_check::{check_block_input_output, type_compatible}, }; use log::trace; use nu_path::canonicalize_with; use nu_path::is_windows_device_path; use nu_protocol::{ Alias, BlockId, CommandWideCompleter, CustomExample, DeclId, FromValue, Module, ModuleId, ParseError, PositionalArg, ResolvedImportPattern, ShellError, Signature, Span, Spanned, SyntaxShape, Type, Value, VarId, ast::{ Argument, AttributeBlock, Block, Call, Expr, Expression, ImportPattern, ImportPatternHead, ImportPatternMember, Pipeline, PipelineElement, }, category_from_string, engine::{DEFAULT_OVERLAY_NAME, StateWorkingSet}, eval_const::eval_constant, parser_path::ParserPath, }; use std::{ collections::{HashMap, HashSet}, path::{Path, PathBuf}, sync::Arc, }; pub const LIB_DIRS_VAR: &str = "NU_LIB_DIRS"; #[cfg(feature = "plugin")] pub const PLUGIN_DIRS_VAR: &str = "NU_PLUGIN_DIRS"; use crate::{ Token, TokenContents, is_math_expression_like, known_external::KnownExternal, lex, lite_parser::{LiteCommand, lite_parse}, parser::{ ParsedInternalCall, garbage, garbage_pipeline, parse, parse_call, parse_expression, parse_full_signature, parse_import_pattern, parse_internal_call, parse_string, parse_var_with_opt_type, trim_quotes, }, unescape_unquote_string, }; /// These parser keywords can be aliased pub const ALIASABLE_PARSER_KEYWORDS: &[&[u8]] = &[ b"if", b"match", b"try", b"overlay", b"overlay hide", b"overlay new", b"overlay use", ]; pub const RESERVED_VARIABLE_NAMES: [&str; 3] = ["in", "nu", "env"]; /// These parser keywords cannot be aliased (either not possible, or support not yet added) pub const UNALIASABLE_PARSER_KEYWORDS: &[&[u8]] = &[ b"alias", b"const", b"def", b"extern", b"module", b"use", b"export", b"export alias", b"export const", b"export def", b"export extern", b"export module", b"export use", b"for", b"loop", b"while", b"return", b"break", b"continue", b"let", b"mut", b"hide", b"export-env", b"source-env", b"source", b"where", b"plugin use", ]; /// Check whether spans start with a parser keyword that can be aliased pub fn is_unaliasable_parser_keyword(working_set: &StateWorkingSet, spans: &[Span]) -> bool { // try two words if let (Some(&span1), Some(&span2)) = (spans.first(), spans.get(1)) { let cmd_name = working_set.get_span_contents(Span::append(span1, span2)); return UNALIASABLE_PARSER_KEYWORDS.contains(&cmd_name); } // try one word if let Some(&span1) = spans.first() { let cmd_name = working_set.get_span_contents(span1); UNALIASABLE_PARSER_KEYWORDS.contains(&cmd_name) } else { false } } /// This is a new more compact method of calling parse_xxx() functions without repeating the /// parse_call() in each function. Remaining keywords can be moved here. pub fn parse_keyword(working_set: &mut StateWorkingSet, lite_command: &LiteCommand) -> Pipeline { let orig_parse_errors_len = working_set.parse_errors.len(); let call_expr = parse_call(working_set, &lite_command.parts, lite_command.parts[0]); // If an error occurred, don't invoke the keyword-specific functionality if working_set.parse_errors.len() > orig_parse_errors_len { return Pipeline::from_vec(vec![call_expr]); } if let Expression { expr: Expr::Call(call), .. } = call_expr.clone() { // Apply parse keyword side effects let cmd = working_set.get_decl(call.decl_id); // check help flag first. if call.named_iter().any(|(flag, _, _)| flag.item == "help") { let call_span = call.span(); return Pipeline::from_vec(vec![Expression::new( working_set, Expr::Call(call), call_span, Type::Any, )]); } match cmd.name() { "overlay hide" => parse_overlay_hide(working_set, call), "overlay new" => parse_overlay_new(working_set, call), "overlay use" => parse_overlay_use(working_set, call), #[cfg(feature = "plugin")] "plugin use" => parse_plugin_use(working_set, call), _ => Pipeline::from_vec(vec![call_expr]), } } else { Pipeline::from_vec(vec![call_expr]) } } pub fn parse_def_predecl(working_set: &mut StateWorkingSet, spans: &[Span]) { let mut pos = 0; let def_type_name = if spans.len() >= 3 { // definition can't have only two spans, minimum is 3, e.g., 'extern spam []' let first_word = working_set.get_span_contents(spans[0]); if first_word == b"export" { pos += 2; } else { pos += 1; } working_set.get_span_contents(spans[pos - 1]).to_vec() } else { return; }; if def_type_name != b"def" && def_type_name != b"extern" { return; } // Now, pos should point at the next span after the def-like call. // Skip all potential flags, like --env, --wrapped or --help: while pos < spans.len() && working_set.get_span_contents(spans[pos]).starts_with(b"-") { pos += 1; } if pos >= spans.len() { // This can happen if the call ends with a flag, e.g., 'def --help' return; } // Now, pos should point at the command name. let name_pos = pos; let Some(name) = parse_string(working_set, spans[name_pos]).as_string() else { return; }; if name.contains('#') || name.contains('^') || name.parse::<bytesize::ByteSize>().is_ok() || name.parse::<f64>().is_ok() { working_set.error(ParseError::CommandDefNotValid(spans[name_pos])); return; } // Find signature let mut signature_pos = None; while pos < spans.len() { if working_set.get_span_contents(spans[pos]).starts_with(b"[") || working_set.get_span_contents(spans[pos]).starts_with(b"(") { signature_pos = Some(pos); break; } pos += 1; } let Some(signature_pos) = signature_pos else { return; }; let mut allow_unknown_args = false; for span in spans { if working_set.get_span_contents(*span) == b"--wrapped" && def_type_name == b"def" { allow_unknown_args = true; } } let starting_error_count = working_set.parse_errors.len(); working_set.enter_scope(); // FIXME: because parse_signature will update the scope with the variables it sees // we end up parsing the signature twice per def. The first time is during the predecl // so that we can see the types that are part of the signature, which we need for parsing. // The second time is when we actually parse the body itworking_set. // We can't reuse the first time because the variables that are created during parse_signature // are lost when we exit the scope below. let sig = parse_full_signature(working_set, &spans[signature_pos..]); working_set.parse_errors.truncate(starting_error_count); working_set.exit_scope(); let Some(mut signature) = sig.as_signature() else { return; }; signature.name = name; if allow_unknown_args { signature.allows_unknown_args = true; } let decl = signature.predeclare(); if working_set.add_predecl(decl).is_some() { working_set.error(ParseError::DuplicateCommandDef(spans[name_pos])); } } pub fn parse_for(working_set: &mut StateWorkingSet, lite_command: &LiteCommand) -> Expression { let spans = &lite_command.parts; // Checking that the function is used with the correct name // Maybe this is not necessary but it is a sanity check if working_set.get_span_contents(spans[0]) != b"for" { working_set.error(ParseError::UnknownState( "internal error: Wrong call name for 'for' function".into(), Span::concat(spans), )); return garbage(working_set, spans[0]); } if let Some(redirection) = lite_command.redirection.as_ref() { working_set.error(redirecting_builtin_error("for", redirection)); return garbage(working_set, spans[0]); } // Parsing the spans and checking that they match the register signature // Using a parsed call makes more sense than checking for how many spans are in the call // Also, by creating a call, it can be checked if it matches the declaration signature let (call, call_span) = match working_set.find_decl(b"for") { None => { working_set.error(ParseError::UnknownState( "internal error: for declaration not found".into(), Span::concat(spans), )); return garbage(working_set, spans[0]); } Some(decl_id) => { let starting_error_count = working_set.parse_errors.len(); working_set.enter_scope(); let ParsedInternalCall { call, output, call_kind, } = parse_internal_call( working_set, spans[0], &spans[1..], decl_id, ArgumentParsingLevel::Full, ); if working_set .parse_errors .get(starting_error_count..) .is_none_or(|new_errors| { new_errors .iter() .all(|e| !matches!(e, ParseError::Unclosed(token, _) if token == "}")) }) { working_set.exit_scope(); } let call_span = Span::concat(spans); let decl = working_set.get_decl(decl_id); let sig = decl.signature(); if call_kind != CallKind::Valid { return Expression::new(working_set, Expr::Call(call), call_span, output); } // Let's get our block and make sure it has the right signature if let Some( Expression { expr: Expr::Block(block_id), .. } | Expression { expr: Expr::RowCondition(block_id), .. }, ) = call.positional_nth(2) { { let block = working_set.get_block_mut(*block_id); block.signature = Box::new(sig); } } (call, call_span) } }; // All positional arguments must be in the call positional vector by this point let var_decl = call.positional_nth(0).expect("for call already checked"); let iteration_expr = call.positional_nth(1).expect("for call already checked"); let block = call.positional_nth(2).expect("for call already checked"); let iteration_expr_ty = iteration_expr.ty.clone(); // Figure out the type of the variable the `for` uses for iteration let var_type = match iteration_expr_ty { Type::List(x) => *x, Type::Table(x) => Type::Record(x), Type::Range => Type::Number, // Range elements can be int or float x => x, }; if let (Some(var_id), Some(block_id)) = (&var_decl.as_var(), block.as_block()) { working_set.set_variable_type(*var_id, var_type.clone()); let block = working_set.get_block_mut(block_id); block.signature.required_positional.insert( 0, PositionalArg { name: String::new(), desc: String::new(), shape: var_type.to_shape(), var_id: Some(*var_id), default_value: None, completion: None, }, ); } Expression::new(working_set, Expr::Call(call), call_span, Type::Nothing) } /// If `name` is a keyword, emit an error. fn verify_not_reserved_variable_name(working_set: &mut StateWorkingSet, name: &str, span: Span) { if RESERVED_VARIABLE_NAMES.contains(&name) { working_set.error(ParseError::NameIsBuiltinVar(name.to_string(), span)) } } // This is meant for parsing attribute blocks without an accompanying `def` or `extern`. It's // necessary to provide consistent syntax highlighting, completions, and helpful errors // // There is no need to run the const evaluation here pub fn parse_attribute_block( working_set: &mut StateWorkingSet, lite_command: &LiteCommand, ) -> Pipeline { let attributes = lite_command .attribute_commands() .map(|cmd| parse_attribute(working_set, &cmd).0) .collect::<Vec<_>>(); let last_attr_span = attributes .last() .expect("Attribute block must contain at least one attribute") .expr .span; working_set.error(ParseError::AttributeRequiresDefinition(last_attr_span)); let cmd_span = if lite_command.command_parts().is_empty() { last_attr_span.past() } else { Span::concat(lite_command.command_parts()) }; let cmd_expr = garbage(working_set, cmd_span); let ty = cmd_expr.ty.clone(); let attr_block_span = Span::merge_many( attributes .first() .map(|x| x.expr.span) .into_iter() .chain(Some(cmd_span)), ); Pipeline::from_vec(vec![Expression::new( working_set, Expr::AttributeBlock(AttributeBlock { attributes, item: Box::new(cmd_expr), }), attr_block_span, ty, )]) } // Returns also the parsed command name and ID pub fn parse_def( working_set: &mut StateWorkingSet, lite_command: &LiteCommand, module_name: Option<&[u8]>, ) -> (Pipeline, Option<(Vec<u8>, DeclId)>) { let mut attributes = vec![]; let mut attribute_vals = vec![]; for attr_cmd in lite_command.attribute_commands() { let (attr, name) = parse_attribute(working_set, &attr_cmd); if let Some(name) = name { let val = eval_constant(working_set, &attr.expr); match val { Ok(val) => attribute_vals.push((name, val)), Err(e) => working_set.error(e.wrap(working_set, attr.expr.span)), } } attributes.push(attr); } let (expr, decl) = parse_def_inner(working_set, attribute_vals, lite_command, module_name); let ty = expr.ty.clone(); let attr_block_span = Span::merge_many( attributes .first() .map(|x| x.expr.span) .into_iter() .chain(Some(expr.span)), ); let expr = if attributes.is_empty() { expr } else { Expression::new( working_set, Expr::AttributeBlock(AttributeBlock { attributes, item: Box::new(expr), }), attr_block_span, ty, ) }; (Pipeline::from_vec(vec![expr]), decl) } pub fn parse_extern( working_set: &mut StateWorkingSet, lite_command: &LiteCommand, module_name: Option<&[u8]>, ) -> Pipeline { let mut attributes = vec![]; let mut attribute_vals = vec![]; for attr_cmd in lite_command.attribute_commands() { let (attr, name) = parse_attribute(working_set, &attr_cmd); if let Some(name) = name { let val = eval_constant(working_set, &attr.expr); match val { Ok(val) => attribute_vals.push((name, val)), Err(e) => working_set.error(e.wrap(working_set, attr.expr.span)), } } attributes.push(attr); } let expr = parse_extern_inner(working_set, attribute_vals, lite_command, module_name); let ty = expr.ty.clone(); let attr_block_span = Span::merge_many( attributes .first() .map(|x| x.expr.span) .into_iter() .chain(Some(expr.span)), ); let expr = if attributes.is_empty() { expr } else { Expression::new( working_set, Expr::AttributeBlock(AttributeBlock { attributes, item: Box::new(expr), }), attr_block_span, ty, ) }; Pipeline::from_vec(vec![expr]) } // Returns also the parsed command name and ID fn parse_def_inner( working_set: &mut StateWorkingSet, attributes: Vec<(String, Value)>, lite_command: &LiteCommand, module_name: Option<&[u8]>, ) -> (Expression, Option<(Vec<u8>, DeclId)>) { let spans = lite_command.command_parts(); let (desc, extra_desc) = working_set.build_desc(&lite_command.comments); let garbage_result = |working_set: &mut StateWorkingSet<'_>| (garbage(working_set, Span::concat(spans)), None); // Checking that the function is used with the correct name // Maybe this is not necessary but it is a sanity check // Note: "export def" is treated the same as "def" let (name_span, split_id) = if spans.len() > 1 && working_set.get_span_contents(spans[0]) == b"export" { (spans[1], 2) } else { (spans[0], 1) }; let def_call = working_set.get_span_contents(name_span); if def_call != b"def" { working_set.error(ParseError::UnknownState( "internal error: Wrong call name for def function".into(), Span::concat(spans), )); return garbage_result(working_set); } if let Some(redirection) = lite_command.redirection.as_ref() { working_set.error(redirecting_builtin_error("def", redirection)); return garbage_result(working_set); } // Parsing the spans and checking that they match the register signature // Using a parsed call makes more sense than checking for how many spans are in the call // Also, by creating a call, it can be checked if it matches the declaration signature // // NOTE: Here we only search for `def` in the permanent state, // since recursively redefining `def` is dangerous, // see https://github.com/nushell/nushell/issues/16586 let (call, call_span) = match working_set.permanent_state.find_decl(def_call, &[]) { None => { working_set.error(ParseError::UnknownState( "internal error: def declaration not found".into(), Span::concat(spans), )); return garbage_result(working_set); } Some(decl_id) => { working_set.enter_scope(); let (command_spans, rest_spans) = spans.split_at(split_id); // Find the first span that is not a flag let mut decl_name_span = None; for span in rest_spans { if !working_set.get_span_contents(*span).starts_with(b"-") { decl_name_span = Some(*span); break; } } if let Some(name_span) = decl_name_span { // Check whether name contains [] or () -- possible missing space error if let Some(err) = detect_params_in_name(working_set, name_span, decl_id) { working_set.error(err); return garbage_result(working_set); } } let starting_error_count = working_set.parse_errors.len(); let ParsedInternalCall { call, output, call_kind, } = parse_internal_call( working_set, Span::concat(command_spans), rest_spans, decl_id, ArgumentParsingLevel::Full, ); if working_set .parse_errors .get(starting_error_count..) .is_none_or(|new_errors| { new_errors .iter() .all(|e| !matches!(e, ParseError::Unclosed(token, _) if token == "}")) }) { working_set.exit_scope(); } let call_span = Span::concat(spans); let decl = working_set.get_decl(decl_id); let sig = decl.signature(); // Let's get our block and make sure it has the right signature if let Some(arg) = call.positional_nth(2) { match arg { Expression { expr: Expr::Closure(block_id), .. } => { // Custom command bodies' are compiled eagerly // 1. `module`s are not compiled, since they aren't ran/don't have any // executable code. So `def`s inside modules have to be compiled by // themselves. // 2. `def` calls in scripts/runnable code don't *run* any code either, // they are handled completely by the parser. compile_block_with_id(working_set, *block_id); working_set.get_block_mut(*block_id).signature = Box::new(sig.clone()); } _ => working_set.error(ParseError::Expected( "definition body closure { ... }", arg.span, )), } } if call_kind != CallKind::Valid { return ( Expression::new(working_set, Expr::Call(call), call_span, output), None, ); } (call, call_span) } }; let Ok(has_env) = has_flag_const(working_set, &call, "env") else { return garbage_result(working_set); }; let Ok(has_wrapped) = has_flag_const(working_set, &call, "wrapped") else { return garbage_result(working_set); }; // All positional arguments must be in the call positional vector by this point let name_expr = call.positional_nth(0).expect("def call already checked"); let sig = call.positional_nth(1).expect("def call already checked"); let block = call.positional_nth(2).expect("def call already checked"); let name = if let Some(name) = name_expr.as_string() { if let Some(mod_name) = module_name && name.as_bytes() == mod_name { let name_expr_span = name_expr.span; working_set.error(ParseError::NamedAsModule( "command".to_string(), name, "main".to_string(), name_expr_span, )); return ( Expression::new(working_set, Expr::Call(call), call_span, Type::Any), None, ); } name } else { working_set.error(ParseError::UnknownState( "Could not get string from string expression".into(), name_expr.span, )); return garbage_result(working_set); }; let mut result = None; if let (Some(mut signature), Some(block_id)) = (sig.as_signature(), block.as_block()) { for arg_name in &signature.required_positional { verify_not_reserved_variable_name(working_set, &arg_name.name, sig.span); } for arg_name in &signature.optional_positional { verify_not_reserved_variable_name(working_set, &arg_name.name, sig.span); } if let Some(arg_name) = &signature.rest_positional { verify_not_reserved_variable_name(working_set, &arg_name.name, sig.span); } for flag_name in &signature.get_names() { verify_not_reserved_variable_name(working_set, flag_name, sig.span); } if has_wrapped { if let Some(rest) = &signature.rest_positional { if let Some(var_id) = rest.var_id { let rest_var = &working_set.get_variable(var_id); if rest_var.ty != Type::Any && rest_var.ty != Type::List(Box::new(Type::String)) { working_set.error(ParseError::TypeMismatchHelp( Type::List(Box::new(Type::String)), rest_var.ty.clone(), rest_var.declaration_span, format!("...rest-like positional argument used in 'def --wrapped' supports only strings. Change the type annotation of ...{} to 'string'.", &rest.name))); return ( Expression::new(working_set, Expr::Call(call), call_span, Type::Any), result, ); } } } else { working_set.error(ParseError::MissingPositional("...rest-like positional argument".to_string(), name_expr.span, "def --wrapped must have a ...rest-like positional argument. Add '...rest: string' to the command's signature.".to_string())); return ( Expression::new(working_set, Expr::Call(call), call_span, Type::Any), result, ); } } if let Some(decl_id) = working_set.find_predecl(name.as_bytes()) { signature.name.clone_from(&name); if !has_wrapped { *signature = signature.add_help(); } signature.description = desc; signature.extra_description = extra_desc; signature.allows_unknown_args = has_wrapped; let (attribute_vals, examples) = handle_special_attributes(attributes, working_set, &mut signature); let declaration = working_set.get_decl_mut(decl_id); *declaration = signature .clone() .into_block_command(block_id, attribute_vals, examples); let block = working_set.get_block_mut(block_id); block.signature = signature; block.redirect_env = has_env; if block.signature.input_output_types.is_empty() { block .signature .input_output_types .push((Type::Any, Type::Any)); } let block = working_set.get_block(block_id); let typecheck_errors = check_block_input_output(working_set, block); working_set .parse_errors .extend_from_slice(&typecheck_errors); result = Some((name.as_bytes().to_vec(), decl_id)); } else { working_set.error(ParseError::InternalError( "Predeclaration failed to add declaration".into(), name_expr.span, )); }; } // It's OK if it returns None: The decl was already merged in previous parse pass. working_set.merge_predecl(name.as_bytes()); ( Expression::new(working_set, Expr::Call(call), call_span, Type::Any), result, ) } fn parse_extern_inner( working_set: &mut StateWorkingSet, attributes: Vec<(String, Value)>, lite_command: &LiteCommand, module_name: Option<&[u8]>, ) -> Expression { let spans = lite_command.command_parts(); let (description, extra_description) = working_set.build_desc(&lite_command.comments); // Checking that the function is used with the correct name // Maybe this is not necessary but it is a sanity check let (name_span, split_id) = if spans.len() > 1 && (working_set.get_span_contents(spans[0]) == b"export") { (spans[1], 2) } else { (spans[0], 1) }; let extern_call = working_set.get_span_contents(name_span); if extern_call != b"extern" { working_set.error(ParseError::UnknownState( "internal error: Wrong call name for extern command".into(), Span::concat(spans), )); return garbage(working_set, Span::concat(spans)); } if let Some(redirection) = lite_command.redirection.as_ref() { working_set.error(redirecting_builtin_error("extern", redirection)); return garbage(working_set, Span::concat(spans)); } // Parsing the spans and checking that they match the register signature // Using a parsed call makes more sense than checking for how many spans are in the call // Also, by creating a call, it can be checked if it matches the declaration signature // // NOTE: Here we only search for `extern` in the permanent state, // since recursively redefining `extern` is dangerous, // see https://github.com/nushell/nushell/issues/16586 let (call, call_span) = match working_set.permanent().find_decl(extern_call, &[]) { None => { working_set.error(ParseError::UnknownState( "internal error: def declaration not found".into(), Span::concat(spans), )); return garbage(working_set, Span::concat(spans)); } Some(decl_id) => { working_set.enter_scope(); let (command_spans, rest_spans) = spans.split_at(split_id); if let Some(name_span) = rest_spans.first() && let Some(err) = detect_params_in_name(working_set, *name_span, decl_id) { working_set.error(err); return garbage(working_set, Span::concat(spans)); } let ParsedInternalCall { call, .. } = parse_internal_call( working_set, Span::concat(command_spans), rest_spans, decl_id, ArgumentParsingLevel::Full, ); working_set.exit_scope(); let call_span = Span::concat(spans); (call, call_span) } }; let name_expr = call.positional_nth(0); let sig = call.positional_nth(1); let body = call.positional_nth(2); if let (Some(name_expr), Some(sig)) = (name_expr, sig) { if let (Some(name), Some(mut signature)) = (&name_expr.as_string(), sig.as_signature()) { if let Some(mod_name) = module_name && name.as_bytes() == mod_name { let name_expr_span = name_expr.span; working_set.error(ParseError::NamedAsModule( "known external".to_string(), name.clone(), "main".to_string(), name_expr_span, )); return Expression::new(working_set, Expr::Call(call), call_span, Type::Any); } if let Some(decl_id) = working_set.find_predecl(name.as_bytes()) { let external_name = if let Some(mod_name) = module_name { if name.as_bytes() == b"main" { String::from_utf8_lossy(mod_name).to_string() } else { name.clone() } } else { name.clone() }; signature.name = external_name; signature.description = description; signature.extra_description = extra_description; signature.allows_unknown_args = true; let (attribute_vals, examples) = handle_special_attributes(attributes, working_set, &mut signature); let declaration = working_set.get_decl_mut(decl_id); if let Some(block_id) = body.and_then(|x| x.as_block()) { if signature.rest_positional.is_none() { working_set.error(ParseError::InternalError( "Extern block must have a rest positional argument".into(), name_expr.span, )); } else { *declaration = signature.clone().into_block_command( block_id, attribute_vals, examples, ); working_set.get_block_mut(block_id).signature = signature; } } else { if signature.rest_positional.is_none() {
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
true
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-parser/src/lib.rs
crates/nu-parser/src/lib.rs
#![doc = include_str!("../README.md")] mod deparse; mod exportable; mod flatten; mod known_external; mod lex; mod lite_parser; mod parse_keywords; mod parse_patterns; mod parse_shape_specs; mod parser; mod type_check; pub use deparse::escape_for_script_arg; pub use flatten::{ FlatShape, flatten_block, flatten_expression, flatten_pipeline, flatten_pipeline_element, }; pub use known_external::KnownExternal; pub use lex::{LexState, Token, TokenContents, lex, lex_n_tokens, lex_signature}; pub use lite_parser::{LiteBlock, LiteCommand, lite_parse}; pub use nu_protocol::parser_path::*; pub use parse_keywords::*; pub use parser::{ DURATION_UNIT_GROUPS, is_math_expression_like, parse, parse_block, parse_expression, parse_external_call, parse_unit_value, trim_quotes, trim_quotes_str, unescape_unquote_string, };
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-parser/src/parser.rs
crates/nu-parser/src/parser.rs
#![allow(clippy::byte_char_slices)] use crate::{ Token, TokenContents, lex::{LexState, is_assignment_operator, lex, lex_n_tokens, lex_signature}, lite_parser::{LiteCommand, LitePipeline, LiteRedirection, LiteRedirectionTarget, lite_parse}, parse_keywords::*, parse_patterns::parse_pattern, parse_shape_specs::{parse_completer, parse_shape_name, parse_type}, type_check::{self, check_range_types, math_result_type, type_compatible}, }; use itertools::Itertools; use log::trace; use nu_engine::DIR_VAR_PARSER_INFO; use nu_protocol::{ BlockId, DeclId, DidYouMean, ENV_VARIABLE_ID, FilesizeUnit, Flag, IN_VARIABLE_ID, ParseError, PositionalArg, ShellError, Signature, Span, Spanned, SyntaxShape, Type, Value, VarId, ast::*, casing::Casing, did_you_mean, engine::StateWorkingSet, eval_const::eval_constant, }; use std::{ collections::{HashMap, HashSet}, str, sync::Arc, }; pub fn garbage(working_set: &mut StateWorkingSet, span: Span) -> Expression { Expression::garbage(working_set, span) } pub fn garbage_pipeline(working_set: &mut StateWorkingSet, spans: &[Span]) -> Pipeline { Pipeline::from_vec(vec![garbage(working_set, Span::concat(spans))]) } fn is_identifier_byte(b: u8) -> bool { b != b'.' && b != b'[' && b != b'(' && b != b'{' && b != b'+' && b != b'-' && b != b'*' && b != b'^' && b != b'/' && b != b'=' && b != b'!' && b != b'<' && b != b'>' && b != b'&' && b != b'|' } pub fn is_math_expression_like(working_set: &mut StateWorkingSet, span: Span) -> bool { let bytes = working_set.get_span_contents(span); if bytes.is_empty() { return false; } if bytes == b"true" || bytes == b"false" || bytes == b"null" || bytes == b"not" || bytes == b"if" || bytes == b"match" { return true; } let b = bytes[0]; // check for raw string if bytes.starts_with(b"r#") { return true; } if b == b'(' || b == b'{' || b == b'[' || b == b'$' || b == b'"' || b == b'\'' || b == b'-' { return true; } let starting_error_count = working_set.parse_errors.len(); // Number parse_number(working_set, span); if working_set.parse_errors.len() == starting_error_count { return true; } working_set.parse_errors.truncate(starting_error_count); // Filesize parse_filesize(working_set, span); if working_set.parse_errors.len() == starting_error_count { return true; } working_set.parse_errors.truncate(starting_error_count); parse_duration(working_set, span); if working_set.parse_errors.len() == starting_error_count { return true; } working_set.parse_errors.truncate(starting_error_count); parse_datetime(working_set, span); if working_set.parse_errors.len() == starting_error_count { return true; } working_set.parse_errors.truncate(starting_error_count); parse_binary(working_set, span); // We need an additional negate match to check if the last error was unexpected // or more specifically, if it was `ParseError::InvalidBinaryString`. // If so, we suppress the error and stop parsing to the next (which is `parse_range()`). if working_set.parse_errors.len() == starting_error_count { return true; } else if !matches!( working_set.parse_errors.last(), Some(ParseError::Expected(_, _)) ) { working_set.parse_errors.truncate(starting_error_count); return true; } working_set.parse_errors.truncate(starting_error_count); let is_range = parse_range(working_set, span).is_some(); working_set.parse_errors.truncate(starting_error_count); is_range } fn is_env_variable_name(bytes: &[u8]) -> bool { if bytes.is_empty() { return false; } let first = bytes[0]; if !first.is_ascii_alphabetic() && first != b'_' { return false; } bytes .iter() .skip(1) .all(|&b| b.is_ascii_alphanumeric() || b == b'_') } fn is_identifier(bytes: &[u8]) -> bool { bytes.iter().all(|x| is_identifier_byte(*x)) } pub fn is_variable(bytes: &[u8]) -> bool { if bytes.len() > 1 && bytes[0] == b'$' { is_identifier(&bytes[1..]) } else { is_identifier(bytes) } } pub fn trim_quotes(bytes: &[u8]) -> &[u8] { if (bytes.starts_with(b"\"") && bytes.ends_with(b"\"") && bytes.len() > 1) || (bytes.starts_with(b"\'") && bytes.ends_with(b"\'") && bytes.len() > 1) || (bytes.starts_with(b"`") && bytes.ends_with(b"`") && bytes.len() > 1) { &bytes[1..(bytes.len() - 1)] } else { bytes } } pub fn trim_quotes_str(s: &str) -> &str { if (s.starts_with('"') && s.ends_with('"') && s.len() > 1) || (s.starts_with('\'') && s.ends_with('\'') && s.len() > 1) || (s.starts_with('`') && s.ends_with('`') && s.len() > 1) { &s[1..(s.len() - 1)] } else { s } } /// Return type of `check_call` #[derive(Debug, PartialEq, Eq)] pub enum CallKind { Help, Valid, Invalid, } pub(crate) fn check_call( working_set: &mut StateWorkingSet, command: Span, sig: &Signature, call: &Call, ) -> CallKind { // Allow the call to pass if they pass in the help flag if call.named_iter().any(|(n, _, _)| n.item == "help") { return CallKind::Help; } if call.positional_len() < sig.required_positional.len() { let end_offset = call .positional_iter() .last() .map(|last| last.span.end) .unwrap_or(command.end); // Comparing the types of all signature positional arguments against the parsed // expressions found in the call. If one type is not found then it could be assumed // that that positional argument is missing from the parsed call for argument in &sig.required_positional { let found = call.positional_iter().fold(false, |ac, expr| { if argument.shape.to_type() == expr.ty || argument.shape == SyntaxShape::Any { true } else { ac } }); if !found { working_set.error(ParseError::MissingPositional( argument.name.clone(), Span::new(end_offset, end_offset), sig.call_signature(), )); return CallKind::Invalid; } } let missing = &sig.required_positional[call.positional_len()]; working_set.error(ParseError::MissingPositional( missing.name.clone(), Span::new(end_offset, end_offset), sig.call_signature(), )); return CallKind::Invalid; } else { for req_flag in sig.named.iter().filter(|x| x.required) { if call.named_iter().all(|(n, _, _)| n.item != req_flag.long) { working_set.error(ParseError::MissingRequiredFlag( req_flag.long.clone(), command, )); return CallKind::Invalid; } } } CallKind::Valid } /// Parses an unknown argument for the given signature. This handles the parsing as appropriate to /// the rest type of the command. fn parse_unknown_arg( working_set: &mut StateWorkingSet, span: Span, signature: &Signature, ) -> Expression { let shape = signature .rest_positional .as_ref() .map(|arg| arg.shape.clone()) .unwrap_or(SyntaxShape::Any); parse_value(working_set, span, &shape) } /// Parses a string in the arg or head position of an external call. /// /// If the string begins with `r#`, it is parsed as a raw string. If it doesn't contain any quotes /// or parentheses, it is parsed as a glob pattern so that tilde and glob expansion can be handled /// by `run-external`. Otherwise, we use a custom state machine to put together an interpolated /// string, where each balanced pair of quotes is parsed as a separate part of the string, and then /// concatenated together. /// /// For example, `-foo="bar\nbaz"` becomes `$"-foo=bar\nbaz"` fn parse_external_string(working_set: &mut StateWorkingSet, span: Span) -> Expression { let contents = working_set.get_span_contents(span); if contents.starts_with(b"r#") { parse_raw_string(working_set, span) } else if contents .iter() .any(|b| matches!(b, b'"' | b'\'' | b'(' | b')' | b'`')) { enum State { Bare { from: usize, }, BackTickQuote { from: usize, }, Quote { from: usize, quote_char: u8, escaped: bool, }, Parenthesized { from: usize, depth: usize, }, } // Find the spans of parts of the string that can be parsed as their own strings for // concatenation. // // By passing each of these parts to `parse_string()`, we can eliminate the quotes and also // handle string interpolation. let make_span = |from: usize, index: usize| Span { start: span.start + from, end: span.start + index, }; let mut spans = vec![]; let mut state = State::Bare { from: 0 }; let mut index = 0; while index < contents.len() { let ch = contents[index]; match &mut state { State::Bare { from } => match ch { b'"' | b'\'' => { // Push bare string if index != *from { spans.push(make_span(*from, index)); } // then transition to other state state = State::Quote { from: index, quote_char: ch, escaped: false, }; } b'$' => { if let Some(&quote_char @ (b'"' | b'\'')) = contents.get(index + 1) { // Start a dollar quote (interpolated string) if index != *from { spans.push(make_span(*from, index)); } state = State::Quote { from: index, quote_char, escaped: false, }; // Skip over two chars (the dollar sign and the quote) index += 2; continue; } } b'`' => { if index != *from { spans.push(make_span(*from, index)) } state = State::BackTickQuote { from: index } } b'(' => { if index != *from { spans.push(make_span(*from, index)) } state = State::Parenthesized { from: index, depth: 1, } } // Continue to consume _ => (), }, State::Quote { from, quote_char, escaped, } => match ch { ch if ch == *quote_char && !*escaped => { // quoted string ended, just make a new span for it. spans.push(make_span(*from, index + 1)); // go back to Bare state. state = State::Bare { from: index + 1 }; } b'\\' if !*escaped && *quote_char == b'"' => { // The next token is escaped so it doesn't count (only for double quote) *escaped = true; } _ => { *escaped = false; } }, State::BackTickQuote { from } => { if ch == b'`' { spans.push(make_span(*from, index + 1)); state = State::Bare { from: index + 1 }; } } State::Parenthesized { from, depth } => { if ch == b')' { if *depth == 1 { spans.push(make_span(*from, index + 1)); state = State::Bare { from: index + 1 }; } else { *depth -= 1; } } else if ch == b'(' { *depth += 1; } } } index += 1; } // Add the final span match state { State::Bare { from } | State::Quote { from, .. } | State::Parenthesized { from, .. } | State::BackTickQuote { from, .. } => { if from < contents.len() { spans.push(make_span(from, contents.len())); } } } // Log the spans that will be parsed if log::log_enabled!(log::Level::Trace) { let contents = spans .iter() .map(|span| String::from_utf8_lossy(working_set.get_span_contents(*span))) .collect::<Vec<_>>(); trace!("parsing: external string, parts: {contents:?}") } // Check if the whole thing is quoted. If not, it should be a glob let quoted = (contents.len() >= 3 && contents.starts_with(b"$\"") && contents.ends_with(b"\"")) || is_quoted(contents); // Parse each as its own string let exprs: Vec<Expression> = spans .into_iter() .map(|span| parse_string(working_set, span)) .collect(); if exprs .iter() .all(|expr| matches!(expr.expr, Expr::String(..))) { // If the exprs are all strings anyway, just collapse into a single string. let string = exprs .into_iter() .map(|expr| { let Expr::String(contents) = expr.expr else { unreachable!("already checked that this was a String") }; contents }) .collect::<String>(); if quoted { Expression::new(working_set, Expr::String(string), span, Type::String) } else { Expression::new( working_set, Expr::GlobPattern(string, false), span, Type::Glob, ) } } else { // Flatten any string interpolations contained with the exprs. let exprs = exprs .into_iter() .flat_map(|expr| match expr.expr { Expr::StringInterpolation(subexprs) => subexprs, _ => vec![expr], }) .collect(); // Make an interpolation out of the expressions. Use `GlobInterpolation` if it's a bare // word, so that the unquoted state can get passed through to `run-external`. if quoted { Expression::new( working_set, Expr::StringInterpolation(exprs), span, Type::String, ) } else { Expression::new( working_set, Expr::GlobInterpolation(exprs, false), span, Type::Glob, ) } } } else { parse_glob_pattern(working_set, span) } } fn parse_external_arg(working_set: &mut StateWorkingSet, span: Span) -> ExternalArgument { let contents = working_set.get_span_contents(span); if contents.len() > 3 && contents.starts_with(b"...") && (contents[3] == b'$' || contents[3] == b'[' || contents[3] == b'(') { ExternalArgument::Spread(parse_value( working_set, Span::new(span.start + 3, span.end), &SyntaxShape::List(Box::new(SyntaxShape::Any)), )) } else { ExternalArgument::Regular(parse_regular_external_arg(working_set, span)) } } fn parse_regular_external_arg(working_set: &mut StateWorkingSet, span: Span) -> Expression { let contents = working_set.get_span_contents(span); if contents.starts_with(b"$") { parse_dollar_expr(working_set, span) } else if contents.starts_with(b"(") { parse_paren_expr(working_set, span, &SyntaxShape::Any) } else if contents.starts_with(b"[") { parse_list_expression(working_set, span, &SyntaxShape::Any) } else { parse_external_string(working_set, span) } } pub fn parse_external_call(working_set: &mut StateWorkingSet, spans: &[Span]) -> Expression { trace!("parse external"); let head_contents = working_set.get_span_contents(spans[0]); let head_span = if head_contents.starts_with(b"^") { Span::new(spans[0].start + 1, spans[0].end) } else { spans[0] }; let head_contents = working_set.get_span_contents(head_span).to_vec(); let head = if head_contents.starts_with(b"$") || head_contents.starts_with(b"(") { // the expression is inside external_call, so it's a subexpression let arg = parse_expression(working_set, &[head_span]); Box::new(arg) } else { Box::new(parse_external_string(working_set, head_span)) }; let args = spans[1..] .iter() .map(|&span| parse_external_arg(working_set, span)) .collect(); Expression::new( working_set, Expr::ExternalCall(head, args), Span::concat(spans), Type::Any, ) } fn ensure_flag_arg_type( working_set: &mut StateWorkingSet, arg_name: String, arg: Expression, arg_shape: &SyntaxShape, long_name_span: Span, ) -> (Spanned<String>, Expression) { if !type_compatible(&arg.ty, &arg_shape.to_type()) { working_set.error(ParseError::TypeMismatch( arg_shape.to_type(), arg.ty, arg.span, )); ( Spanned { item: arg_name, span: long_name_span, }, Expression::garbage(working_set, arg.span), ) } else { ( Spanned { item: arg_name, span: long_name_span, }, arg, ) } } fn parse_long_flag( working_set: &mut StateWorkingSet, spans: &[Span], spans_idx: &mut usize, sig: &Signature, ) -> (Option<Spanned<String>>, Option<Expression>) { let arg_span = spans[*spans_idx]; let arg_contents = working_set.get_span_contents(arg_span); if arg_contents.starts_with(b"--") { // FIXME: only use the first flag you find? let split: Vec<_> = arg_contents.split(|x| *x == b'=').collect(); let long_name = String::from_utf8(split[0].into()); if let Ok(long_name) = long_name { let long_name = long_name[2..].to_string(); if let Some(flag) = sig.get_long_flag(&long_name) { if let Some(arg_shape) = &flag.arg { if split.len() > 1 { // and we also have the argument let long_name_len = long_name.len(); let mut span = arg_span; span.start += long_name_len + 3; //offset by long flag and '=' let arg = parse_value(working_set, span, arg_shape); let (arg_name, val_expression) = ensure_flag_arg_type( working_set, long_name, arg, arg_shape, Span::new(arg_span.start, arg_span.start + long_name_len + 2), ); (Some(arg_name), Some(val_expression)) } else if let Some(arg) = spans.get(*spans_idx + 1) { let arg = parse_value(working_set, *arg, arg_shape); *spans_idx += 1; let (arg_name, val_expression) = ensure_flag_arg_type(working_set, long_name, arg, arg_shape, arg_span); (Some(arg_name), Some(val_expression)) } else { working_set.error(ParseError::MissingFlagParam( arg_shape.to_string(), arg_span, )); // NOTE: still need to cover this incomplete flag in the final expression // see https://github.com/nushell/nushell/issues/16375 ( Some(Spanned { item: long_name, span: arg_span, }), None, ) } } else { // A flag with no argument // It can also takes a boolean value like --x=true if split.len() > 1 { // and we also have the argument let long_name_len = long_name.len(); let mut span = arg_span; span.start += long_name_len + 3; //offset by long flag and '=' let arg = parse_value(working_set, span, &SyntaxShape::Boolean); let (arg_name, val_expression) = ensure_flag_arg_type( working_set, long_name, arg, &SyntaxShape::Boolean, Span::new(arg_span.start, arg_span.start + long_name_len + 2), ); (Some(arg_name), Some(val_expression)) } else { ( Some(Spanned { item: long_name, span: arg_span, }), None, ) } } } else { let suggestion = did_you_mean(sig.get_names(), &long_name) .map(|name| format!("Did you mean: `--{name}`?")) .unwrap_or("Use `--help` to see available flags".to_owned()); working_set.error(ParseError::UnknownFlag( sig.name.clone(), long_name.clone(), arg_span, suggestion, )); ( Some(Spanned { item: long_name.clone(), span: arg_span, }), None, ) } } else { working_set.error(ParseError::NonUtf8(arg_span)); ( Some(Spanned { item: "--".into(), span: arg_span, }), None, ) } } else { (None, None) } } fn parse_short_flags( working_set: &mut StateWorkingSet, spans: &[Span], spans_idx: &mut usize, positional_idx: usize, sig: &Signature, ) -> Option<Vec<Flag>> { let arg_span = spans[*spans_idx]; let arg_contents = working_set.get_span_contents(arg_span); if let Ok(arg_contents_uft8_ref) = str::from_utf8(arg_contents) { if arg_contents_uft8_ref.starts_with('-') && arg_contents_uft8_ref.len() > 1 { let short_flags = &arg_contents_uft8_ref[1..]; let num_chars = short_flags.chars().count(); let mut found_short_flags = vec![]; let mut unmatched_short_flags = vec![]; for (offset, short_flag) in short_flags.char_indices() { let short_flag_span = Span::new( arg_span.start + 1 + offset, arg_span.start + 1 + offset + short_flag.len_utf8(), ); if let Some(flag) = sig.get_short_flag(short_flag) { // Allow args in short flag batches as long as it is the last flag. if flag.arg.is_some() && offset < num_chars - 1 { working_set .error(ParseError::OnlyLastFlagInBatchCanTakeArg(short_flag_span)); break; } found_short_flags.push(flag); } else { unmatched_short_flags.push(short_flag_span); } } if found_short_flags.is_empty() // check to see if we have a negative number && matches!( sig.get_positional(positional_idx), Some(PositionalArg { shape: SyntaxShape::Int | SyntaxShape::Number | SyntaxShape::Float, .. }) ) && String::from_utf8_lossy(working_set.get_span_contents(arg_span)) .parse::<f64>() .is_ok() { return None; } else if let Some(first) = unmatched_short_flags.first() { let contents = working_set.get_span_contents(*first); working_set.error(ParseError::UnknownFlag( sig.name.clone(), format!("-{}", String::from_utf8_lossy(contents)), *first, "Use `--help` to see available flags".to_owned(), )); } Some(found_short_flags) } else { None } } else { working_set.error(ParseError::NonUtf8(arg_span)); None } } fn first_kw_idx( working_set: &StateWorkingSet, signature: &Signature, spans: &[Span], spans_idx: usize, positional_idx: usize, ) -> (Option<usize>, usize) { for idx in (positional_idx + 1)..signature.num_positionals() { if let Some(PositionalArg { shape: SyntaxShape::Keyword(kw, ..), .. }) = signature.get_positional(idx) { for (span_idx, &span) in spans.iter().enumerate().skip(spans_idx) { let contents = working_set.get_span_contents(span); if contents == kw { return (Some(idx), span_idx); } } } } (None, spans.len()) } fn calculate_end_span( working_set: &StateWorkingSet, signature: &Signature, spans: &[Span], spans_idx: usize, positional_idx: usize, ) -> usize { if signature.rest_positional.is_some() { spans.len() } else { let (kw_pos, kw_idx) = first_kw_idx(working_set, signature, spans, spans_idx, positional_idx); if let Some(kw_pos) = kw_pos { // We found a keyword. Keywords, once found, create a guidepost to // show us where the positionals will lay into the arguments. Because they're // keywords, they get to set this by being present let positionals_between = kw_pos - positional_idx - 1; if positionals_between >= (kw_idx - spans_idx) { kw_idx } else { kw_idx - positionals_between } } else { // Make space for the remaining require positionals, if we can // spans_idx < spans.len() is an invariant let remaining_spans = spans.len() - (spans_idx + 1); // positional_idx can be larger than required_positional.len() if we have optional args let remaining_positional = signature .required_positional .len() .saturating_sub(positional_idx + 1); // Saturates to 0 when we have too few args let extra_spans = remaining_spans.saturating_sub(remaining_positional); spans_idx + 1 + extra_spans } } } fn parse_oneof( working_set: &mut StateWorkingSet, spans: &[Span], spans_idx: &mut usize, possible_shapes: &Vec<SyntaxShape>, multispan: bool, ) -> Expression { let starting_spans_idx = *spans_idx; let mut best_guess = None; let mut best_guess_errors = Vec::new(); let mut max_first_error_offset = 0; let mut propagate_error = false; for shape in possible_shapes { let starting_error_count = working_set.parse_errors.len(); *spans_idx = starting_spans_idx; let value = match multispan { true => parse_multispan_value(working_set, spans, spans_idx, shape), false => parse_value(working_set, spans[*spans_idx], shape), }; let new_errors = working_set.parse_errors[starting_error_count..].to_vec(); // no new errors found means success let Some(first_error_offset) = new_errors.iter().map(|e| e.span().start).min() else { return value; }; if first_error_offset > max_first_error_offset { // while trying the possible shapes, ignore Expected type errors // unless they're inside a block, closure, or expression propagate_error = match working_set.parse_errors.last() { Some(ParseError::Expected(_, error_span)) | Some(ParseError::ExpectedWithStringMsg(_, error_span)) => { matches!( shape, SyntaxShape::Block | SyntaxShape::Closure(_) | SyntaxShape::Expression ) && *error_span != spans[*spans_idx] } _ => true, }; max_first_error_offset = first_error_offset; best_guess = Some(value); best_guess_errors = new_errors; } working_set.parse_errors.truncate(starting_error_count); } // if best_guess results in new errors further than current span, then accept it // or propagate_error is marked as true for it if max_first_error_offset > spans[starting_spans_idx].start || propagate_error { working_set.parse_errors.extend(best_guess_errors); best_guess.expect("best_guess should not be None here!") } else { working_set.error(ParseError::ExpectedWithStringMsg( format!("one of a list of accepted shapes: {possible_shapes:?}"), spans[starting_spans_idx], )); Expression::garbage(working_set, spans[starting_spans_idx]) } } pub fn parse_multispan_value( working_set: &mut StateWorkingSet, spans: &[Span], spans_idx: &mut usize, shape: &SyntaxShape, ) -> Expression { trace!("parse multispan value"); match shape { SyntaxShape::VarWithOptType => { trace!("parsing: var with opt type"); parse_var_with_opt_type(working_set, spans, spans_idx, false).0 } SyntaxShape::RowCondition => { trace!("parsing: row condition"); let arg = parse_row_condition(working_set, &spans[*spans_idx..]); *spans_idx = spans.len() - 1; arg } SyntaxShape::MathExpression => { trace!("parsing: math expression"); let arg = parse_math_expression(working_set, &spans[*spans_idx..], None); *spans_idx = spans.len() - 1; arg } SyntaxShape::OneOf(possible_shapes) => { parse_oneof(working_set, spans, spans_idx, possible_shapes, true) } SyntaxShape::Expression => { trace!("parsing: expression");
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
true
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-parser/src/flatten.rs
crates/nu-parser/src/flatten.rs
use nu_protocol::{ DeclId, GetSpan, Span, SyntaxShape, VarId, ast::{ Argument, Block, Expr, Expression, ExternalArgument, ImportPatternMember, ListItem, MatchPattern, PathMember, Pattern, Pipeline, PipelineElement, PipelineRedirection, RecordItem, }, engine::StateWorkingSet, }; use std::fmt::{Display, Formatter, Result}; #[derive(Debug, Eq, PartialEq, Ord, Clone, PartialOrd)] pub enum FlatShape { Binary, Block, Bool, Closure, Custom(DeclId), DateTime, Directory, // The stored span contains the call's head if this call is through an alias: // This is only different from the name of the called external command, // and is only useful for its location (not its contents). External(Box<Span>), ExternalArg, ExternalResolved, Filepath, Flag, Float, Garbage, GlobInterpolation, GlobPattern, Int, InternalCall(DeclId), Keyword, List, Literal, MatchPattern, Nothing, Operator, Pipe, Range, RawString, Record, Redirection, Signature, String, StringInterpolation, Table, Variable(VarId), VarDecl(VarId), } impl FlatShape { pub fn as_str(&self) -> &str { match self { FlatShape::Binary => "shape_binary", FlatShape::Block => "shape_block", FlatShape::Bool => "shape_bool", FlatShape::Closure => "shape_closure", FlatShape::Custom(_) => "shape_custom", FlatShape::DateTime => "shape_datetime", FlatShape::Directory => "shape_directory", FlatShape::External(_) => "shape_external", FlatShape::ExternalArg => "shape_externalarg", FlatShape::ExternalResolved => "shape_external_resolved", FlatShape::Filepath => "shape_filepath", FlatShape::Flag => "shape_flag", FlatShape::Float => "shape_float", FlatShape::Garbage => "shape_garbage", FlatShape::GlobInterpolation => "shape_glob_interpolation", FlatShape::GlobPattern => "shape_globpattern", FlatShape::Int => "shape_int", FlatShape::InternalCall(_) => "shape_internalcall", FlatShape::Keyword => "shape_keyword", FlatShape::List => "shape_list", FlatShape::Literal => "shape_literal", FlatShape::MatchPattern => "shape_match_pattern", FlatShape::Nothing => "shape_nothing", FlatShape::Operator => "shape_operator", FlatShape::Pipe => "shape_pipe", FlatShape::Range => "shape_range", FlatShape::RawString => "shape_raw_string", FlatShape::Record => "shape_record", FlatShape::Redirection => "shape_redirection", FlatShape::Signature => "shape_signature", FlatShape::String => "shape_string", FlatShape::StringInterpolation => "shape_string_interpolation", FlatShape::Table => "shape_table", FlatShape::Variable(_) => "shape_variable", FlatShape::VarDecl(_) => "shape_vardecl", } } } impl Display for FlatShape { fn fmt(&self, f: &mut Formatter) -> Result { f.write_str(self.as_str()) } } /* The `_into` functions below (e.g., `flatten_block_into`) take an existing `output` `Vec` and append more data to it. This is to reduce the number of intermediate `Vec`s. The non-`into` functions (e.g., `flatten_block`) are part of the crate's public API and return a new `Vec` instead of modifying an existing one. */ fn flatten_block_into( working_set: &StateWorkingSet, block: &Block, output: &mut Vec<(Span, FlatShape)>, ) { for pipeline in &block.pipelines { flatten_pipeline_into(working_set, pipeline, output); } } fn flatten_pipeline_into( working_set: &StateWorkingSet, pipeline: &Pipeline, output: &mut Vec<(Span, FlatShape)>, ) { for expr in &pipeline.elements { flatten_pipeline_element_into(working_set, expr, output) } } fn flatten_pipeline_element_into( working_set: &StateWorkingSet, pipeline_element: &PipelineElement, output: &mut Vec<(Span, FlatShape)>, ) { if let Some(span) = pipeline_element.pipe { output.push((span, FlatShape::Pipe)); } flatten_expression_into(working_set, &pipeline_element.expr, output); if let Some(redirection) = pipeline_element.redirection.as_ref() { match redirection { PipelineRedirection::Single { target, .. } => { output.push((target.span(), FlatShape::Redirection)); if let Some(expr) = target.expr() { flatten_expression_into(working_set, expr, output); } } PipelineRedirection::Separate { out, err } => { let (out, err) = if out.span() <= err.span() { (out, err) } else { (err, out) }; output.push((out.span(), FlatShape::Redirection)); if let Some(expr) = out.expr() { flatten_expression_into(working_set, expr, output); } output.push((err.span(), FlatShape::Redirection)); if let Some(expr) = err.expr() { flatten_expression_into(working_set, expr, output); } } } } } fn flatten_positional_arg_into( working_set: &StateWorkingSet, positional: &Expression, shape: &SyntaxShape, output: &mut Vec<(Span, FlatShape)>, ) { if matches!(shape, SyntaxShape::ExternalArgument) && matches!(positional.expr, Expr::String(..) | Expr::GlobPattern(..)) { // Make known external arguments look more like external arguments output.push((positional.span, FlatShape::ExternalArg)); } else { flatten_expression_into(working_set, positional, output) } } fn flatten_expression_into( working_set: &StateWorkingSet, expr: &Expression, output: &mut Vec<(Span, FlatShape)>, ) { match &expr.expr { Expr::AttributeBlock(ab) => { for attr in &ab.attributes { flatten_expression_into(working_set, &attr.expr, output); } flatten_expression_into(working_set, &ab.item, output); } Expr::BinaryOp(lhs, op, rhs) => { flatten_expression_into(working_set, lhs, output); flatten_expression_into(working_set, op, output); flatten_expression_into(working_set, rhs, output); } Expr::UnaryNot(not) => { output.push(( Span::new(expr.span.start, expr.span.start + 3), FlatShape::Operator, )); flatten_expression_into(working_set, not, output); } Expr::Collect(_, expr) => { flatten_expression_into(working_set, expr, output); } Expr::Closure(block_id) => { let outer_span = expr.span; let block = working_set.get_block(*block_id); let flattened = flatten_block(working_set, block); if let Some(first) = flattened.first() && first.0.start > outer_span.start { output.push(( Span::new(outer_span.start, first.0.start), FlatShape::Closure, )); } let last = if let Some(last) = flattened.last() { if last.0.end < outer_span.end { Some((Span::new(last.0.end, outer_span.end), FlatShape::Closure)) } else { None } } else { // for empty closures Some((outer_span, FlatShape::Closure)) }; output.extend(flattened); if let Some(last) = last { output.push(last); } } Expr::Block(block_id) | Expr::RowCondition(block_id) | Expr::Subexpression(block_id) => { let outer_span = expr.span; let flattened = flatten_block(working_set, working_set.get_block(*block_id)); if let Some(first) = flattened.first() && first.0.start > outer_span.start { output.push((Span::new(outer_span.start, first.0.start), FlatShape::Block)); } let last = if let Some(last) = flattened.last() { if last.0.end < outer_span.end { Some((Span::new(last.0.end, outer_span.end), FlatShape::Block)) } else { None } } else { None }; output.extend(flattened); if let Some(last) = last { output.push(last); } } Expr::Call(call) => { let decl = working_set.get_decl(call.decl_id); if call.head.end != 0 { // Make sure we don't push synthetic calls output.push((call.head, FlatShape::InternalCall(call.decl_id))); } // Follow positional arguments from the signature. let signature = decl.signature(); let mut positional_args = signature .required_positional .iter() .chain(&signature.optional_positional); let arg_start = output.len(); for arg in &call.arguments { match arg { Argument::Positional(positional) => { let positional_arg = positional_args.next(); let shape = positional_arg .or(signature.rest_positional.as_ref()) .map(|arg| &arg.shape) .unwrap_or(&SyntaxShape::Any); flatten_positional_arg_into(working_set, positional, shape, output) } Argument::Unknown(positional) => { let shape = signature .rest_positional .as_ref() .map(|arg| &arg.shape) .unwrap_or(&SyntaxShape::Any); flatten_positional_arg_into(working_set, positional, shape, output) } Argument::Named(named) => { if named.0.span.end != 0 { // Ignore synthetic flags output.push((named.0.span, FlatShape::Flag)); } if let Some(expr) = &named.2 { flatten_expression_into(working_set, expr, output); } } Argument::Spread(expr) => { output.push(( Span::new(expr.span.start - 3, expr.span.start), FlatShape::Operator, )); flatten_expression_into(working_set, expr, output); } } } // sort these since flags and positional args can be intermixed output[arg_start..].sort(); } Expr::ExternalCall(head, args) => { if let Expr::String(..) | Expr::GlobPattern(..) = &head.expr { // If this external call is through an alias, then head.span contains the // name of the alias (needed to highlight the right thing), but we also need // the name of the aliased command (to decide *how* to highlight the call). // The parser actually created this head by cloning from the alias's definition // and then just overwriting the `span` field - but `span_id` still points to // the original span, so we can recover it from there. let span = working_set.get_span(head.span_id); output.push((span, FlatShape::External(Box::new(head.span)))); } else { flatten_expression_into(working_set, head, output); } for arg in args.as_ref() { match arg { ExternalArgument::Regular(expr) => { if let Expr::String(..) | Expr::GlobPattern(..) = &expr.expr { output.push((expr.span, FlatShape::ExternalArg)); } else { flatten_expression_into(working_set, expr, output); } } ExternalArgument::Spread(expr) => { output.push(( Span::new(expr.span.start - 3, expr.span.start), FlatShape::Operator, )); flatten_expression_into(working_set, expr, output); } } } } Expr::Garbage => output.push((expr.span, FlatShape::Garbage)), Expr::Nothing => output.push((expr.span, FlatShape::Nothing)), Expr::DateTime(_) => output.push((expr.span, FlatShape::DateTime)), Expr::Binary(_) => output.push((expr.span, FlatShape::Binary)), Expr::Int(_) => output.push((expr.span, FlatShape::Int)), Expr::Float(_) => output.push((expr.span, FlatShape::Float)), Expr::MatchBlock(matches) => { for (pattern, expr) in matches { flatten_pattern_into(pattern, output); flatten_expression_into(working_set, expr, output); } } Expr::ValueWithUnit(value) => { flatten_expression_into(working_set, &value.expr, output); output.push((value.unit.span, FlatShape::String)); } Expr::CellPath(cell_path) => { output.extend(cell_path.members.iter().map(|member| match *member { PathMember::String { span, .. } => (span, FlatShape::String), PathMember::Int { span, .. } => (span, FlatShape::Int), })); } Expr::FullCellPath(cell_path) => { flatten_expression_into(working_set, &cell_path.head, output); output.extend(cell_path.tail.iter().map(|member| match *member { PathMember::String { span, .. } => (span, FlatShape::String), PathMember::Int { span, .. } => (span, FlatShape::Int), })); } Expr::ImportPattern(import_pattern) => { output.push((import_pattern.head.span, FlatShape::String)); for member in &import_pattern.members { match member { ImportPatternMember::Glob { span } => output.push((*span, FlatShape::String)), ImportPatternMember::Name { span, .. } => { output.push((*span, FlatShape::String)) } ImportPatternMember::List { names } => { output.extend(names.iter().map(|&(_, span)| (span, FlatShape::String))) } } } } Expr::Overlay(_) => output.push((expr.span, FlatShape::String)), Expr::Range(range) => { if let Some(f) = &range.from { flatten_expression_into(working_set, f, output); } if let Some(s) = &range.next { output.push((range.operator.next_op_span, FlatShape::Operator)); flatten_expression_into(working_set, s, output); } output.push((range.operator.span, FlatShape::Operator)); if let Some(t) = &range.to { flatten_expression_into(working_set, t, output); } } Expr::Bool(_) => output.push((expr.span, FlatShape::Bool)), Expr::Filepath(_, _) => output.push((expr.span, FlatShape::Filepath)), Expr::Directory(_, _) => output.push((expr.span, FlatShape::Directory)), Expr::GlobPattern(_, _) => output.push((expr.span, FlatShape::GlobPattern)), Expr::List(list) => { let outer_span = expr.span; let mut last_end = outer_span.start; for item in list { match item { ListItem::Item(expr) => { let flattened = flatten_expression(working_set, expr); if let Some(first) = flattened.first() && first.0.start > last_end { output.push((Span::new(last_end, first.0.start), FlatShape::List)); } if let Some(last) = flattened.last() { last_end = last.0.end; } output.extend(flattened); } ListItem::Spread(op_span, expr) => { if op_span.start > last_end { output.push((Span::new(last_end, op_span.start), FlatShape::List)); } output.push((*op_span, FlatShape::Operator)); last_end = op_span.end; let flattened_inner = flatten_expression(working_set, expr); if let Some(first) = flattened_inner.first() && first.0.start > last_end { output.push((Span::new(last_end, first.0.start), FlatShape::List)); } if let Some(last) = flattened_inner.last() { last_end = last.0.end; } output.extend(flattened_inner); } } } if last_end < outer_span.end { output.push((Span::new(last_end, outer_span.end), FlatShape::List)); } } Expr::StringInterpolation(exprs) => { let mut flattened = vec![]; for expr in exprs { flatten_expression_into(working_set, expr, &mut flattened); } if let Some(first) = flattened.first() && first.0.start != expr.span.start { // If we aren't a bare word interpolation, also highlight the outer quotes output.push(( Span::new(expr.span.start, expr.span.start + 2), FlatShape::StringInterpolation, )); flattened.push(( Span::new(expr.span.end - 1, expr.span.end), FlatShape::StringInterpolation, )); } output.extend(flattened); } Expr::GlobInterpolation(exprs, quoted) => { let mut flattened = vec![]; for expr in exprs { flatten_expression_into(working_set, expr, &mut flattened); } if *quoted { // If we aren't a bare word interpolation, also highlight the outer quotes output.push(( Span::new(expr.span.start, expr.span.start + 2), FlatShape::GlobInterpolation, )); flattened.push(( Span::new(expr.span.end - 1, expr.span.end), FlatShape::GlobInterpolation, )); } output.extend(flattened); } Expr::Record(list) => { let outer_span = expr.span; let mut last_end = outer_span.start; for l in list { match l { RecordItem::Pair(key, val) => { let flattened_lhs = flatten_expression(working_set, key); let flattened_rhs = flatten_expression(working_set, val); if let Some(first) = flattened_lhs.first() && first.0.start > last_end { output.push((Span::new(last_end, first.0.start), FlatShape::Record)); } if let Some(last) = flattened_lhs.last() { last_end = last.0.end; } output.extend(flattened_lhs); if let Some(first) = flattened_rhs.first() && first.0.start > last_end { output.push((Span::new(last_end, first.0.start), FlatShape::Record)); } if let Some(last) = flattened_rhs.last() { last_end = last.0.end; } output.extend(flattened_rhs); } RecordItem::Spread(op_span, record) => { if op_span.start > last_end { output.push((Span::new(last_end, op_span.start), FlatShape::Record)); } output.push((*op_span, FlatShape::Operator)); last_end = op_span.end; let flattened = flatten_expression(working_set, record); if let Some(first) = flattened.first() && first.0.start > last_end { output.push((Span::new(last_end, first.0.start), FlatShape::Record)); } if let Some(last) = flattened.last() { last_end = last.0.end; } output.extend(flattened); } } } if last_end < outer_span.end { output.push((Span::new(last_end, outer_span.end), FlatShape::Record)); } } Expr::Keyword(kw) => { output.push((kw.span, FlatShape::Keyword)); flatten_expression_into(working_set, &kw.expr, output); } Expr::Operator(_) => output.push((expr.span, FlatShape::Operator)), Expr::Signature(_) => output.push((expr.span, FlatShape::Signature)), Expr::String(_) => output.push((expr.span, FlatShape::String)), Expr::RawString(_) => output.push((expr.span, FlatShape::RawString)), Expr::Table(table) => { let outer_span = expr.span; let mut last_end = outer_span.start; for col in table.columns.as_ref() { let flattened = flatten_expression(working_set, col); if let Some(first) = flattened.first() && first.0.start > last_end { output.push((Span::new(last_end, first.0.start), FlatShape::Table)); } if let Some(last) = flattened.last() { last_end = last.0.end; } output.extend(flattened); } for row in table.rows.as_ref() { for expr in row.as_ref() { let flattened = flatten_expression(working_set, expr); if let Some(first) = flattened.first() && first.0.start > last_end { output.push((Span::new(last_end, first.0.start), FlatShape::Table)); } if let Some(last) = flattened.last() { last_end = last.0.end; } output.extend(flattened); } } if last_end < outer_span.end { output.push((Span::new(last_end, outer_span.end), FlatShape::Table)); } } Expr::Var(var_id) => output.push((expr.span, FlatShape::Variable(*var_id))), Expr::VarDecl(var_id) => output.push((expr.span, FlatShape::VarDecl(*var_id))), } } fn flatten_pattern_into(match_pattern: &MatchPattern, output: &mut Vec<(Span, FlatShape)>) { match &match_pattern.pattern { Pattern::Garbage => output.push((match_pattern.span, FlatShape::Garbage)), Pattern::IgnoreValue => output.push((match_pattern.span, FlatShape::Nothing)), Pattern::IgnoreRest => output.push((match_pattern.span, FlatShape::Nothing)), Pattern::List(items) => { if let Some(first) = items.first() { if let Some(last) = items.last() { output.push(( Span::new(match_pattern.span.start, first.span.start), FlatShape::MatchPattern, )); for item in items { flatten_pattern_into(item, output); } output.push(( Span::new(last.span.end, match_pattern.span.end), FlatShape::MatchPattern, )) } } else { output.push((match_pattern.span, FlatShape::MatchPattern)); } } Pattern::Record(items) => { if let Some(first) = items.first() { if let Some(last) = items.last() { output.push(( Span::new(match_pattern.span.start, first.1.span.start), FlatShape::MatchPattern, )); for (_, pattern) in items { flatten_pattern_into(pattern, output); } output.push(( Span::new(last.1.span.end, match_pattern.span.end), FlatShape::MatchPattern, )) } } else { output.push((match_pattern.span, FlatShape::MatchPattern)); } } Pattern::Expression(_) | Pattern::Value(_) => { output.push((match_pattern.span, FlatShape::MatchPattern)) } Pattern::Variable(var_id) => output.push((match_pattern.span, FlatShape::VarDecl(*var_id))), Pattern::Rest(var_id) => output.push((match_pattern.span, FlatShape::VarDecl(*var_id))), Pattern::Or(patterns) => { for pattern in patterns { flatten_pattern_into(pattern, output); } } } } pub fn flatten_block(working_set: &StateWorkingSet, block: &Block) -> Vec<(Span, FlatShape)> { let mut output = Vec::new(); flatten_block_into(working_set, block, &mut output); output } pub fn flatten_pipeline( working_set: &StateWorkingSet, pipeline: &Pipeline, ) -> Vec<(Span, FlatShape)> { let mut output = Vec::new(); flatten_pipeline_into(working_set, pipeline, &mut output); output } pub fn flatten_pipeline_element( working_set: &StateWorkingSet, pipeline_element: &PipelineElement, ) -> Vec<(Span, FlatShape)> { let mut output = Vec::new(); flatten_pipeline_element_into(working_set, pipeline_element, &mut output); output } pub fn flatten_expression( working_set: &StateWorkingSet, expr: &Expression, ) -> Vec<(Span, FlatShape)> { let mut output = Vec::new(); flatten_expression_into(working_set, expr, &mut output); output }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-parser/src/type_check.rs
crates/nu-parser/src/type_check.rs
use nu_protocol::{ ParseError, Span, Type, ast::{Assignment, Block, Comparison, Expr, Expression, Math, Operator, Pipeline, Range}, combined_type_string, engine::StateWorkingSet, }; fn type_error( op: Operator, op_span: Span, lhs: &Expression, rhs: &Expression, is_supported: fn(&Type) -> bool, ) -> (Type, Option<ParseError>) { let is_supported = |ty| is_supported(ty) || matches!(ty, Type::Any | Type::Custom(_)); let err = match (is_supported(&lhs.ty), is_supported(&rhs.ty)) { (true, true) => ParseError::OperatorIncompatibleTypes { op: op.as_str(), lhs: lhs.ty.clone(), rhs: rhs.ty.clone(), op_span, lhs_span: lhs.span, rhs_span: rhs.span, help: None, }, (true, false) => ParseError::OperatorUnsupportedType { op: op.as_str(), unsupported: rhs.ty.clone(), op_span, unsupported_span: rhs.span, help: None, }, (false, _) => ParseError::OperatorUnsupportedType { op: op.as_str(), unsupported: lhs.ty.clone(), op_span, unsupported_span: lhs.span, help: None, }, }; (Type::Any, Some(err)) } pub fn type_compatible(lhs: &Type, rhs: &Type) -> bool { // Structural subtyping let is_compatible = |expected: &[(String, Type)], found: &[(String, Type)]| { if expected.is_empty() || found.is_empty() { // We treat an incoming empty table/record type as compatible for typechecking purposes // It is the responsibility of the runtime to reject if necessary true } else if expected.len() > found.len() { false } else { expected.iter().all(|(col_x, ty_x)| { if let Some((_, ty_y)) = found.iter().find(|(col_y, _)| col_x == col_y) { type_compatible(ty_x, ty_y) } else { false } }) } }; match (lhs, rhs) { (Type::List(c), Type::List(d)) => type_compatible(c, d), (Type::List(c), Type::Table(table_fields)) => { if matches!(**c, Type::Any) { return true; } if let Type::Record(fields) = &**c { is_compatible(fields, table_fields) } else { false } } (Type::Table(table_fields), Type::List(c)) => { if matches!(**c, Type::Any) { return true; } if let Type::Record(fields) = &**c { is_compatible(table_fields, fields) } else { false } } (Type::Number, Type::Int) => true, (Type::Int, Type::Number) => true, (Type::Number, Type::Float) => true, (Type::Float, Type::Number) => true, (Type::Closure, Type::Block) => true, (Type::Any, _) => true, (_, Type::Any) => true, (Type::Record(lhs), Type::Record(rhs)) | (Type::Table(lhs), Type::Table(rhs)) => { is_compatible(lhs, rhs) } (Type::Glob, Type::String) => true, (Type::CellPath, other) => { other.is_subtype_of(&Type::CellPath) || Type::CellPath.is_subtype_of(other) } (Type::OneOf(types), u) | (u, Type::OneOf(types)) => { types.iter().any(|t| type_compatible(t, u)) } (lhs, rhs) => lhs == rhs, } } // TODO: rework type checking for Custom values pub fn math_result_type( working_set: &mut StateWorkingSet, lhs: &mut Expression, op: &mut Expression, rhs: &mut Expression, ) -> (Type, Option<ParseError>) { let &Expr::Operator(operator) = &op.expr else { *op = Expression::garbage(working_set, op.span); return ( Type::Any, Some(ParseError::IncompleteMathExpression(op.span)), ); }; match operator { Operator::Math(Math::Add) => match (&lhs.ty, &rhs.ty) { (Type::Int, Type::Int) => (Type::Int, None), (Type::Float, Type::Int) => (Type::Float, None), (Type::Int, Type::Float) => (Type::Float, None), (Type::Float, Type::Float) => (Type::Float, None), (Type::Number, Type::Number) => (Type::Number, None), (Type::Number, Type::Int) => (Type::Number, None), (Type::Int, Type::Number) => (Type::Number, None), (Type::Number, Type::Float) => (Type::Number, None), (Type::Float, Type::Number) => (Type::Number, None), (Type::String, Type::String) => (Type::String, None), // TODO: should this include glob (Type::Date, Type::Duration) => (Type::Date, None), (Type::Duration, Type::Date) => (Type::Date, None), (Type::Duration, Type::Duration) => (Type::Duration, None), (Type::Filesize, Type::Filesize) => (Type::Filesize, None), (Type::Custom(a), Type::Custom(b)) if a == b => (Type::Custom(a.clone()), None), (Type::Custom(a), _) => (Type::Custom(a.clone()), None), (Type::Any, _) => (Type::Any, None), (_, Type::Any) => (Type::Any, None), _ => { *op = Expression::garbage(working_set, op.span); type_error(operator, op.span, lhs, rhs, |ty| { matches!( ty, Type::Int | Type::Float | Type::Number | Type::String | Type::Date | Type::Duration | Type::Filesize, ) }) } }, Operator::Math(Math::Subtract) => match (&lhs.ty, &rhs.ty) { (Type::Int, Type::Int) => (Type::Int, None), (Type::Float, Type::Int) => (Type::Float, None), (Type::Int, Type::Float) => (Type::Float, None), (Type::Float, Type::Float) => (Type::Float, None), (Type::Number, Type::Number) => (Type::Number, None), (Type::Number, Type::Int) => (Type::Number, None), (Type::Int, Type::Number) => (Type::Number, None), (Type::Number, Type::Float) => (Type::Number, None), (Type::Float, Type::Number) => (Type::Number, None), (Type::Date, Type::Date) => (Type::Duration, None), (Type::Date, Type::Duration) => (Type::Date, None), (Type::Duration, Type::Duration) => (Type::Duration, None), (Type::Filesize, Type::Filesize) => (Type::Filesize, None), (Type::Custom(a), Type::Custom(b)) if a == b => (Type::Custom(a.clone()), None), (Type::Custom(a), _) => (Type::Custom(a.clone()), None), (Type::Any, _) => (Type::Any, None), (_, Type::Any) => (Type::Any, None), _ => { *op = Expression::garbage(working_set, op.span); type_error(operator, op.span, lhs, rhs, |ty| { matches!( ty, Type::Int | Type::Float | Type::Number | Type::Date | Type::Duration | Type::Filesize ) }) } }, Operator::Math(Math::Multiply) => match (&lhs.ty, &rhs.ty) { (Type::Int, Type::Int) => (Type::Int, None), (Type::Float, Type::Int) => (Type::Float, None), (Type::Int, Type::Float) => (Type::Float, None), (Type::Float, Type::Float) => (Type::Float, None), (Type::Number, Type::Number) => (Type::Number, None), (Type::Number, Type::Int) => (Type::Number, None), (Type::Int, Type::Number) => (Type::Number, None), (Type::Number, Type::Float) => (Type::Number, None), (Type::Float, Type::Number) => (Type::Number, None), (Type::Filesize, Type::Int) => (Type::Filesize, None), (Type::Int, Type::Filesize) => (Type::Filesize, None), (Type::Filesize, Type::Float) => (Type::Filesize, None), (Type::Float, Type::Filesize) => (Type::Filesize, None), (Type::Duration, Type::Int) => (Type::Duration, None), (Type::Int, Type::Duration) => (Type::Duration, None), (Type::Duration, Type::Float) => (Type::Duration, None), (Type::Float, Type::Duration) => (Type::Duration, None), (Type::Custom(a), Type::Custom(b)) if a == b => (Type::Custom(a.clone()), None), (Type::Custom(a), _) => (Type::Custom(a.clone()), None), (Type::Any, _) => (Type::Any, None), (_, Type::Any) => (Type::Any, None), _ => { *op = Expression::garbage(working_set, op.span); type_error(operator, op.span, lhs, rhs, |ty| { matches!( ty, Type::Int | Type::Float | Type::Number | Type::Duration | Type::Filesize, ) }) } }, Operator::Math(Math::Divide) => match (&lhs.ty, &rhs.ty) { (Type::Int, Type::Int) => (Type::Float, None), (Type::Float, Type::Int) => (Type::Float, None), (Type::Int, Type::Float) => (Type::Float, None), (Type::Float, Type::Float) => (Type::Float, None), (Type::Number, Type::Number) => (Type::Float, None), (Type::Number, Type::Int) => (Type::Float, None), (Type::Int, Type::Number) => (Type::Float, None), (Type::Number, Type::Float) => (Type::Float, None), (Type::Float, Type::Number) => (Type::Float, None), (Type::Filesize, Type::Filesize) => (Type::Float, None), (Type::Filesize, Type::Int) => (Type::Filesize, None), (Type::Filesize, Type::Float) => (Type::Filesize, None), (Type::Duration, Type::Duration) => (Type::Float, None), (Type::Duration, Type::Int) => (Type::Duration, None), (Type::Duration, Type::Float) => (Type::Duration, None), (Type::Custom(a), Type::Custom(b)) if a == b => (Type::Custom(a.clone()), None), (Type::Custom(a), _) => (Type::Custom(a.clone()), None), (Type::Any, _) => (Type::Any, None), (_, Type::Any) => (Type::Any, None), _ => { *op = Expression::garbage(working_set, op.span); type_error(operator, op.span, lhs, rhs, |ty| { matches!( ty, Type::Int | Type::Float | Type::Number | Type::Filesize | Type::Duration ) }) } }, Operator::Math(Math::FloorDivide) => match (&lhs.ty, &rhs.ty) { (Type::Int, Type::Int) => (Type::Int, None), (Type::Float, Type::Int) => (Type::Float, None), (Type::Int, Type::Float) => (Type::Float, None), (Type::Float, Type::Float) => (Type::Float, None), (Type::Number, Type::Number) => (Type::Number, None), (Type::Number, Type::Int) => (Type::Number, None), (Type::Int, Type::Number) => (Type::Number, None), (Type::Number, Type::Float) => (Type::Number, None), (Type::Float, Type::Number) => (Type::Number, None), (Type::Filesize, Type::Filesize) => (Type::Int, None), (Type::Filesize, Type::Int) => (Type::Filesize, None), (Type::Filesize, Type::Float) => (Type::Filesize, None), (Type::Duration, Type::Duration) => (Type::Int, None), (Type::Duration, Type::Int) => (Type::Duration, None), (Type::Duration, Type::Float) => (Type::Duration, None), (Type::Custom(a), Type::Custom(b)) if a == b => (Type::Custom(a.clone()), None), (Type::Custom(a), _) => (Type::Custom(a.clone()), None), (Type::Any, _) => (Type::Any, None), (_, Type::Any) => (Type::Any, None), _ => { *op = Expression::garbage(working_set, op.span); type_error(operator, op.span, lhs, rhs, |ty| { matches!( ty, Type::Int | Type::Float | Type::Number | Type::Filesize | Type::Duration ) }) } }, Operator::Math(Math::Modulo) => match (&lhs.ty, &rhs.ty) { (Type::Int, Type::Int) => (Type::Int, None), (Type::Float, Type::Int) => (Type::Float, None), (Type::Int, Type::Float) => (Type::Float, None), (Type::Float, Type::Float) => (Type::Float, None), (Type::Number, Type::Number) => (Type::Number, None), (Type::Number, Type::Int) => (Type::Number, None), (Type::Int, Type::Number) => (Type::Number, None), (Type::Number, Type::Float) => (Type::Number, None), (Type::Float, Type::Number) => (Type::Number, None), (Type::Filesize, Type::Filesize) => (Type::Filesize, None), (Type::Filesize, Type::Int) => (Type::Filesize, None), (Type::Filesize, Type::Float) => (Type::Filesize, None), (Type::Duration, Type::Duration) => (Type::Duration, None), (Type::Duration, Type::Int) => (Type::Duration, None), (Type::Duration, Type::Float) => (Type::Duration, None), (Type::Custom(a), Type::Custom(b)) if a == b => (Type::Custom(a.clone()), None), (Type::Custom(a), _) => (Type::Custom(a.clone()), None), (Type::Any, _) => (Type::Any, None), (_, Type::Any) => (Type::Any, None), _ => { *op = Expression::garbage(working_set, op.span); type_error(operator, op.span, lhs, rhs, |ty| { matches!( ty, Type::Int | Type::Float | Type::Number | Type::Filesize | Type::Duration ) }) } }, Operator::Math(Math::Pow) => match (&lhs.ty, &rhs.ty) { (Type::Int, Type::Int) => (Type::Int, None), (Type::Float, Type::Int) => (Type::Float, None), (Type::Int, Type::Float) => (Type::Float, None), (Type::Float, Type::Float) => (Type::Float, None), (Type::Number, Type::Number) => (Type::Number, None), (Type::Number, Type::Int) => (Type::Number, None), (Type::Int, Type::Number) => (Type::Number, None), (Type::Number, Type::Float) => (Type::Number, None), (Type::Float, Type::Number) => (Type::Number, None), (Type::Custom(a), Type::Custom(b)) if a == b => (Type::Custom(a.clone()), None), (Type::Custom(a), _) => (Type::Custom(a.clone()), None), (Type::Any, _) => (Type::Any, None), (_, Type::Any) => (Type::Any, None), _ => { *op = Expression::garbage(working_set, op.span); type_error(operator, op.span, lhs, rhs, |ty| { matches!(ty, Type::Int | Type::Float | Type::Number) }) } }, Operator::Math(Math::Concatenate) => match (&lhs.ty, &rhs.ty) { (Type::List(a), Type::List(b)) => { if a == b { (Type::list(a.as_ref().clone()), None) } else { (Type::list(Type::Any), None) } } (Type::Table(a), Type::Table(_)) => (Type::Table(a.clone()), None), (Type::Table(table), Type::List(list)) => { if matches!(list.as_ref(), Type::Record(..)) { (Type::Table(table.clone()), None) } else { (Type::list(Type::Any), None) } } (Type::List(list), Type::Table(_)) => { if matches!(list.as_ref(), Type::Record(..)) { (Type::list(list.as_ref().clone()), None) } else { (Type::list(Type::Any), None) } } (Type::String, Type::String) => (Type::String, None), // TODO: should this include glob (Type::Binary, Type::Binary) => (Type::Binary, None), (Type::Custom(a), Type::Custom(b)) if a == b => (Type::Custom(a.clone()), None), (Type::Custom(a), _) => (Type::Custom(a.clone()), None), (Type::Any, _) | (_, Type::Any) => (Type::Any, None), _ => { *op = Expression::garbage(working_set, op.span); let is_supported = |ty: &Type| { matches!( ty, Type::List(_) | Type::Table(_) | Type::String | Type::Binary | Type::Any | Type::Custom(_) ) }; let help = if matches!(lhs.ty, Type::List(_) | Type::Table(_)) || matches!(rhs.ty, Type::List(_) | Type::Table(_)) { Some( "if you meant to append a value to a list or a record to a table, use the `append` command or wrap the value in a list. For example: `$list ++ $value` should be `$list ++ [$value]` or `$list | append $value`.", ) } else { None }; let err = match (is_supported(&lhs.ty), is_supported(&rhs.ty)) { (true, true) => ParseError::OperatorIncompatibleTypes { op: operator.as_str(), lhs: lhs.ty.clone(), rhs: rhs.ty.clone(), op_span: op.span, lhs_span: lhs.span, rhs_span: rhs.span, help, }, (true, false) => ParseError::OperatorUnsupportedType { op: operator.as_str(), unsupported: rhs.ty.clone(), op_span: op.span, unsupported_span: rhs.span, help, }, (false, _) => ParseError::OperatorUnsupportedType { op: operator.as_str(), unsupported: lhs.ty.clone(), op_span: op.span, unsupported_span: lhs.span, help, }, }; (Type::Any, Some(err)) } }, Operator::Boolean(_) => match (&lhs.ty, &rhs.ty) { (Type::Bool, Type::Bool) => (Type::Bool, None), (Type::Custom(a), Type::Custom(b)) if a == b => (Type::Custom(a.clone()), None), (Type::Custom(a), _) => (Type::Custom(a.clone()), None), (Type::Any, _) => (Type::Any, None), (_, Type::Any) => (Type::Any, None), _ => { *op = Expression::garbage(working_set, op.span); type_error(operator, op.span, lhs, rhs, |ty| matches!(ty, Type::Bool)) } }, Operator::Comparison(Comparison::LessThan) => match (&lhs.ty, &rhs.ty) { (Type::Int, Type::Int) => (Type::Bool, None), (Type::Float, Type::Int) => (Type::Bool, None), (Type::Int, Type::Float) => (Type::Bool, None), (Type::Float, Type::Float) => (Type::Bool, None), (Type::Number, Type::Number) => (Type::Bool, None), (Type::Number, Type::Int) => (Type::Bool, None), (Type::Int, Type::Number) => (Type::Bool, None), (Type::Number, Type::Float) => (Type::Bool, None), (Type::Float, Type::Number) => (Type::Bool, None), (Type::String, Type::String) => (Type::Bool, None), (Type::Duration, Type::Duration) => (Type::Bool, None), (Type::Date, Type::Date) => (Type::Bool, None), (Type::Filesize, Type::Filesize) => (Type::Bool, None), (Type::Bool, Type::Bool) => (Type::Bool, None), (Type::Custom(a), Type::Custom(b)) if a == b => (Type::Custom(a.clone()), None), (Type::Custom(a), _) => (Type::Custom(a.clone()), None), (Type::Nothing, _) => (Type::Nothing, None), // TODO: is this right (_, Type::Nothing) => (Type::Nothing, None), // TODO: is this right // TODO: should this include: // - binary // - glob // - list // - table // - record // - range (Type::Any, _) => (Type::Bool, None), (_, Type::Any) => (Type::Bool, None), _ => { *op = Expression::garbage(working_set, op.span); type_error(operator, op.span, lhs, rhs, |ty| { matches!( ty, Type::Int | Type::Float | Type::Number | Type::String | Type::Filesize | Type::Duration | Type::Date | Type::Bool | Type::Nothing ) }) } }, Operator::Comparison(Comparison::LessThanOrEqual) => match (&lhs.ty, &rhs.ty) { (Type::Int, Type::Int) => (Type::Bool, None), (Type::Float, Type::Int) => (Type::Bool, None), (Type::Int, Type::Float) => (Type::Bool, None), (Type::Float, Type::Float) => (Type::Bool, None), (Type::Number, Type::Number) => (Type::Bool, None), (Type::Number, Type::Int) => (Type::Bool, None), (Type::Int, Type::Number) => (Type::Bool, None), (Type::Number, Type::Float) => (Type::Bool, None), (Type::Float, Type::Number) => (Type::Bool, None), (Type::String, Type::String) => (Type::Bool, None), (Type::Duration, Type::Duration) => (Type::Bool, None), (Type::Date, Type::Date) => (Type::Bool, None), (Type::Filesize, Type::Filesize) => (Type::Bool, None), (Type::Bool, Type::Bool) => (Type::Bool, None), (Type::Custom(a), Type::Custom(b)) if a == b => (Type::Custom(a.clone()), None), (Type::Custom(a), _) => (Type::Custom(a.clone()), None), (Type::Nothing, _) => (Type::Nothing, None), // TODO: is this right (_, Type::Nothing) => (Type::Nothing, None), // TODO: is this right // TODO: should this include: // - binary // - glob // - list // - table // - record // - range (Type::Any, _) => (Type::Bool, None), (_, Type::Any) => (Type::Bool, None), _ => { *op = Expression::garbage(working_set, op.span); type_error(operator, op.span, lhs, rhs, |ty| { matches!( ty, Type::Int | Type::Float | Type::Number | Type::String | Type::Filesize | Type::Duration | Type::Date | Type::Bool | Type::Nothing ) }) } }, Operator::Comparison(Comparison::GreaterThan) => match (&lhs.ty, &rhs.ty) { (Type::Int, Type::Int) => (Type::Bool, None), (Type::Float, Type::Int) => (Type::Bool, None), (Type::Int, Type::Float) => (Type::Bool, None), (Type::Float, Type::Float) => (Type::Bool, None), (Type::Number, Type::Number) => (Type::Bool, None), (Type::Number, Type::Int) => (Type::Bool, None), (Type::Int, Type::Number) => (Type::Bool, None), (Type::Number, Type::Float) => (Type::Bool, None), (Type::Float, Type::Number) => (Type::Bool, None), (Type::String, Type::String) => (Type::Bool, None), (Type::Duration, Type::Duration) => (Type::Bool, None), (Type::Date, Type::Date) => (Type::Bool, None), (Type::Filesize, Type::Filesize) => (Type::Bool, None), (Type::Bool, Type::Bool) => (Type::Bool, None), (Type::Custom(a), Type::Custom(b)) if a == b => (Type::Custom(a.clone()), None), (Type::Custom(a), _) => (Type::Custom(a.clone()), None), (Type::Nothing, _) => (Type::Nothing, None), // TODO: is this right (_, Type::Nothing) => (Type::Nothing, None), // TODO: is this right // TODO: should this include: // - binary // - glob // - list // - table // - record // - range (Type::Any, _) => (Type::Bool, None), (_, Type::Any) => (Type::Bool, None), _ => { *op = Expression::garbage(working_set, op.span); type_error(operator, op.span, lhs, rhs, |ty| { matches!( ty, Type::Int | Type::Float | Type::Number | Type::String | Type::Filesize | Type::Duration | Type::Date | Type::Bool | Type::Nothing ) }) } }, Operator::Comparison(Comparison::GreaterThanOrEqual) => match (&lhs.ty, &rhs.ty) { (Type::Int, Type::Int) => (Type::Bool, None), (Type::Float, Type::Int) => (Type::Bool, None), (Type::Int, Type::Float) => (Type::Bool, None), (Type::Float, Type::Float) => (Type::Bool, None), (Type::Number, Type::Number) => (Type::Bool, None), (Type::Number, Type::Int) => (Type::Bool, None), (Type::Int, Type::Number) => (Type::Bool, None), (Type::Number, Type::Float) => (Type::Bool, None), (Type::Float, Type::Number) => (Type::Bool, None), (Type::String, Type::String) => (Type::Bool, None), (Type::Duration, Type::Duration) => (Type::Bool, None), (Type::Date, Type::Date) => (Type::Bool, None), (Type::Filesize, Type::Filesize) => (Type::Bool, None), (Type::Bool, Type::Bool) => (Type::Bool, None), (Type::Custom(a), Type::Custom(b)) if a == b => (Type::Custom(a.clone()), None), (Type::Custom(a), _) => (Type::Custom(a.clone()), None), (Type::Nothing, _) => (Type::Nothing, None), // TODO: is this right (_, Type::Nothing) => (Type::Nothing, None), // TODO: is this right // TODO: should this include: // - binary // - glob // - list // - table // - record // - range (Type::Any, _) => (Type::Bool, None), (_, Type::Any) => (Type::Bool, None), _ => { *op = Expression::garbage(working_set, op.span); type_error(operator, op.span, lhs, rhs, |ty| { matches!( ty, Type::Int | Type::Float | Type::Number | Type::String | Type::Filesize | Type::Duration | Type::Date | Type::Bool | Type::Nothing ) }) } }, Operator::Comparison(Comparison::Equal | Comparison::NotEqual) => { match (&lhs.ty, &rhs.ty) { (Type::Custom(a), Type::Custom(b)) if a == b => (Type::Custom(a.clone()), None), (Type::Custom(a), _) => (Type::Custom(a.clone()), None), _ => (Type::Bool, None), } } Operator::Comparison(Comparison::RegexMatch | Comparison::NotRegexMatch) => { match (&lhs.ty, &rhs.ty) { (Type::String | Type::Any, Type::String | Type::Any) => (Type::Bool, None), // TODO: should this include glob? (Type::Custom(a), Type::Custom(b)) if a == b => (Type::Custom(a.clone()), None), (Type::Custom(a), _) => (Type::Custom(a.clone()), None), _ => { *op = Expression::garbage(working_set, op.span); type_error(operator, op.span, lhs, rhs, |ty| matches!(ty, Type::String)) } } } Operator::Comparison( Comparison::StartsWith | Comparison::NotStartsWith | Comparison::EndsWith | Comparison::NotEndsWith, ) => { match (&lhs.ty, &rhs.ty) { (Type::String | Type::Any, Type::String | Type::Any) => (Type::Bool, None), // TODO: should this include glob? (Type::Custom(a), Type::Custom(b)) if a == b => (Type::Custom(a.clone()), None), (Type::Custom(a), _) => (Type::Custom(a.clone()), None), _ => { *op = Expression::garbage(working_set, op.span); type_error(operator, op.span, lhs, rhs, |ty| matches!(ty, Type::String)) } } } Operator::Comparison(Comparison::In | Comparison::NotIn) => match (&lhs.ty, &rhs.ty) { (t, Type::List(u)) if type_compatible(t, u) => (Type::Bool, None), (Type::Int | Type::Float | Type::Number, Type::Range) => (Type::Bool, None), (Type::String, Type::String) => (Type::Bool, None), (Type::String, Type::Record(_)) => (Type::Bool, None), (Type::Custom(a), Type::Custom(b)) if a == b => (Type::Custom(a.clone()), None), (Type::Custom(a), _) => (Type::Custom(a.clone()), None), (Type::Any, _) => (Type::Bool, None), (_, Type::Any) => (Type::Bool, None), _ => { let err = if matches!( &rhs.ty, Type::List(_) | Type::Range | Type::String | Type::Record(_) | Type::Custom(_) | Type::Any ) { ParseError::OperatorIncompatibleTypes { op: operator.as_str(), lhs: lhs.ty.clone(), rhs: rhs.ty.clone(), op_span: op.span, lhs_span: lhs.span, rhs_span: rhs.span, help: None, } } else { ParseError::OperatorUnsupportedType { op: operator.as_str(), unsupported: rhs.ty.clone(), op_span: op.span, unsupported_span: rhs.span, help: None, } }; *op = Expression::garbage(working_set, op.span); (Type::Any, Some(err)) } }, Operator::Comparison(Comparison::Has | Comparison::NotHas) => match (&lhs.ty, &rhs.ty) { (Type::List(u), t) if type_compatible(u, t) => (Type::Bool, None), (Type::Range, Type::Int | Type::Float | Type::Number) => (Type::Bool, None), (Type::String, Type::String) => (Type::Bool, None), (Type::Record(_), Type::String) => (Type::Bool, None), (Type::Custom(a), Type::Custom(b)) if a == b => (Type::Custom(a.clone()), None), (Type::Custom(a), _) => (Type::Custom(a.clone()), None),
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
true
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-parser/src/deparse.rs
crates/nu-parser/src/deparse.rs
use nu_utils::escape_quote_string; fn string_should_be_quoted(input: &str) -> bool { input.starts_with('$') || input.chars().any(|c| { c == ' ' || c == '(' || c == '\'' || c == '`' || c == '"' || c == '\\' || c == ';' || c == '|' }) } // Escape rules: // input argument is not a flag, does not start with $ and doesn't contain special characters, it is passed as it is (foo -> foo) // input argument is not a flag and either starts with $ or contains special characters, quotes are added, " and \ are escaped (two \words -> "two \\words") // input argument is a flag without =, it's passed as it is (--foo -> --foo) // input argument is a flag with =, the first two points apply to the value (--foo=bar -> --foo=bar; --foo=bar' -> --foo="bar'") // // special characters are white space, (, ', `, ",and \ pub fn escape_for_script_arg(input: &str) -> String { // handle for flag, maybe we need to escape the value. if input.starts_with("--") { if let Some((arg_name, arg_val)) = input.split_once('=') { // only want to escape arg_val. let arg_val = if string_should_be_quoted(arg_val) { escape_quote_string(arg_val) } else { arg_val.into() }; return format!("{arg_name}={arg_val}"); } else { return input.into(); } } if string_should_be_quoted(input) { escape_quote_string(input) } else { input.into() } } #[cfg(test)] mod test { use super::escape_for_script_arg; #[test] fn test_not_extra_quote() { // check for input arg like this: // nu b.nu word 8 assert_eq!(escape_for_script_arg("word"), "word".to_string()); assert_eq!(escape_for_script_arg("8"), "8".to_string()); } #[test] fn test_quote_special() { let cases = vec![ ("two words", r#""two words""#), ("$nake", r#""$nake""#), ("`123", r#""`123""#), ("this|cat", r#""this|cat""#), ("this;cat", r#""this;cat""#), ]; for (input, expected) in cases { assert_eq!(escape_for_script_arg(input).as_str(), expected); } } #[test] fn test_arg_with_flag() { // check for input arg like this: // nu b.nu --linux --version=v5.2 assert_eq!(escape_for_script_arg("--linux"), "--linux".to_string()); assert_eq!( escape_for_script_arg("--version=v5.2"), "--version=v5.2".to_string() ); // check for input arg like this: // nu b.nu linux --version v5.2 assert_eq!(escape_for_script_arg("--version"), "--version".to_string()); assert_eq!(escape_for_script_arg("v5.2"), "v5.2".to_string()); } #[test] fn test_flag_arg_with_values_contains_special() { // check for input arg like this: // nu b.nu test_ver --version='xx yy' --separator="`" assert_eq!( escape_for_script_arg("--version='xx yy'"), r#"--version="'xx yy'""#.to_string() ); assert_eq!( escape_for_script_arg("--separator=`"), r#"--separator="`""#.to_string() ); } #[test] fn test_escape() { // check for input arg like this: // nu b.nu \ --arg='"' assert_eq!(escape_for_script_arg(r"\"), r#""\\""#.to_string()); assert_eq!( escape_for_script_arg(r#"--arg=""#), r#"--arg="\"""#.to_string() ); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-parser/src/parse_patterns.rs
crates/nu-parser/src/parse_patterns.rs
#![allow(clippy::byte_char_slices)] use crate::{ lex, lite_parse, parser::{is_variable, parse_value}, }; use nu_protocol::{ ParseError, Span, SyntaxShape, Type, VarId, ast::{MatchPattern, Pattern}, engine::StateWorkingSet, }; pub fn garbage(span: Span) -> MatchPattern { MatchPattern { pattern: Pattern::Garbage, guard: None, span, } } pub fn parse_pattern(working_set: &mut StateWorkingSet, span: Span) -> MatchPattern { let bytes = working_set.get_span_contents(span); if bytes.starts_with(b"$") { // Variable pattern parse_variable_pattern(working_set, span) } else if bytes.starts_with(b"{") { // Record pattern parse_record_pattern(working_set, span) } else if bytes.starts_with(b"[") { // List pattern parse_list_pattern(working_set, span) } else if bytes == b"_" { MatchPattern { pattern: Pattern::IgnoreValue, guard: None, span, } } else { // Literal value let value = parse_value(working_set, span, &SyntaxShape::Any); MatchPattern { pattern: Pattern::Expression(Box::new(value)), guard: None, span, } } } fn parse_variable_pattern_helper(working_set: &mut StateWorkingSet, span: Span) -> Option<VarId> { let bytes = working_set.get_span_contents(span); if is_variable(bytes) { if let Some(var_id) = working_set.find_variable_in_current_frame(bytes) { Some(var_id) } else { let var_id = working_set.add_variable(bytes.to_vec(), span, Type::Any, false); Some(var_id) } } else { None } } pub fn parse_variable_pattern(working_set: &mut StateWorkingSet, span: Span) -> MatchPattern { if let Some(var_id) = parse_variable_pattern_helper(working_set, span) { MatchPattern { pattern: Pattern::Variable(var_id), guard: None, span, } } else { working_set.error(ParseError::Expected("valid variable name", span)); garbage(span) } } pub fn parse_list_pattern(working_set: &mut StateWorkingSet, span: Span) -> MatchPattern { let bytes = working_set.get_span_contents(span); let mut start = span.start; let mut end = span.end; if bytes.starts_with(b"[") { start += 1; } if bytes.ends_with(b"]") { end -= 1; } else { working_set.error(ParseError::Unclosed("]".into(), Span::new(end, end))); } let inner_span = Span::new(start, end); let source = working_set.get_span_contents(inner_span); let (output, err) = lex(source, inner_span.start, &[b'\n', b'\r', b','], &[], true); if let Some(err) = err { working_set.error(err); } let (output, err) = lite_parse(&output, working_set); if let Some(err) = err { working_set.error(err); } let mut args = vec![]; if !output.block.is_empty() { for command in &output.block[0].commands { let mut spans_idx = 0; while spans_idx < command.parts.len() { let contents = working_set.get_span_contents(command.parts[spans_idx]); if contents == b".." { args.push(MatchPattern { pattern: Pattern::IgnoreRest, guard: None, span: command.parts[spans_idx], }); break; } else if contents.starts_with(b"..$") { if let Some(var_id) = parse_variable_pattern_helper( working_set, Span::new( command.parts[spans_idx].start + 2, command.parts[spans_idx].end, ), ) { args.push(MatchPattern { pattern: Pattern::Rest(var_id), guard: None, span: command.parts[spans_idx], }); break; } else { args.push(garbage(command.parts[spans_idx])); working_set.error(ParseError::Expected( "valid variable name", command.parts[spans_idx], )); } } else { let arg = parse_pattern(working_set, command.parts[spans_idx]); args.push(arg); }; spans_idx += 1; } } } MatchPattern { pattern: Pattern::List(args), guard: None, span, } } pub fn parse_record_pattern(working_set: &mut StateWorkingSet, span: Span) -> MatchPattern { let mut bytes = working_set.get_span_contents(span); let mut start = span.start; let mut end = span.end; if bytes.starts_with(b"{") { start += 1; } else { working_set.error(ParseError::Expected("{", Span::new(start, start + 1))); bytes = working_set.get_span_contents(span); } if bytes.ends_with(b"}") { end -= 1; } else { working_set.error(ParseError::Unclosed("}".into(), Span::new(end, end))); } let inner_span = Span::new(start, end); let source = working_set.get_span_contents(inner_span); let (tokens, err) = lex(source, start, &[b'\n', b'\r', b','], &[b':'], true); if let Some(err) = err { working_set.error(err); } let mut output = vec![]; let mut idx = 0; while idx < tokens.len() { let bytes = working_set.get_span_contents(tokens[idx].span); let (field, pattern) = if !bytes.is_empty() && bytes[0] == b'$' { // If this is a variable, treat it as both the name of the field and the pattern let field = String::from_utf8_lossy(&bytes[1..]).to_string(); let pattern = parse_variable_pattern(working_set, tokens[idx].span); (field, pattern) } else { let field = String::from_utf8_lossy(bytes).to_string(); idx += 1; if idx == tokens.len() { working_set.error(ParseError::Expected("record", span)); return garbage(span); } let colon = working_set.get_span_contents(tokens[idx].span); idx += 1; if idx == tokens.len() || colon != b":" { //FIXME: need better error working_set.error(ParseError::Expected("record", span)); return garbage(span); } let pattern = parse_pattern(working_set, tokens[idx].span); (field, pattern) }; idx += 1; output.push((field, pattern)); } MatchPattern { pattern: Pattern::Record(output), guard: None, span, } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-parser/src/parse_shape_specs.rs
crates/nu-parser/src/parse_shape_specs.rs
#![allow(clippy::byte_char_slices)] use std::borrow::Cow; use crate::{TokenContents, lex::lex_signature, parser::parse_value}; use nu_protocol::{ Completion, IntoSpanned, ParseError, ShellError, Span, Spanned, SyntaxShape, Type, Value, engine::StateWorkingSet, eval_const::eval_constant, }; use nu_utils::NuCow; /// [`parse_shape_name`] then convert to Type pub fn parse_type(working_set: &mut StateWorkingSet, bytes: &[u8], span: Span) -> Type { parse_shape_name(working_set, bytes, span).to_type() } /// Parse the literals of [`Type`]-like [`SyntaxShape`]s including inner types. /// /// NOTE: Does not provide a mapping to every [`SyntaxShape`] pub fn parse_shape_name( working_set: &mut StateWorkingSet, bytes: &[u8], span: Span, ) -> SyntaxShape { match bytes { b"any" => SyntaxShape::Any, b"binary" => SyntaxShape::Binary, b"block" => { working_set.error(ParseError::LabeledErrorWithHelp { error: "Blocks are not support as first-class values".into(), label: "blocks are not supported as values".into(), help: "Use 'closure' instead of 'block'".into(), span, }); SyntaxShape::Any } b"bool" => SyntaxShape::Boolean, b"cell-path" => SyntaxShape::CellPath, b"closure" => SyntaxShape::Closure(None), //FIXME: Blocks should have known output types b"datetime" => SyntaxShape::DateTime, b"directory" => SyntaxShape::Directory, b"duration" => SyntaxShape::Duration, b"error" => SyntaxShape::Error, b"float" => SyntaxShape::Float, b"filesize" => SyntaxShape::Filesize, b"glob" => SyntaxShape::GlobPattern, b"int" => SyntaxShape::Int, b"nothing" => SyntaxShape::Nothing, b"number" => SyntaxShape::Number, b"path" => SyntaxShape::Filepath, b"range" => SyntaxShape::Range, b"string" => SyntaxShape::String, _ if bytes.starts_with(b"oneof") || bytes.starts_with(b"list") || bytes.starts_with(b"record") || bytes.starts_with(b"table") => { parse_generic_shape(working_set, bytes, span) } _ => { if bytes.contains(&b'@') { working_set.error(ParseError::LabeledError( "Unexpected custom completer in type spec".into(), "Type specifications do not support custom completers".into(), span, )); } //TODO: Handle error case for unknown shapes working_set.error(ParseError::UnknownType(span)); SyntaxShape::Any } } } /// Handles the specification of custom completions with `type@completer`. pub fn parse_completer( working_set: &mut StateWorkingSet, _bytes: &[u8], span: Span, ) -> Option<Completion> { let error_count = working_set.parse_errors.len(); let expr = parse_value( working_set, span, &SyntaxShape::OneOf(vec![ SyntaxShape::List(Box::new(SyntaxShape::String)), SyntaxShape::String, ]), ); if working_set.parse_errors.len() > error_count { return None; } let val = match eval_constant(working_set, &expr) { Ok(val) => val, Err(e) => { working_set.error(e.wrap(working_set, span)); return None; } }; let completion = match val { // Static list completions Value::List { vals, .. } => vals .into_iter() .map(|val| { let span = val.span(); match val { // TODO: currently `Completion::List` only supports simple string suggestions, // but it will likely support description and style properties as well. // // For that reason records with a "value" field are accepted. So one can use // choose to use "full"/record suggestions even if they get no benefit from // that *not*, and when support for the other properties land their completions // will improve without any extra intervention. Value::Record { val, .. } => val .get("value") .ok_or(ShellError::CantFindColumn { col_name: "value".into(), span: None, src_span: span, }) .and_then(Value::coerce_str) .map(Cow::into_owned), val => val.coerce_into_string(), } }) .collect::<Result<Vec<_>, ShellError>>() .map_err(|err| err.wrap(working_set, span)) .map(|vals| Completion::List(NuCow::Owned(vals))), // Command completions Value::String { val, .. } => working_set .find_decl(val.as_bytes()) .map(Completion::Command) .ok_or(ParseError::UnknownCommand(span)), val => Err(ParseError::OperatorUnsupportedType { op: "parameter completer", unsupported: val.get_type(), op_span: Span::new(span.start - 1, span.start), unsupported_span: span, help: Some( "\ the completer can only be a\n\ - string (name of a command)\n\ - list of items with simple string representations\ ", ), }), }; match completion { Ok(completion) => Some(completion), Err(err) => { working_set.error(err); None } } } fn parse_generic_shape( working_set: &mut StateWorkingSet<'_>, bytes: &[u8], span: Span, ) -> SyntaxShape { let (type_name, type_params) = split_generic_params(working_set, bytes, span); match type_name { b"oneof" => SyntaxShape::OneOf(match type_params { Some(params) => parse_type_params(working_set, params), None => vec![], }), b"list" => SyntaxShape::List(Box::new(match type_params { Some(params) => { let mut parsed_params = parse_type_params(working_set, params); if parsed_params.len() > 1 { working_set.error(ParseError::LabeledError( "expected a single type parameter".into(), "only one parameter allowed".into(), params.span, )); SyntaxShape::Any } else { parsed_params.pop().unwrap_or(SyntaxShape::Any) } } None => SyntaxShape::Any, })), b"record" => SyntaxShape::Record(match type_params { Some(params) => parse_named_type_params(working_set, params), None => vec![], }), b"table" => SyntaxShape::Table(match type_params { Some(params) => parse_named_type_params(working_set, params), None => vec![], }), _ => { working_set.error(ParseError::UnknownType(span)); SyntaxShape::Any } } } fn split_generic_params<'a>( working_set: &mut StateWorkingSet, bytes: &'a [u8], span: Span, ) -> (&'a [u8], Option<Spanned<&'a [u8]>>) { let n = bytes.iter().position(|&c| c == b'<'); let (open_delim_pos, close_delim) = match n.and_then(|n| Some((n, bytes.get(n)?))) { Some((n, b'<')) => (n, b'>'), _ => return (bytes, None), }; let type_name = &bytes[..(open_delim_pos)]; let params = &bytes[(open_delim_pos + 1)..]; let start = span.start + type_name.len() + 1; if params.ends_with(&[close_delim]) { let end = span.end - 1; ( type_name, Some((&params[..(params.len() - 1)]).into_spanned(Span::new(start, end))), ) } else if let Some(close_delim_pos) = params.iter().position(|it| it == &close_delim) { let span = Span::new(span.start + close_delim_pos, span.end); working_set.error(ParseError::LabeledError( "Extra characters in the parameter name".into(), "extra characters".into(), span, )); (bytes, None) } else { working_set.error(ParseError::Unclosed((close_delim as char).into(), span)); (bytes, None) } } fn parse_named_type_params( working_set: &mut StateWorkingSet, Spanned { item: source, span }: Spanned<&[u8]>, ) -> Vec<(String, SyntaxShape)> { let (tokens, err) = lex_signature(source, span.start, &[b'\n', b'\r'], &[b':', b','], true); if let Some(err) = err { working_set.error(err); return Vec::new(); } let mut sig = Vec::new(); let mut idx = 0; let key_error = |span| { ParseError::LabeledError( // format!("`{name}` type annotations key not string"), "annotation key not string".into(), "must be a string".into(), span, ) }; while idx < tokens.len() { let TokenContents::Item = tokens[idx].contents else { working_set.error(key_error(tokens[idx].span)); return Vec::new(); }; if working_set .get_span_contents(tokens[idx].span) .starts_with(b",") { idx += 1; continue; } let Some(key) = parse_value(working_set, tokens[idx].span, &SyntaxShape::String).as_string() else { working_set.error(key_error(tokens[idx].span)); return Vec::new(); }; // we want to allow such an annotation // `record<name>` where the user leaves out the type if idx + 1 == tokens.len() { sig.push((key, SyntaxShape::Any)); break; } else { idx += 1; } let maybe_colon = working_set.get_span_contents(tokens[idx].span); match maybe_colon { b":" => { if idx + 1 == tokens.len() { working_set.error(ParseError::Expected("type after colon", tokens[idx].span)); break; } else { idx += 1; } } // a key provided without a type b"," => { idx += 1; sig.push((key, SyntaxShape::Any)); continue; } // a key provided without a type _ => { sig.push((key, SyntaxShape::Any)); continue; } } let shape_bytes = working_set.get_span_contents(tokens[idx].span).to_vec(); let shape = parse_shape_name(working_set, &shape_bytes, tokens[idx].span); sig.push((key, shape)); idx += 1; } sig } fn parse_type_params( working_set: &mut StateWorkingSet, Spanned { item: source, span }: Spanned<&[u8]>, ) -> Vec<SyntaxShape> { let (tokens, err) = lex_signature(source, span.start, &[b'\n', b'\r'], &[b':', b','], true); if let Some(err) = err { working_set.error(err); return Vec::new(); } let mut sig = vec![]; let mut idx = 0; while idx < tokens.len() { if working_set .get_span_contents(tokens[idx].span) .starts_with(b",") { idx += 1; continue; } let shape_bytes = working_set.get_span_contents(tokens[idx].span).to_vec(); let shape = parse_shape_name(working_set, &shape_bytes, tokens[idx].span); sig.push(shape); idx += 1; } sig }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-parser/src/exportable.rs
crates/nu-parser/src/exportable.rs
use nu_protocol::{DeclId, ModuleId, VarId}; /// Symbol that can be exported with its associated name and ID pub enum Exportable { Decl { name: Vec<u8>, id: DeclId }, Module { name: Vec<u8>, id: ModuleId }, VarDecl { name: Vec<u8>, id: VarId }, }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-parser/src/lite_parser.rs
crates/nu-parser/src/lite_parser.rs
//! Lite parsing converts a flat stream of tokens from the lexer to a syntax element structure that //! can be parsed. use crate::{Token, TokenContents}; use itertools::{Either, Itertools}; use nu_protocol::{ParseError, Span, ast::RedirectionSource, engine::StateWorkingSet}; use std::mem; #[derive(Debug, Clone, Copy)] pub enum LiteRedirectionTarget { File { connector: Span, file: Span, append: bool, }, Pipe { connector: Span, }, } impl LiteRedirectionTarget { pub fn connector(&self) -> Span { match self { LiteRedirectionTarget::File { connector, .. } | LiteRedirectionTarget::Pipe { connector } => *connector, } } pub fn spans(&self) -> impl Iterator<Item = Span> { match *self { LiteRedirectionTarget::File { connector, file, .. } => Either::Left([connector, file].into_iter()), LiteRedirectionTarget::Pipe { connector } => Either::Right(std::iter::once(connector)), } } } #[derive(Debug, Clone)] pub enum LiteRedirection { Single { source: RedirectionSource, target: LiteRedirectionTarget, }, Separate { out: LiteRedirectionTarget, err: LiteRedirectionTarget, }, } impl LiteRedirection { pub fn spans(&self) -> impl Iterator<Item = Span> { match self { LiteRedirection::Single { target, .. } => Either::Left(target.spans()), LiteRedirection::Separate { out, err } => { Either::Right(out.spans().chain(err.spans()).sorted()) } } } } #[derive(Debug, Clone, Default)] pub struct LiteCommand { pub pipe: Option<Span>, pub comments: Vec<Span>, pub parts: Vec<Span>, pub redirection: Option<LiteRedirection>, /// one past the end indices of attributes pub attribute_idx: Vec<usize>, } impl LiteCommand { fn push(&mut self, span: Span) { self.parts.push(span); } fn check_accepts_redirection(&self, span: Span) -> Option<ParseError> { self.parts .is_empty() .then_some(ParseError::UnexpectedRedirection { span }) } fn try_add_redirection( &mut self, source: RedirectionSource, target: LiteRedirectionTarget, ) -> Result<(), ParseError> { let redirection = match (self.redirection.take(), source) { (None, _) if self.parts.is_empty() => Err(ParseError::UnexpectedRedirection { span: target.connector(), }), (None, source) => Ok(LiteRedirection::Single { source, target }), ( Some(LiteRedirection::Single { source: RedirectionSource::Stdout, target: out, }), RedirectionSource::Stderr, ) => Ok(LiteRedirection::Separate { out, err: target }), ( Some(LiteRedirection::Single { source: RedirectionSource::Stderr, target: err, }), RedirectionSource::Stdout, ) => Ok(LiteRedirection::Separate { out: target, err }), ( Some(LiteRedirection::Single { source, target: first, }), _, ) => Err(ParseError::MultipleRedirections( source, first.connector(), target.connector(), )), ( Some(LiteRedirection::Separate { out, .. }), RedirectionSource::Stdout | RedirectionSource::StdoutAndStderr, ) => Err(ParseError::MultipleRedirections( RedirectionSource::Stdout, out.connector(), target.connector(), )), (Some(LiteRedirection::Separate { err, .. }), RedirectionSource::Stderr) => { Err(ParseError::MultipleRedirections( RedirectionSource::Stderr, err.connector(), target.connector(), )) } }?; self.redirection = Some(redirection); Ok(()) } pub fn parts_including_redirection(&self) -> impl Iterator<Item = Span> + '_ { self.parts .iter() .copied() .chain( self.redirection .iter() .flat_map(|redirection| redirection.spans()), ) .sorted_unstable_by_key(|a| (a.start, a.end)) } pub fn command_parts(&self) -> &[Span] { let command_start = self.attribute_idx.last().copied().unwrap_or(0); &self.parts[command_start..] } pub fn has_attributes(&self) -> bool { !self.attribute_idx.is_empty() } pub fn attribute_commands(&'_ self) -> impl Iterator<Item = LiteCommand> + '_ { std::iter::once(0) .chain(self.attribute_idx.iter().copied()) .tuple_windows() .map(|(s, e)| LiteCommand { parts: self.parts[s..e].to_owned(), ..Default::default() }) } } #[derive(Debug, Clone, Default)] pub struct LitePipeline { pub commands: Vec<LiteCommand>, } impl LitePipeline { fn push(&mut self, element: &mut LiteCommand) { if !element.parts.is_empty() || element.redirection.is_some() { self.commands.push(mem::take(element)); } } } #[derive(Debug, Clone, Default)] pub struct LiteBlock { pub block: Vec<LitePipeline>, } impl LiteBlock { fn push(&mut self, pipeline: &mut LitePipeline) { if !pipeline.commands.is_empty() { self.block.push(mem::take(pipeline)); } } } fn last_non_comment_token(tokens: &[Token], cur_idx: usize) -> Option<TokenContents> { let mut expect = TokenContents::Comment; for token in tokens.iter().take(cur_idx).rev() { // skip ([Comment]+ [Eol]) pair match (token.contents, expect) { (TokenContents::Comment, TokenContents::Comment) | (TokenContents::Comment, TokenContents::Eol) => expect = TokenContents::Eol, (TokenContents::Eol, TokenContents::Eol) => expect = TokenContents::Comment, (token, _) => return Some(token), } } None } #[derive(PartialEq, Eq)] enum Mode { Assignment, Attribute, Normal, } pub fn lite_parse( tokens: &[Token], working_set: &StateWorkingSet, ) -> (LiteBlock, Option<ParseError>) { if tokens.is_empty() { return (LiteBlock::default(), None); } let mut block = LiteBlock::default(); let mut pipeline = LitePipeline::default(); let mut command = LiteCommand::default(); let mut last_token = TokenContents::Eol; let mut file_redirection = None; let mut curr_comment: Option<Vec<Span>> = None; let mut mode = Mode::Normal; let mut error = None; for (idx, token) in tokens.iter().enumerate() { match mode { Mode::Attribute => { match &token.contents { // Consume until semicolon or terminating EOL. Attributes can't contain pipelines or redirections. TokenContents::Eol | TokenContents::Semicolon => { command.attribute_idx.push(command.parts.len()); mode = Mode::Normal; if let TokenContents::Eol | TokenContents::Semicolon = last_token { // Clear out the comment as we're entering a new comment curr_comment = None; pipeline.push(&mut command); block.push(&mut pipeline); } } TokenContents::Comment => { command.comments.push(token.span); curr_comment = None; } _ => command.push(token.span), } } Mode::Assignment => { match &token.contents { // Consume until semicolon or terminating EOL. Assignments absorb pipelines and // redirections. TokenContents::Eol => { // Handle `[Command] [Pipe] ([Comment] | [Eol])+ [Command]` // // `[Eol]` branch checks if previous token is `[Pipe]` to construct pipeline // and so `[Comment] | [Eol]` should be ignore to make it work let actual_token = last_non_comment_token(tokens, idx); if actual_token != Some(TokenContents::Pipe) { mode = Mode::Normal; pipeline.push(&mut command); block.push(&mut pipeline); } if last_token == TokenContents::Eol { // Clear out the comment as we're entering a new comment curr_comment = None; } } TokenContents::Semicolon => { mode = Mode::Normal; pipeline.push(&mut command); block.push(&mut pipeline); } TokenContents::Comment => { command.comments.push(token.span); curr_comment = None; } _ => command.push(token.span), } } Mode::Normal => { if let Some((source, append, span)) = file_redirection.take() { match &token.contents { TokenContents::PipePipe => { error = error.or(Some(ParseError::ShellOrOr(token.span))); command.push(span); command.push(token.span); } TokenContents::Item => { let target = LiteRedirectionTarget::File { connector: span, file: token.span, append, }; if let Err(err) = command.try_add_redirection(source, target) { error = error.or(Some(err)); command.push(span); command.push(token.span) } } TokenContents::AssignmentOperator => { error = error .or(Some(ParseError::Expected("redirection target", token.span))); command.push(span); command.push(token.span); } TokenContents::OutGreaterThan | TokenContents::OutGreaterGreaterThan | TokenContents::ErrGreaterThan | TokenContents::ErrGreaterGreaterThan | TokenContents::OutErrGreaterThan | TokenContents::OutErrGreaterGreaterThan => { error = error .or(Some(ParseError::Expected("redirection target", token.span))); command.push(span); command.push(token.span); } TokenContents::Pipe | TokenContents::ErrGreaterPipe | TokenContents::OutErrGreaterPipe => { error = error .or(Some(ParseError::Expected("redirection target", token.span))); command.push(span); pipeline.push(&mut command); command.pipe = Some(token.span); } TokenContents::Eol => { error = error .or(Some(ParseError::Expected("redirection target", token.span))); command.push(span); pipeline.push(&mut command); } TokenContents::Semicolon => { error = error .or(Some(ParseError::Expected("redirection target", token.span))); command.push(span); pipeline.push(&mut command); block.push(&mut pipeline); } TokenContents::Comment => { error = error.or(Some(ParseError::Expected("redirection target", span))); command.push(span); command.comments.push(token.span); curr_comment = None; } } } else { match &token.contents { TokenContents::PipePipe => { error = error.or(Some(ParseError::ShellOrOr(token.span))); command.push(token.span); } TokenContents::Item => { // FIXME: This is commented out to preserve old parser behavior, // but we should probably error here. // // if element.redirection.is_some() { // error = error.or(Some(ParseError::LabeledError( // "Unexpected positional".into(), // "cannot add positional arguments after output redirection".into(), // token.span, // ))); // } // // For example, this is currently allowed: ^echo thing o> out.txt extra_arg if working_set.get_span_contents(token.span).starts_with(b"@") { if let TokenContents::Eol | TokenContents::Semicolon = last_token { mode = Mode::Attribute; } command.push(token.span); } else { // If we have a comment, go ahead and attach it if let Some(curr_comment) = curr_comment.take() { command.comments = curr_comment; } command.push(token.span); } } TokenContents::AssignmentOperator => { // When in assignment mode, we'll just consume pipes or redirections as part of // the command. mode = Mode::Assignment; if let Some(curr_comment) = curr_comment.take() { command.comments = curr_comment; } command.push(token.span); } TokenContents::OutGreaterThan => { error = error.or(command.check_accepts_redirection(token.span)); file_redirection = Some((RedirectionSource::Stdout, false, token.span)); } TokenContents::OutGreaterGreaterThan => { error = error.or(command.check_accepts_redirection(token.span)); file_redirection = Some((RedirectionSource::Stdout, true, token.span)); } TokenContents::ErrGreaterThan => { error = error.or(command.check_accepts_redirection(token.span)); file_redirection = Some((RedirectionSource::Stderr, false, token.span)); } TokenContents::ErrGreaterGreaterThan => { error = error.or(command.check_accepts_redirection(token.span)); file_redirection = Some((RedirectionSource::Stderr, true, token.span)); } TokenContents::OutErrGreaterThan => { error = error.or(command.check_accepts_redirection(token.span)); file_redirection = Some((RedirectionSource::StdoutAndStderr, false, token.span)); } TokenContents::OutErrGreaterGreaterThan => { error = error.or(command.check_accepts_redirection(token.span)); file_redirection = Some((RedirectionSource::StdoutAndStderr, true, token.span)); } TokenContents::ErrGreaterPipe => { let target = LiteRedirectionTarget::Pipe { connector: token.span, }; if let Err(err) = command.try_add_redirection(RedirectionSource::Stderr, target) { error = error.or(Some(err)); } pipeline.push(&mut command); command.pipe = Some(token.span); } TokenContents::OutErrGreaterPipe => { let target = LiteRedirectionTarget::Pipe { connector: token.span, }; if let Err(err) = command .try_add_redirection(RedirectionSource::StdoutAndStderr, target) { error = error.or(Some(err)); } pipeline.push(&mut command); command.pipe = Some(token.span); } TokenContents::Pipe => { pipeline.push(&mut command); command.pipe = Some(token.span); } TokenContents::Eol => { // Handle `[Command] [Pipe] ([Comment] | [Eol])+ [Command]` // // `[Eol]` branch checks if previous token is `[Pipe]` to construct pipeline // and so `[Comment] | [Eol]` should be ignore to make it work let actual_token = last_non_comment_token(tokens, idx); if actual_token != Some(TokenContents::Pipe) { pipeline.push(&mut command); block.push(&mut pipeline); } if last_token == TokenContents::Eol { // Clear out the comment as we're entering a new comment curr_comment = None; } } TokenContents::Semicolon => { pipeline.push(&mut command); block.push(&mut pipeline); } TokenContents::Comment => { // Comment is beside something if last_token != TokenContents::Eol { command.comments.push(token.span); curr_comment = None; } else { // Comment precedes something if let Some(curr_comment) = &mut curr_comment { curr_comment.push(token.span); } else { curr_comment = Some(vec![token.span]); } } } } } } } last_token = token.contents; } if let Some((_, _, span)) = file_redirection { command.push(span); error = error.or(Some(ParseError::Expected("redirection target", span))); } if let Mode::Attribute = mode { command.attribute_idx.push(command.parts.len()); } pipeline.push(&mut command); block.push(&mut pipeline); if last_non_comment_token(tokens, tokens.len()) == Some(TokenContents::Pipe) { ( block, Some(ParseError::UnexpectedEof( "pipeline missing end".into(), tokens[tokens.len() - 1].span, )), ) } else { (block, error) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-parser/src/known_external.rs
crates/nu-parser/src/known_external.rs
use nu_engine::command_prelude::*; use nu_protocol::{ CustomExample, ast::{self, Expr, Expression}, engine::{self, CallImpl, CommandType, UNKNOWN_SPAN_ID}, ir::{self, DataSlice}, }; #[derive(Clone)] pub struct KnownExternal { pub signature: Box<Signature>, pub attributes: Vec<(String, Value)>, pub examples: Vec<CustomExample>, } impl Command for KnownExternal { fn name(&self) -> &str { &self.signature.name } fn signature(&self) -> Signature { *self.signature.clone() } fn description(&self) -> &str { &self.signature.description } fn extra_description(&self) -> &str { &self.signature.extra_description } fn search_terms(&self) -> Vec<&str> { self.signature .search_terms .iter() .map(String::as_str) .collect() } fn command_type(&self) -> CommandType { CommandType::External } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head_span = call.head; let decl_id = engine_state .find_decl("run-external".as_bytes(), &[]) .ok_or(ShellError::ExternalNotSupported { span: head_span })?; let command = engine_state.get_decl(decl_id); let extern_name = if let Some(name_bytes) = engine_state.find_decl_name(call.decl_id, &[]) { String::from_utf8_lossy(name_bytes) } else { return Err(ShellError::NushellFailedSpanned { msg: "known external name not found".to_string(), label: "could not find name for this command".to_string(), span: call.head, }); }; let extern_name: Vec<_> = extern_name.split(' ').collect(); match &call.inner { CallImpl::AstRef(call) => { let extern_call = ast_call_to_extern_call(engine_state, call, &extern_name)?; command.run(engine_state, stack, &(&extern_call).into(), input) } CallImpl::AstBox(call) => { let extern_call = ast_call_to_extern_call(engine_state, call, &extern_name)?; command.run(engine_state, stack, &(&extern_call).into(), input) } CallImpl::IrRef(call) => { let extern_call = ir_call_to_extern_call(stack, call, &extern_name)?; command.run(engine_state, stack, &(&extern_call).into(), input) } CallImpl::IrBox(call) => { let extern_call = ir_call_to_extern_call(stack, call, &extern_name)?; command.run(engine_state, stack, &(&extern_call).into(), input) } } } fn attributes(&self) -> Vec<(String, Value)> { self.attributes.clone() } fn examples(&self) -> Vec<Example<'_>> { self.examples .iter() .map(CustomExample::to_example) .collect() } } /// Transform the args from an `ast::Call` onto a `run-external` call fn ast_call_to_extern_call( engine_state: &EngineState, call: &ast::Call, extern_name: &[&str], ) -> Result<ast::Call, ShellError> { let head_span = call.head; let mut extern_call = ast::Call::new(head_span); let call_head_id = engine_state .find_span_id(call.head) .unwrap_or(UNKNOWN_SPAN_ID); let arg_extern_name = Expression::new_existing( Expr::String(extern_name[0].to_string()), call.head, call_head_id, Type::String, ); extern_call.add_positional(arg_extern_name); for subcommand in extern_name.iter().skip(1) { extern_call.add_positional(Expression::new_existing( Expr::String(subcommand.to_string()), call.head, call_head_id, Type::String, )); } for arg in &call.arguments { match arg { ast::Argument::Positional(positional) => extern_call.add_positional(positional.clone()), ast::Argument::Named(named) => { let named_span_id = engine_state .find_span_id(named.0.span) .unwrap_or(UNKNOWN_SPAN_ID); if let Some(short) = &named.1 { extern_call.add_positional(Expression::new_existing( Expr::String(format!("-{}", short.item)), named.0.span, named_span_id, Type::String, )); } else { extern_call.add_positional(Expression::new_existing( Expr::String(format!("--{}", named.0.item)), named.0.span, named_span_id, Type::String, )); } if let Some(arg) = &named.2 { extern_call.add_positional(arg.clone()); } } ast::Argument::Unknown(unknown) => extern_call.add_unknown(unknown.clone()), ast::Argument::Spread(args) => extern_call.add_spread(args.clone()), } } Ok(extern_call) } /// Transform the args from an `ir::Call` onto a `run-external` call fn ir_call_to_extern_call( stack: &mut Stack, call: &ir::Call, extern_name: &[&str], ) -> Result<ir::Call, ShellError> { let mut extern_call = ir::Call::build(call.decl_id, call.head); // Add the command and subcommands for name in extern_name { extern_call.add_positional(stack, call.head, Value::string(*name, call.head)); } // Add the arguments, reformatting named arguments into string positionals for index in 0..call.args_len { match &call.arguments(stack)[index] { engine::Argument::Flag { data, name, short, span, } => { let name_arg = engine::Argument::Positional { span: *span, val: Value::string(known_external_option_name(data, *name, *short), *span), ast: None, }; extern_call.add_argument(stack, name_arg); } engine::Argument::Named { data, name, short, span, val, .. } => { let name_arg = engine::Argument::Positional { span: *span, val: Value::string(known_external_option_name(data, *name, *short), *span), ast: None, }; let val_arg = engine::Argument::Positional { span: *span, val: val.clone(), ast: None, }; extern_call.add_argument(stack, name_arg); extern_call.add_argument(stack, val_arg); } a @ (engine::Argument::Positional { .. } | engine::Argument::Spread { .. } | engine::Argument::ParserInfo { .. }) => { let argument = a.clone(); extern_call.add_argument(stack, argument); } } } Ok(extern_call.finish()) } fn known_external_option_name(data: &[u8], name: DataSlice, short: DataSlice) -> String { if !data[name].is_empty() { format!( "--{}", std::str::from_utf8(&data[name]).expect("invalid utf-8 in flag name") ) } else { format!( "-{}", std::str::from_utf8(&data[short]).expect("invalid utf-8 in flag short name") ) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-parser/src/lex.rs
crates/nu-parser/src/lex.rs
use nu_protocol::{ParseError, Span}; #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum TokenContents { Item, Comment, Pipe, PipePipe, AssignmentOperator, ErrGreaterPipe, OutErrGreaterPipe, Semicolon, OutGreaterThan, OutGreaterGreaterThan, ErrGreaterThan, ErrGreaterGreaterThan, OutErrGreaterThan, OutErrGreaterGreaterThan, Eol, } #[derive(Debug, PartialEq, Eq)] pub struct Token { pub contents: TokenContents, pub span: Span, } impl Token { pub fn new(contents: TokenContents, span: Span) -> Token { Token { contents, span } } } #[derive(Clone, Copy, Debug)] pub enum BlockKind { Paren, CurlyBracket, SquareBracket, AngleBracket, } impl BlockKind { fn closing(self) -> u8 { match self { BlockKind::Paren => b')', BlockKind::SquareBracket => b']', BlockKind::CurlyBracket => b'}', BlockKind::AngleBracket => b'>', } } } // A baseline token is terminated if it's not nested inside of a paired // delimiter and the next character is one of: `|`, `;` or any // whitespace. fn is_item_terminator( block_level: &[BlockKind], c: u8, additional_whitespace: &[u8], special_tokens: &[u8], ) -> bool { block_level.is_empty() && (c == b' ' || c == b'\t' || c == b'\n' || c == b'\r' || c == b'|' || c == b';' || additional_whitespace.contains(&c) || special_tokens.contains(&c)) } /// Assignment operators have special handling distinct from math expressions, as they cause the /// rest of the pipeline to be consumed. pub fn is_assignment_operator(bytes: &[u8]) -> bool { matches!(bytes, b"=" | b"+=" | b"++=" | b"-=" | b"*=" | b"/=") } // A special token is one that is a byte that stands alone as its own token. For example // when parsing a signature you may want to have `:` be able to separate tokens and also // to be handled as its own token to notify you you're about to parse a type in the example // `foo:bar` fn is_special_item(block_level: &[BlockKind], c: u8, special_tokens: &[u8]) -> bool { block_level.is_empty() && special_tokens.contains(&c) } pub fn lex_item( input: &[u8], curr_offset: &mut usize, span_offset: usize, additional_whitespace: &[u8], special_tokens: &[u8], in_signature: bool, ) -> (Token, Option<ParseError>) { // This variable tracks the starting character of a string literal, so that // we remain inside the string literal lexer mode until we encounter the // closing quote. let mut quote_start: Option<u8> = None; let mut in_comment = false; let token_start = *curr_offset; // This Vec tracks paired delimiters let mut block_level: Vec<BlockKind> = vec![]; // The process of slurping up a baseline token repeats: // // - String literal, which begins with `'` or `"`, and continues until // the same character is encountered again. // - Delimiter pair, which begins with `[`, `(`, or `{`, and continues until // the matching closing delimiter is found, skipping comments and string // literals. // - When not nested inside of a delimiter pair, when a terminating // character (whitespace, `|`, `;` or `#`) is encountered, the baseline // token is done. // - Otherwise, accumulate the character into the current baseline token. let mut previous_char = None; while let Some(c) = input.get(*curr_offset) { let c = *c; if let Some(start) = quote_start { // Check if we're in an escape sequence if c == b'\\' && start == b'"' { // Go ahead and consume the escape character if possible if input.get(*curr_offset + 1).is_some() { // Successfully escaped the character *curr_offset += 2; continue; } else { let span = Span::new(span_offset + token_start, span_offset + *curr_offset); return ( Token { contents: TokenContents::Item, span, }, Some(ParseError::UnexpectedEof( (start as char).to_string(), Span::new(span.end - 1, span.end), )), ); } } // If we encountered the closing quote character for the current // string, we're done with the current string. if c == start { // Also need to check to make sure we aren't escaped quote_start = None; } } else if c == b'#' && !in_comment { // To start a comment, It either need to be the first character of the token or prefixed with whitespace. in_comment = previous_char .map(char::from) .map(char::is_whitespace) .unwrap_or(true); } else if c == b'\n' || c == b'\r' { in_comment = false; if is_item_terminator(&block_level, c, additional_whitespace, special_tokens) { break; } } else if in_comment { if is_item_terminator(&block_level, c, additional_whitespace, special_tokens) { break; } } else if is_special_item(&block_level, c, special_tokens) && token_start == *curr_offset { *curr_offset += 1; break; } else if c == b'\'' || c == b'"' || c == b'`' { // We encountered the opening quote of a string literal. quote_start = Some(c); } else if c == b'[' { // We encountered an opening `[` delimiter. block_level.push(BlockKind::SquareBracket); } else if c == b'<' && in_signature { block_level.push(BlockKind::AngleBracket); } else if c == b'>' && in_signature { if let Some(BlockKind::AngleBracket) = block_level.last() { let _ = block_level.pop(); } } else if c == b']' { // We encountered a closing `]` delimiter. Pop off the opening `[` // delimiter. if let Some(BlockKind::SquareBracket) = block_level.last() { let _ = block_level.pop(); } } else if c == b'{' { // We encountered an opening `{` delimiter. block_level.push(BlockKind::CurlyBracket); } else if c == b'}' { // We encountered a closing `}` delimiter. Pop off the opening `{`. if let Some(BlockKind::CurlyBracket) = block_level.last() { let _ = block_level.pop(); } else { // We encountered a closing `}` delimiter, but the last opening // delimiter was not a `{`. This is an error. *curr_offset += 1; let span = Span::new(span_offset + token_start, span_offset + *curr_offset); return ( Token { contents: TokenContents::Item, span, }, Some(ParseError::Unbalanced( "{".to_string(), "}".to_string(), Span::new(span.end - 1, span.end), )), ); } } else if c == b'(' { // We encountered an opening `(` delimiter. block_level.push(BlockKind::Paren); } else if c == b')' { // We encountered a closing `)` delimiter. Pop off the opening `(`. if let Some(BlockKind::Paren) = block_level.last() { let _ = block_level.pop(); } else { // We encountered a closing `)` delimiter, but the last opening // delimiter was not a `(`. This is an error. *curr_offset += 1; let span = Span::new(span_offset + token_start, span_offset + *curr_offset); return ( Token { contents: TokenContents::Item, span, }, Some(ParseError::Unbalanced( "(".to_string(), ")".to_string(), Span::new(span.end - 1, span.end), )), ); } } else if c == b'r' && input.get(*curr_offset + 1) == Some(b'#').as_ref() { // already checked `r#` pattern, so it's a raw string. let lex_result = lex_raw_string(input, curr_offset, span_offset); let span = Span::new(span_offset + token_start, span_offset + *curr_offset); if let Err(e) = lex_result { return ( Token { contents: TokenContents::Item, span, }, Some(e), ); } } else if c == b'|' && is_redirection(&input[token_start..*curr_offset]) { // matches err>| etc. *curr_offset += 1; break; } else if is_item_terminator(&block_level, c, additional_whitespace, special_tokens) { break; } *curr_offset += 1; previous_char = Some(c); } let span = Span::new(span_offset + token_start, span_offset + *curr_offset); if let Some(delim) = quote_start { // The non-lite parse trims quotes on both sides, so we add the expected quote so that // anyone wanting to consume this partial parse (e.g., completions) will be able to get // correct information from the non-lite parse. return ( Token { contents: TokenContents::Item, span, }, Some(ParseError::UnexpectedEof( (delim as char).to_string(), Span::new(span.end - 1, span.end), )), ); } // If there is still unclosed opening delimiters, remember they were missing if let Some(block) = block_level.last() { let delim = block.closing(); let cause = ParseError::UnexpectedEof( (delim as char).to_string(), Span::new(span.end - 1, span.end), ); return ( Token { contents: TokenContents::Item, span, }, Some(cause), ); } // If we didn't accumulate any characters, it's an unexpected error. if *curr_offset - token_start == 0 { return ( Token { contents: TokenContents::Item, span, }, Some(ParseError::UnexpectedEof("command".to_string(), span)), ); } let mut err = None; let output = match &input[(span.start - span_offset)..(span.end - span_offset)] { bytes if is_assignment_operator(bytes) => Token { contents: TokenContents::AssignmentOperator, span, }, b"out>" | b"o>" => Token { contents: TokenContents::OutGreaterThan, span, }, b"out>>" | b"o>>" => Token { contents: TokenContents::OutGreaterGreaterThan, span, }, b"out>|" | b"o>|" => { err = Some(ParseError::Expected( "`|`. Redirecting stdout to a pipe is the same as normal piping.", span, )); Token { contents: TokenContents::Item, span, } } b"err>" | b"e>" => Token { contents: TokenContents::ErrGreaterThan, span, }, b"err>>" | b"e>>" => Token { contents: TokenContents::ErrGreaterGreaterThan, span, }, b"err>|" | b"e>|" => Token { contents: TokenContents::ErrGreaterPipe, span, }, b"out+err>" | b"err+out>" | b"o+e>" | b"e+o>" => Token { contents: TokenContents::OutErrGreaterThan, span, }, b"out+err>>" | b"err+out>>" | b"o+e>>" | b"e+o>>" => Token { contents: TokenContents::OutErrGreaterGreaterThan, span, }, b"out+err>|" | b"err+out>|" | b"o+e>|" | b"e+o>|" => Token { contents: TokenContents::OutErrGreaterPipe, span, }, b"&&" => { err = Some(ParseError::ShellAndAnd(span)); Token { contents: TokenContents::Item, span, } } b"2>" => { err = Some(ParseError::ShellErrRedirect(span)); Token { contents: TokenContents::Item, span, } } b"2>&1" => { err = Some(ParseError::ShellOutErrRedirect(span)); Token { contents: TokenContents::Item, span, } } _ => Token { contents: TokenContents::Item, span, }, }; (output, err) } fn lex_raw_string( input: &[u8], curr_offset: &mut usize, span_offset: usize, ) -> Result<(), ParseError> { // A raw string literal looks like `echo r#'Look, I can use 'single quotes'!'#` // If the next character is `#` we're probably looking at a raw string literal // so we need to read all the text until we find a closing `#`. This raw string // can contain any character, including newlines and double quotes without needing // to escape them. // // A raw string can contain many `#` as prefix, // incase if there is a `'#` or `#'` in the string itself. // E.g: r##'I can use '#' in a raw string'## let mut prefix_sharp_cnt = 0; let start = *curr_offset; while let Some(b'#') = input.get(start + prefix_sharp_cnt + 1) { prefix_sharp_cnt += 1; } // curr_offset is the character `r`, we need to move forward and skip all `#` // characters. // // e.g: r###'<body> // ^ // ^ // curr_offset *curr_offset += prefix_sharp_cnt + 1; // the next one should be a single quote. if input.get(*curr_offset) != Some(&b'\'') { return Err(ParseError::Expected( "'", Span::new(span_offset + *curr_offset, span_offset + *curr_offset + 1), )); } *curr_offset += 1; let mut matches = false; while let Some(ch) = input.get(*curr_offset) { // check for postfix '### if *ch == b'#' { let start_ch = input[*curr_offset - prefix_sharp_cnt]; let postfix = &input[*curr_offset - prefix_sharp_cnt + 1..=*curr_offset]; if start_ch == b'\'' && postfix.iter().all(|x| *x == b'#') { matches = true; break; } } *curr_offset += 1 } if !matches { let mut expected = '\''.to_string(); expected.push_str(&"#".repeat(prefix_sharp_cnt)); return Err(ParseError::UnexpectedEof( expected, Span::new(span_offset + *curr_offset - 1, span_offset + *curr_offset), )); } Ok(()) } pub fn lex_signature( input: &[u8], span_offset: usize, additional_whitespace: &[u8], special_tokens: &[u8], skip_comment: bool, ) -> (Vec<Token>, Option<ParseError>) { let mut state = LexState { input, output: Vec::new(), error: None, span_offset, }; lex_internal( &mut state, additional_whitespace, special_tokens, skip_comment, true, None, ); (state.output, state.error) } #[derive(Debug)] pub struct LexState<'a> { pub input: &'a [u8], pub output: Vec<Token>, pub error: Option<ParseError>, pub span_offset: usize, } /// Lex until the output is `max_tokens` longer than before the call, or until the input is exhausted. /// The return value indicates how many tokens the call added to / removed from the output. /// /// The behaviour here is non-obvious when `additional_whitespace` doesn't include newline: /// If you pass a `state` where the last token in the output is an Eol, this might *remove* tokens. pub fn lex_n_tokens( state: &mut LexState, additional_whitespace: &[u8], special_tokens: &[u8], skip_comment: bool, max_tokens: usize, ) -> isize { let n_tokens = state.output.len(); lex_internal( state, additional_whitespace, special_tokens, skip_comment, false, Some(max_tokens), ); // If this lex_internal call reached the end of the input, there may now be fewer tokens // in the output than before. let tokens_n_diff = (state.output.len() as isize) - (n_tokens as isize); let next_offset = state.output.last().map(|token| token.span.end); if let Some(next_offset) = next_offset { state.input = &state.input[next_offset - state.span_offset..]; state.span_offset = next_offset; } tokens_n_diff } pub fn lex( input: &[u8], span_offset: usize, additional_whitespace: &[u8], special_tokens: &[u8], skip_comment: bool, ) -> (Vec<Token>, Option<ParseError>) { let mut state = LexState { input, output: Vec::new(), error: None, span_offset, }; lex_internal( &mut state, additional_whitespace, special_tokens, skip_comment, false, None, ); (state.output, state.error) } fn lex_internal( state: &mut LexState, additional_whitespace: &[u8], special_tokens: &[u8], skip_comment: bool, // within signatures we want to treat `<` and `>` specially in_signature: bool, max_tokens: Option<usize>, ) { let initial_output_len = state.output.len(); let mut curr_offset = 0; let mut is_complete = true; while let Some(c) = state.input.get(curr_offset) { if max_tokens .is_some_and(|max_tokens| state.output.len() >= initial_output_len + max_tokens) { break; } let c = *c; if c == b'|' { // If the next character is `|`, it's either `|` or `||`. let idx = curr_offset; let prev_idx = idx; curr_offset += 1; // If the next character is `|`, we're looking at a `||`. if let Some(c) = state.input.get(curr_offset) && *c == b'|' { let idx = curr_offset; curr_offset += 1; state.output.push(Token::new( TokenContents::PipePipe, Span::new(state.span_offset + prev_idx, state.span_offset + idx + 1), )); continue; } // Otherwise, it's just a regular `|` token. // Before we push, check to see if the previous character was a newline. // If so, then this is a continuation of the previous line if let Some(prev) = state.output.last_mut() { match prev.contents { TokenContents::Eol => { *prev = Token::new( TokenContents::Pipe, Span::new(state.span_offset + idx, state.span_offset + idx + 1), ); // And this is a continuation of the previous line if previous line is a // comment line (combined with EOL + Comment) // // Initially, the last one token is TokenContents::Pipe, we don't need to // check it, so the beginning offset is 2. let mut offset = 2; while state.output.len() > offset { let index = state.output.len() - offset; if state.output[index].contents == TokenContents::Comment && state.output[index - 1].contents == TokenContents::Eol { state.output.remove(index - 1); offset += 1; } else { break; } } } _ => { state.output.push(Token::new( TokenContents::Pipe, Span::new(state.span_offset + idx, state.span_offset + idx + 1), )); } } } else { state.output.push(Token::new( TokenContents::Pipe, Span::new(state.span_offset + idx, state.span_offset + idx + 1), )); } is_complete = false; } else if c == b';' { // If the next character is a `;`, we're looking at a semicolon token. if !is_complete && state.error.is_none() { state.error = Some(ParseError::ExtraTokens(Span::new( curr_offset, curr_offset + 1, ))); } let idx = curr_offset; curr_offset += 1; state.output.push(Token::new( TokenContents::Semicolon, Span::new(state.span_offset + idx, state.span_offset + idx + 1), )); } else if c == b'\r' { // Ignore a stand-alone carriage return curr_offset += 1; } else if c == b'\n' { // If the next character is a newline, we're looking at an EOL (end of line) token. let idx = curr_offset; curr_offset += 1; if !additional_whitespace.contains(&c) { state.output.push(Token::new( TokenContents::Eol, Span::new(state.span_offset + idx, state.span_offset + idx + 1), )); } } else if c == b'#' { // If the next character is `#`, we're at the beginning of a line // comment. The comment continues until the next newline. let mut start = curr_offset; while let Some(input) = state.input.get(curr_offset) { if *input == b'\n' { if !skip_comment { state.output.push(Token::new( TokenContents::Comment, Span::new(state.span_offset + start, state.span_offset + curr_offset), )); } start = curr_offset; break; } else { curr_offset += 1; } } if start != curr_offset && !skip_comment { state.output.push(Token::new( TokenContents::Comment, Span::new(state.span_offset + start, state.span_offset + curr_offset), )); } } else if c == b' ' || c == b'\t' || additional_whitespace.contains(&c) { // If the next character is non-newline whitespace, skip it. curr_offset += 1; } else { let (token, err) = lex_item( state.input, &mut curr_offset, state.span_offset, additional_whitespace, special_tokens, in_signature, ); if state.error.is_none() { state.error = err; } is_complete = true; state.output.push(token); } } } /// True if this the start of a redirection. Does not match `>>` or `>|` forms. fn is_redirection(token: &[u8]) -> bool { matches!( token, b"o>" | b"out>" | b"e>" | b"err>" | b"o+e>" | b"e+o>" | b"out+err>" | b"err+out>" ) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-parser/tests/test_lex.rs
crates/nu-parser/tests/test_lex.rs
#![allow(clippy::byte_char_slices)] use nu_parser::{LexState, Token, TokenContents, lex, lex_n_tokens, lex_signature}; use nu_protocol::{ParseError, Span}; #[test] fn lex_basic() { let file = b"let x = 4"; let output = lex(file, 0, &[], &[], true); assert!(output.1.is_none()); } #[test] fn lex_newline() { let file = b"let x = 300\nlet y = 500;"; let output = lex(file, 0, &[], &[], true); assert!(output.0.contains(&Token { contents: TokenContents::Eol, span: Span::new(11, 12) })); } #[test] fn lex_annotations_list() { let file = b"items: list<string>"; let (output, err) = lex_signature(file, 0, &[b'\n', b'\r'], &[b':', b'=', b','], false); assert!(err.is_none()); assert_eq!(output.len(), 3); } #[test] fn lex_annotations_record() { let file = b"config: record<name: string>"; let (output, err) = lex_signature(file, 0, &[b'\n', b'\r'], &[b':', b'=', b','], false); assert!(err.is_none()); assert_eq!(output.len(), 3); } #[test] fn lex_annotations_empty() { let file = b"items: list<>"; let (output, err) = lex_signature(file, 0, &[b'\n', b'\r'], &[b':', b'=', b','], false); assert!(err.is_none()); assert_eq!(output.len(), 3); } #[test] fn lex_annotations_space_before_annotations() { let file = b"items: list <string>"; let (output, err) = lex_signature(file, 0, &[b'\n', b'\r'], &[b':', b'=', b','], false); assert!(err.is_none()); assert_eq!(output.len(), 4); } #[test] fn lex_annotations_space_within_annotations() { let file = b"items: list< string>"; let (output, err) = lex_signature(file, 0, &[b'\n', b'\r'], &[b':', b'=', b','], false); assert!(err.is_none()); assert_eq!(output.len(), 3); let file = b"items: list<string >"; let (output, err) = lex_signature(file, 0, &[b'\n', b'\r'], &[b':', b'=', b','], false); assert!(err.is_none()); assert_eq!(output.len(), 3); let file = b"items: list< string >"; let (output, err) = lex_signature(file, 0, &[b'\n', b'\r'], &[b':', b'=', b','], false); assert!(err.is_none()); assert_eq!(output.len(), 3); } #[test] fn lex_annotations_nested() { let file = b"items: list<record<name: string>>"; let (output, err) = lex_signature(file, 0, &[b'\n', b'\r'], &[b':', b'=', b','], false); assert!(err.is_none()); assert_eq!(output.len(), 3); } #[test] fn lex_annotations_nested_unterminated() { let file = b"items: list<record<name: string>"; let (output, err) = lex_signature(file, 0, &[b'\n', b'\r'], &[b':', b'=', b','], false); assert!(matches!(err.unwrap(), ParseError::UnexpectedEof(_, _))); assert_eq!(output.len(), 3); } #[test] fn lex_annotations_unterminated() { let file = b"items: list<string"; let (output, err) = lex_signature(file, 0, &[b'\n', b'\r'], &[b':', b'=', b','], false); assert!(matches!(err.unwrap(), ParseError::UnexpectedEof(_, _))); assert_eq!(output.len(), 3); } #[test] fn lex_empty() { let file = b""; let output = lex(file, 0, &[], &[], true); assert!(output.0.is_empty()); assert!(output.1.is_none()); } #[test] fn lex_parenthesis() { // The whole parenthesis is an item for the lexer let file = b"let x = (300 + (322 * 444));"; let output = lex(file, 0, &[], &[], true); assert_eq!( output.0.get(3).unwrap(), &Token { contents: TokenContents::Item, span: Span::new(8, 27) } ); } #[test] fn lex_comment() { let file = b"let x = 300 # a comment \n $x + 444"; let output = lex(file, 0, &[], &[], false); assert_eq!( output.0.get(4).unwrap(), &Token { contents: TokenContents::Comment, span: Span::new(12, 24) } ); } #[test] fn lex_not_comment_needs_space_in_front_of_hashtag() { let file = b"1..10 | each {echo test#testing }"; let output = lex(file, 0, &[], &[], false); assert!(output.1.is_none()); } #[test] fn lex_comment_with_space_in_front_of_hashtag() { let file = b"1..10 | each {echo test #testing }"; let output = lex(file, 0, &[], &[], false); assert!(output.1.is_some()); assert!(matches!( output.1.unwrap(), ParseError::UnexpectedEof(missing_token, span) if missing_token == "}" && span == Span::new(33, 34) )); } #[test] fn lex_comment_with_tab_in_front_of_hashtag() { let file = b"1..10 | each {echo test\t#testing }"; let output = lex(file, 0, &[], &[], false); assert!(output.1.is_some()); assert!(matches!( output.1.unwrap(), ParseError::UnexpectedEof(missing_token, span) if missing_token == "}" && span == Span::new(33, 34) )); } #[test] fn lex_is_incomplete() { let file = b"let x = 300 | ;"; let output = lex(file, 0, &[], &[], true); let err = output.1.unwrap(); assert!(matches!(err, ParseError::ExtraTokens(_))); } #[test] fn lex_incomplete_paren() { let file = b"let x = (300 + ( 4 + 1)"; let output = lex(file, 0, &[], &[], true); let err = output.1.unwrap(); assert!(matches!(err, ParseError::UnexpectedEof(v, _) if v == ")")); } #[test] fn lex_incomplete_quote() { let file = b"let x = '300 + 4 + 1"; let output = lex(file, 0, &[], &[], true); let err = output.1.unwrap(); assert!(matches!(err, ParseError::UnexpectedEof(v, _) if v == "'")); } #[test] fn lex_comments_no_space() { // test for parses that contain tokens that normally introduce comments // Code: // let z = 42 #the comment // let x#y = 69 #hello // let flk = nixpkgs#hello #hello let file = b"let z = 42 #the comment \n let x#y = 69 #hello \n let flk = nixpkgs#hello #hello"; let output = lex(file, 0, &[], &[], false); assert_eq!( output.0.get(4).unwrap(), &Token { contents: TokenContents::Comment, span: Span::new(11, 24) } ); assert_eq!( output.0.get(7).unwrap(), &Token { contents: TokenContents::Item, span: Span::new(30, 33) } ); assert_eq!( output.0.get(10).unwrap(), &Token { contents: TokenContents::Comment, span: Span::new(39, 46) } ); assert_eq!( output.0.get(15).unwrap(), &Token { contents: TokenContents::Item, span: Span::new(58, 71) } ); assert_eq!( output.0.get(16).unwrap(), &Token { contents: TokenContents::Comment, span: Span::new(72, 78) } ); } #[test] fn lex_comments() { // Comments should keep the end of line token // Code: // let z = 4 // let x = 4 #comment // let y = 1 # comment let file = b"let z = 4 #comment \n let x = 4 # comment\n let y = 1 # comment"; let output = lex(file, 0, &[], &[], false); assert_eq!( output.0.get(4).unwrap(), &Token { contents: TokenContents::Comment, span: Span::new(10, 19) } ); assert_eq!( output.0.get(5).unwrap(), &Token { contents: TokenContents::Eol, span: Span::new(19, 20) } ); // When there is no space between the comment and the new line the span // for the command and the EOL overlaps assert_eq!( output.0.get(10).unwrap(), &Token { contents: TokenContents::Comment, span: Span::new(31, 40) } ); assert_eq!( output.0.get(11).unwrap(), &Token { contents: TokenContents::Eol, span: Span::new(40, 41) } ); } #[test] fn lex_manually() { let file = b"'a'\n#comment\n#comment again\n| continue"; let mut lex_state = LexState { input: file, output: Vec::new(), error: None, span_offset: 10, }; assert_eq!(lex_n_tokens(&mut lex_state, &[], &[], false, 1), 1); assert_eq!(lex_state.output.len(), 1); assert_eq!(lex_n_tokens(&mut lex_state, &[], &[], false, 5), 5); assert_eq!(lex_state.output.len(), 6); // Next token is the pipe. // This shortens the output because it exhausts the input before it can // compensate for the EOL tokens lost to the line continuation assert_eq!(lex_n_tokens(&mut lex_state, &[], &[], false, 1), -1); assert_eq!(lex_state.output.len(), 5); assert_eq!(file.len(), lex_state.span_offset - 10); let last_span = lex_state.output.last().unwrap().span; assert_eq!(&file[last_span.start - 10..last_span.end - 10], b"continue"); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-parser/tests/test_parser_unicode_escapes.rs
crates/nu-parser/tests/test_parser_unicode_escapes.rs
#![cfg(test)] use nu_parser::*; use nu_protocol::{ ast::Expr, engine::{EngineState, StateWorkingSet}, }; pub fn do_test(test: &[u8], expected: &str, error_contains: Option<&str>) { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let block = parse(&mut working_set, None, test, true); match working_set.parse_errors.first() { None => { assert_eq!(block.len(), 1); let pipeline = &block.pipelines[0]; assert_eq!(pipeline.len(), 1); let element = &pipeline.elements[0]; assert!(element.redirection.is_none()); assert_eq!(element.expr.expr, Expr::String(expected.to_string())); } Some(pev) => match error_contains { None => { panic!("Err:{pev:#?}"); } Some(contains_string) => { let full_err = format!("{pev:#?}"); assert!( full_err.contains(contains_string), "Expected error containing {contains_string}, instead got {full_err}" ); } }, } } // cases that all should work #[test] pub fn unicode_escapes_in_strings() { pub struct Tc(&'static [u8], &'static str); let test_vec = vec![ Tc(b"\"hello \\u{6e}\\u{000075}\\u{073}hell\"", "hello nushell"), // template: Tc(br#""<string literal without #'s>"", "<Rust literal comparand>") //deprecated Tc(br#""\u006enu\u0075\u0073\u0073""#, "nnuuss"), Tc(br#""hello \u{6e}\u{000075}\u{073}hell""#, "hello nushell"), Tc(br#""\u{39}8\u{10ffff}""#, "98\u{10ffff}"), Tc(br#""abc\u{41}""#, "abcA"), // at end of string Tc(br#""\u{41}abc""#, "Aabc"), // at start of string Tc(br#""\u{a}""#, "\n"), // single digit ]; for tci in test_vec { println!("Expecting: {}", tci.1); do_test(tci.0, tci.1, None); } } // cases that all should fail (in expected way) #[test] pub fn unicode_escapes_in_strings_expected_failures() { // input, substring of expected failure pub struct Tc(&'static [u8], &'static str); let test_vec = vec![ // template: Tc(br#""<string literal without #'s>"", "<pattern in expected error>") //deprecated Tc(br#""\u06e""#, "any shape"), // 4digit too short, next char is EOF //deprecatedTc(br#""\u06ex""#, "any shape"), // 4digit too short, next char is non-hex-digit Tc(br#""hello \u{6e""#, "missing '}'"), // extended, missing close delim Tc( br#""\u{39}8\u{000000000000000000000000000000000000000000000037}""#, "must be 1-6 hex digits", ), // hex too long, but small value Tc(br#""\u{110000}""#, "max value 10FFF"), // max unicode <= 0x10ffff ]; for tci in test_vec { println!("Expecting failure containing: {}", tci.1); do_test(tci.0, "--success not expected--", Some(tci.1)); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-parser/tests/test_parser.rs
crates/nu-parser/tests/test_parser.rs
use nu_parser::*; use nu_protocol::{ DeclId, FilesizeUnit, ParseError, Signature, Span, SyntaxShape, Type, Unit, ast::{Argument, Expr, Expression, ExternalArgument, PathMember, Range}, engine::{Command, EngineState, Stack, StateWorkingSet}, }; use rstest::rstest; use mock::{Alias, AttrEcho, Const, Def, IfMocked, Let, Mut, ToCustom}; fn test_int( test_tag: &str, // name of sub-test test: &[u8], // input expression expected_val: Expr, // (usually Expr::{Int,String, Float}, not ::BinOp... expected_err: Option<&str>, ) // substring in error text { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let block = parse(&mut working_set, None, test, true); let err = working_set.parse_errors.first(); if let Some(err_pat) = expected_err { if let Some(parse_err) = err { let act_err = format!("{parse_err:?}"); assert!( act_err.contains(err_pat), "{test_tag}: expected err to contain {err_pat}, but actual error was {act_err}" ); } else { assert!( err.is_some(), "{test_tag}: expected err containing {err_pat}, but no error returned" ); } } else { assert!(err.is_none(), "{test_tag}: unexpected error {err:#?}"); assert_eq!(block.len(), 1, "{test_tag}: result block length > 1"); let pipeline = &block.pipelines[0]; assert_eq!( pipeline.len(), 1, "{test_tag}: got multiple result expressions, expected 1" ); let element = &pipeline.elements[0]; assert!(element.redirection.is_none()); compare_rhs_binary_op(test_tag, &expected_val, &element.expr.expr); } } fn compare_rhs_binary_op( test_tag: &str, expected: &Expr, // the rhs expr we hope to see (::Int, ::Float, not ::B) observed: &Expr, // the Expr actually provided: can be ::Int, ::Float, ::String, // or ::BinOp (in which case rhs is checked), or ::Call (in which case cmd is checked) ) { match observed { Expr::Int(..) | Expr::Float(..) | Expr::String(..) => { assert_eq!( expected, observed, "{test_tag}: Expected: {expected:#?}, observed {observed:#?}" ); } Expr::BinaryOp(_, _, e) => { let observed_expr = &e.expr; // can't pattern match Box<Foo>, but can match the box, then deref in separate statement. assert_eq!( expected, observed_expr, "{test_tag}: Expected: {expected:#?}, observed: {observed:#?}" ) } Expr::ExternalCall(e, _) => { let observed_expr = &e.expr; assert_eq!( expected, observed_expr, "{test_tag}: Expected: {expected:#?}, observed: {observed_expr:#?}" ) } _ => { panic!("{test_tag}: Unexpected Expr:: variant returned, observed {observed:#?}"); } } } #[test] pub fn multi_test_parse_int() { struct Test<'a>(&'a str, &'a [u8], Expr, Option<&'a str>); // use test expression of form '0 + x' to force parse() to parse x as numeric. // if expression were just 'x', parse() would try other items that would mask the error we're looking for. let tests = vec![ Test("binary literal int", b"0 + 0b0", Expr::Int(0), None), Test( "binary literal invalid digits", b"0 + 0b2", Expr::Int(0), Some("invalid digits for radix 2"), ), Test("octal literal int", b"0 + 0o1", Expr::Int(1), None), Test( "octal literal int invalid digits", b"0 + 0o8", Expr::Int(0), Some("invalid digits for radix 8"), ), Test( "octal literal int truncated", b"0 + 0o", Expr::Int(0), Some("invalid digits for radix 8"), ), Test("hex literal int", b"0 + 0x2", Expr::Int(2), None), Test( "hex literal int invalid digits", b"0 + 0x0aq", Expr::Int(0), Some("invalid digits for radix 16"), ), Test( "hex literal with 'e' not mistaken for float", b"0 + 0x00e0", Expr::Int(0xe0), None, ), // decimal (rad10) literal is anything that starts with // optional sign then a digit. Test("rad10 literal int", b"0 + 42", Expr::Int(42), None), Test( "rad10 with leading + sign", b"0 + -42", Expr::Int(-42), None, ), Test("rad10 with leading - sign", b"0 + +42", Expr::Int(42), None), Test( "flag char is string, not (invalid) int", b"-x", Expr::String("-x".into()), None, ), Test( "keyword parameter is string", b"--exact", Expr::String("--exact".into()), None, ), Test( "ranges or relative paths not confused for int", b"./a/b", Expr::GlobPattern("./a/b".into(), false), None, ), Test( "semver data not confused for int", b"'1.0.1'", Expr::String("1.0.1".into()), None, ), ]; for test in tests { test_int(test.0, test.1, test.2, test.3); } } #[ignore] #[test] pub fn multi_test_parse_number() { struct Test<'a>(&'a str, &'a [u8], Expr, Option<&'a str>); // use test expression of form '0 + x' to force parse() to parse x as numeric. // if expression were just 'x', parse() would try other items that would mask the error we're looking for. let tests = vec![ Test("float decimal", b"0 + 43.5", Expr::Float(43.5), None), //Test("float with leading + sign", b"0 + +41.7", Expr::Float(-41.7), None), Test( "float with leading - sign", b"0 + -41.7", Expr::Float(-41.7), None, ), Test( "float scientific notation", b"0 + 3e10", Expr::Float(3.00e10), None, ), Test( "float decimal literal invalid digits", b"0 + .3foo", Expr::Int(0), Some("invalid digits"), ), Test( "float scientific notation literal invalid digits", b"0 + 3e0faa", Expr::Int(0), Some("invalid digits"), ), Test( // odd that error is unsupportedOperation, but it does fail. "decimal literal int 2 leading signs", b"0 + --9", Expr::Int(0), Some("UnsupportedOperation"), ), //Test( // ".<string> should not be taken as float", // b"abc + .foo", // Expr::String("..".into()), // None, //), ]; for test in tests { test_int(test.0, test.1, test.2, test.3); } } #[ignore] #[test] fn test_parse_any() { let test = b"1..10"; let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let block = parse(&mut working_set, None, test, true); match (block, working_set.parse_errors.first()) { (_, Some(e)) => { println!("test: {test:?}, error: {e:#?}"); } (b, None) => { println!("test: {test:?}, parse: {b:#?}"); } } } #[test] pub fn parse_int() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let block = parse(&mut working_set, None, b"3", true); assert!(working_set.parse_errors.is_empty()); assert_eq!(block.len(), 1); let pipeline = &block.pipelines[0]; assert_eq!(pipeline.len(), 1); let element = &pipeline.elements[0]; assert!(element.redirection.is_none()); assert_eq!(element.expr.expr, Expr::Int(3)); } #[test] pub fn parse_int_with_underscores() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let block = parse(&mut working_set, None, b"420_69_2023", true); assert!(working_set.parse_errors.is_empty()); assert_eq!(block.len(), 1); let pipeline = &block.pipelines[0]; assert_eq!(pipeline.len(), 1); let element = &pipeline.elements[0]; assert!(element.redirection.is_none()); assert_eq!(element.expr.expr, Expr::Int(420692023)); } #[test] pub fn parse_filesize() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let block = parse(&mut working_set, None, b"95307.27MiB", true); assert!(working_set.parse_errors.is_empty()); assert_eq!(block.len(), 1); let pipeline = &block.pipelines[0]; assert_eq!(pipeline.len(), 1); let element = &pipeline.elements[0]; assert!(element.redirection.is_none()); let Expr::ValueWithUnit(value) = &element.expr.expr else { panic!("should be a ValueWithUnit"); }; assert_eq!(value.expr.expr, Expr::Int(99_936_915_947)); assert_eq!(value.unit.item, Unit::Filesize(FilesizeUnit::B)); } #[test] pub fn parse_non_utf8_fails() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); // Panic when parsing units was triggered by non-UTF8 characters // due to bad handling via `String::from_utf8_lossy` // // See https://github.com/nushell/nushell/pull/16355 let _block = parse(&mut working_set, None, b"0\xffB", true); // Asserting on the exact error doesn't make as much sense as assert!(!working_set.parse_errors.is_empty()); } #[test] pub fn parse_cell_path() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); working_set.add_variable( "foo".to_string().into_bytes(), Span::test_data(), nu_protocol::Type::record(), false, ); let block = parse(&mut working_set, None, b"$foo.bar.baz", true); assert!(working_set.parse_errors.is_empty()); assert_eq!(block.len(), 1); let pipeline = &block.pipelines[0]; assert_eq!(pipeline.len(), 1); let element = &pipeline.elements[0]; assert!(element.redirection.is_none()); if let Expr::FullCellPath(b) = &element.expr.expr { assert!(matches!(b.head.expr, Expr::Var(_))); if let [a, b] = &b.tail[..] { if let PathMember::String { val, optional, .. } = a { assert_eq!(val, "bar"); assert_eq!(optional, &false); } else { panic!("wrong type") } if let PathMember::String { val, optional, .. } = b { assert_eq!(val, "baz"); assert_eq!(optional, &false); } else { panic!("wrong type") } } else { panic!("cell path tail is unexpected") } } else { panic!("Not a cell path"); } } #[test] pub fn parse_cell_path_optional() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); working_set.add_variable( "foo".to_string().into_bytes(), Span::test_data(), nu_protocol::Type::record(), false, ); let block = parse(&mut working_set, None, b"$foo.bar?.baz", true); assert!(working_set.parse_errors.is_empty()); assert_eq!(block.len(), 1); let pipeline = &block.pipelines[0]; assert_eq!(pipeline.len(), 1); let element = &pipeline.elements[0]; assert!(element.redirection.is_none()); if let Expr::FullCellPath(b) = &element.expr.expr { assert!(matches!(b.head.expr, Expr::Var(_))); if let [a, b] = &b.tail[..] { if let PathMember::String { val, optional, .. } = a { assert_eq!(val, "bar"); assert_eq!(optional, &true); } else { panic!("wrong type") } if let PathMember::String { val, optional, .. } = b { assert_eq!(val, "baz"); assert_eq!(optional, &false); } else { panic!("wrong type") } } else { panic!("cell path tail is unexpected") } } else { panic!("Not a cell path"); } } #[test] pub fn parse_binary_with_hex_format() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let block = parse(&mut working_set, None, b"0x[13]", true); assert!(working_set.parse_errors.is_empty()); assert_eq!(block.len(), 1); let pipeline = &block.pipelines[0]; assert_eq!(pipeline.len(), 1); let element = &pipeline.elements[0]; assert!(element.redirection.is_none()); assert_eq!(element.expr.expr, Expr::Binary(vec![0x13])); } #[test] pub fn parse_binary_with_incomplete_hex_format() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let block = parse(&mut working_set, None, b"0x[3]", true); assert!(working_set.parse_errors.is_empty()); assert_eq!(block.len(), 1); let pipeline = &block.pipelines[0]; assert_eq!(pipeline.len(), 1); let element = &pipeline.elements[0]; assert!(element.redirection.is_none()); assert_eq!(element.expr.expr, Expr::Binary(vec![0x03])); } #[test] pub fn parse_binary_with_binary_format() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let block = parse(&mut working_set, None, b"0b[1010 1000]", true); assert!(working_set.parse_errors.is_empty()); assert_eq!(block.len(), 1); let pipeline = &block.pipelines[0]; assert_eq!(pipeline.len(), 1); let element = &pipeline.elements[0]; assert!(element.redirection.is_none()); assert_eq!(element.expr.expr, Expr::Binary(vec![0b10101000])); } #[test] pub fn parse_binary_with_incomplete_binary_format() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let block = parse(&mut working_set, None, b"0b[10]", true); assert!(working_set.parse_errors.is_empty()); assert_eq!(block.len(), 1); let pipeline = &block.pipelines[0]; assert_eq!(pipeline.len(), 1); let element = &pipeline.elements[0]; assert!(element.redirection.is_none()); assert_eq!(element.expr.expr, Expr::Binary(vec![0b00000010])); } #[test] pub fn parse_binary_with_octal_format() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let block = parse(&mut working_set, None, b"0o[250]", true); assert!(working_set.parse_errors.is_empty()); assert_eq!(block.len(), 1); let pipeline = &block.pipelines[0]; assert_eq!(pipeline.len(), 1); let element = &pipeline.elements[0]; assert!(element.redirection.is_none()); assert_eq!(element.expr.expr, Expr::Binary(vec![0o250])); } #[test] pub fn parse_binary_with_incomplete_octal_format() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let block = parse(&mut working_set, None, b"0o[2]", true); assert!(working_set.parse_errors.is_empty()); assert_eq!(block.len(), 1); let pipeline = &block.pipelines[0]; assert_eq!(pipeline.len(), 1); let element = &pipeline.elements[0]; assert!(element.redirection.is_none()); assert_eq!(element.expr.expr, Expr::Binary(vec![0o2])); } #[test] pub fn parse_binary_with_invalid_octal_format() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let block = parse(&mut working_set, None, b"0o[90]", true); assert_eq!(working_set.parse_errors.len(), 1); assert!(matches!( working_set.parse_errors.first(), Some(ParseError::InvalidBinaryString(_, _)) )); assert_eq!(block.len(), 1); let pipeline = &block.pipelines[0]; assert_eq!(pipeline.len(), 1); let element = &pipeline.elements[0]; assert!(element.redirection.is_none()); assert!(!matches!(element.expr.expr, Expr::Binary(_))); } #[test] pub fn parse_binary_with_multi_byte_char() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); // found using fuzzing, Rust can panic if you slice into this string let contents = b"0x[\xEF\xBF\xBD]"; let block = parse(&mut working_set, None, contents, true); assert_eq!(working_set.parse_errors.len(), 1); assert!(matches!( working_set.parse_errors.first(), Some(ParseError::InvalidBinaryString(_, _)) )); assert_eq!(block.len(), 1); let pipeline = &block.pipelines[0]; assert_eq!(pipeline.len(), 1); let element = &pipeline.elements[0]; assert!(element.redirection.is_none()); assert!(!matches!(element.expr.expr, Expr::Binary(_))) } #[test] pub fn parse_call() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let sig = Signature::build("foo").named("--jazz", SyntaxShape::Int, "jazz!!", Some('j')); working_set.add_decl(sig.predeclare()); let block = parse(&mut working_set, None, b"foo", true); assert!(working_set.parse_errors.is_empty()); assert_eq!(block.len(), 1); let pipeline = &block.pipelines[0]; assert_eq!(pipeline.len(), 1); let element = &pipeline.elements[0]; assert!(element.redirection.is_none()); if let Expr::Call(call) = &element.expr.expr { assert_eq!(call.decl_id, DeclId::new(0)); } } #[test] pub fn parse_call_missing_flag_arg() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let sig = Signature::build("foo").named("jazz", SyntaxShape::Int, "jazz!!", Some('j')); working_set.add_decl(sig.predeclare()); parse(&mut working_set, None, b"foo --jazz", true); assert!(matches!( working_set.parse_errors.first(), Some(ParseError::MissingFlagParam(..)) )); } #[test] pub fn parse_call_missing_short_flag_arg() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let sig = Signature::build("foo").named("--jazz", SyntaxShape::Int, "jazz!!", Some('j')); working_set.add_decl(sig.predeclare()); parse(&mut working_set, None, b"foo -j", true); assert!(matches!( working_set.parse_errors.first(), Some(ParseError::MissingFlagParam(..)) )); } #[test] pub fn parse_call_short_flag_batch_arg_allowed() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let sig = Signature::build("foo") .named("--jazz", SyntaxShape::Int, "jazz!!", Some('j')) .switch("--math", "math!!", Some('m')); working_set.add_decl(sig.predeclare()); let block = parse(&mut working_set, None, b"foo -mj 10", true); assert!(working_set.parse_errors.is_empty()); assert_eq!(block.len(), 1); let pipeline = &block.pipelines[0]; assert_eq!(pipeline.len(), 1); let element = &pipeline.elements[0]; assert!(element.redirection.is_none()); if let Expr::Call(call) = &element.expr.expr { assert_eq!(call.decl_id, DeclId::new(0)); assert_eq!(call.arguments.len(), 2); matches!(call.arguments[0], Argument::Named((_, None, None))); matches!(call.arguments[1], Argument::Named((_, None, Some(_)))); } } #[test] pub fn parse_call_short_flag_batch_arg_disallowed() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let sig = Signature::build("foo") .named("--jazz", SyntaxShape::Int, "jazz!!", Some('j')) .switch("--math", "math!!", Some('m')); working_set.add_decl(sig.predeclare()); parse(&mut working_set, None, b"foo -jm 10", true); assert!(matches!( working_set.parse_errors.first(), Some(ParseError::OnlyLastFlagInBatchCanTakeArg(..)) )); } #[test] pub fn parse_call_short_flag_batch_disallow_multiple_args() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let sig = Signature::build("foo") .named("--math", SyntaxShape::Int, "math!!", Some('m')) .named("--jazz", SyntaxShape::Int, "jazz!!", Some('j')); working_set.add_decl(sig.predeclare()); parse(&mut working_set, None, b"foo -mj 10 20", true); assert!(matches!( working_set.parse_errors.first(), Some(ParseError::OnlyLastFlagInBatchCanTakeArg(..)) )); } #[test] pub fn parse_call_unknown_shorthand() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let sig = Signature::build("foo").switch("--jazz", "jazz!!", Some('j')); working_set.add_decl(sig.predeclare()); parse(&mut working_set, None, b"foo -mj", true); assert!(matches!( working_set.parse_errors.first(), Some(ParseError::UnknownFlag(..)) )); } #[test] pub fn parse_call_extra_positional() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let sig = Signature::build("foo").switch("--jazz", "jazz!!", Some('j')); working_set.add_decl(sig.predeclare()); parse(&mut working_set, None, b"foo -j 100", true); assert!(matches!( working_set.parse_errors.first(), Some(ParseError::ExtraPositional(..)) )); } #[test] pub fn parse_call_missing_req_positional() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let sig = Signature::build("foo").required("jazz", SyntaxShape::Int, "jazz!!"); working_set.add_decl(sig.predeclare()); parse(&mut working_set, None, b"foo", true); assert!(matches!( working_set.parse_errors.first(), Some(ParseError::MissingPositional(..)) )); } #[test] pub fn parse_call_missing_req_flag() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let sig = Signature::build("foo").required_named("--jazz", SyntaxShape::Int, "jazz!!", None); working_set.add_decl(sig.predeclare()); parse(&mut working_set, None, b"foo", true); assert!(matches!( working_set.parse_errors.first(), Some(ParseError::MissingRequiredFlag(..)) )); } #[test] pub fn parse_attribute_block_check_spans() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let source = br#" @foo a 1 2 @bar b 3 4 echo baz "#; let block = parse(&mut working_set, None, source, true); // There SHOULD be errors here, we're using nonexistent commands assert!(!working_set.parse_errors.is_empty()); assert_eq!(block.len(), 1); let pipeline = &block.pipelines[0]; assert_eq!(pipeline.len(), 1); let element = &pipeline.elements[0]; assert!(element.redirection.is_none()); let Expr::AttributeBlock(ab) = &element.expr.expr else { panic!("Couldn't parse attribute block"); }; assert_eq!( working_set.get_span_contents(ab.attributes[0].expr.span), b"foo a 1 2" ); assert_eq!( working_set.get_span_contents(ab.attributes[1].expr.span), b"bar b 3 4" ); assert_eq!(working_set.get_span_contents(ab.item.span), b"echo baz"); } #[test] pub fn parse_attributes_check_values() { let mut engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); working_set.add_decl(Box::new(Def)); working_set.add_decl(Box::new(AttrEcho)); let _ = engine_state.merge_delta(working_set.render()); let mut working_set = StateWorkingSet::new(&engine_state); let source = br#" @echo "hello world" @echo 42 def foo [] {} "#; let _ = parse(&mut working_set, None, source, false); assert!(working_set.parse_errors.is_empty()); let decl_id = working_set.find_decl(b"foo").unwrap(); let cmd = working_set.get_decl(decl_id); let attributes = cmd.attributes(); let (name, val) = &attributes[0]; assert_eq!(name, "echo"); assert_eq!(val.as_str(), Ok("hello world")); let (name, val) = &attributes[1]; assert_eq!(name, "echo"); assert_eq!(val.as_int(), Ok(42)); } #[test] pub fn parse_attributes_alias() { let mut engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); working_set.add_decl(Box::new(Def)); working_set.add_decl(Box::new(Alias)); working_set.add_decl(Box::new(AttrEcho)); let _ = engine_state.merge_delta(working_set.render()); let mut working_set = StateWorkingSet::new(&engine_state); let source = br#" alias "attr test" = attr echo @test null def foo [] {} "#; let _ = parse(&mut working_set, None, source, false); assert!(working_set.parse_errors.is_empty()); let decl_id = working_set.find_decl(b"foo").unwrap(); let cmd = working_set.get_decl(decl_id); let attributes = cmd.attributes(); let (name, val) = &attributes[0]; assert_eq!(name, "test"); assert!(val.is_nothing()); } #[test] pub fn parse_attributes_external_alias() { let mut engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); working_set.add_decl(Box::new(Def)); working_set.add_decl(Box::new(Alias)); working_set.add_decl(Box::new(AttrEcho)); let _ = engine_state.merge_delta(working_set.render()); let mut working_set = StateWorkingSet::new(&engine_state); let source = br#" alias "attr test" = ^echo @test null def foo [] {} "#; let _ = parse(&mut working_set, None, source, false); assert!(!working_set.parse_errors.is_empty()); let ParseError::LabeledError(shell_error, parse_error, _span) = &working_set.parse_errors[0] else { panic!("Expected LabeledError"); }; assert!(shell_error.contains("nu::shell::not_a_const_command")); assert!(parse_error.contains("Encountered error during parse-time evaluation")); } #[test] pub fn parse_if_in_const_expression() { // https://github.com/nushell/nushell/issues/15321 let mut engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); working_set.add_decl(Box::new(Const)); working_set.add_decl(Box::new(Def)); working_set.add_decl(Box::new(IfMocked)); let _ = engine_state.merge_delta(working_set.render()); let mut working_set = StateWorkingSet::new(&engine_state); let source = b"const foo = if t"; let _ = parse(&mut working_set, None, source, false); assert!(!working_set.parse_errors.is_empty()); let ParseError::MissingPositional(error, _, _) = &working_set.parse_errors[0] else { panic!("Expected MissingPositional"); }; assert!(error.contains("cond")); working_set.parse_errors = Vec::new(); let source = b"def a [n= (if ]"; let _ = parse(&mut working_set, None, source, false); assert!(!working_set.parse_errors.is_empty()); let ParseError::UnexpectedEof(error, _) = &working_set.parse_errors[0] else { panic!("Expected UnexpectedEof"); }; assert!(error.contains(")")); } fn test_external_call(input: &str, tag: &str, f: impl FnOnce(&Expression, &[ExternalArgument])) { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let block = parse(&mut working_set, None, input.as_bytes(), true); assert!( working_set.parse_errors.is_empty(), "{tag}: errors: {:?}", working_set.parse_errors ); let pipeline = &block.pipelines[0]; assert_eq!(1, pipeline.len()); let element = &pipeline.elements[0]; match &element.expr.expr { Expr::ExternalCall(name, args) => f(name, args), other => { panic!("{tag}: Unexpected expression in pipeline: {other:?}"); } } } fn check_external_call_interpolation( tag: &str, subexpr_count: usize, quoted: bool, expr: &Expression, ) -> bool { match &expr.expr { Expr::StringInterpolation(exprs) => { assert!(quoted, "{tag}: quoted"); assert_eq!(expr.ty, Type::String, "{tag}: expr.ty"); assert_eq!(subexpr_count, exprs.len(), "{tag}: subexpr_count"); true } Expr::GlobInterpolation(exprs, is_quoted) => { assert_eq!(quoted, *is_quoted, "{tag}: quoted"); assert_eq!(expr.ty, Type::Glob, "{tag}: expr.ty"); assert_eq!(subexpr_count, exprs.len(), "{tag}: subexpr_count"); true } _ => false, } } #[rstest] #[case("foo-external-call", "foo-external-call", "bare word")] #[case("^foo-external-call", "foo-external-call", "bare word with caret")] #[case( "foo/external-call", "foo/external-call", "bare word with forward slash" )] #[case( "^foo/external-call", "foo/external-call", "bare word with forward slash and caret" )] #[case(r"foo\external-call", r"foo\external-call", "bare word with backslash")] #[case( r"^foo\external-call", r"foo\external-call", "bare word with backslash and caret" )] #[case("`foo external call`", "foo external call", "backtick quote")] #[case( "^`foo external call`", "foo external call", "backtick quote with caret" )] #[case( "`foo/external call`", "foo/external call", "backtick quote with forward slash" )] #[case( "^`foo/external call`", "foo/external call", "backtick quote with forward slash and caret" )] #[case( r"`foo\external call`", r"foo\external call", "backtick quote with backslash" )] #[case( r"^`foo\external call`", r"foo\external call", "backtick quote with backslash and caret" )] pub fn test_external_call_head_glob( #[case] input: &str, #[case] expected: &str, #[case] tag: &str, ) { test_external_call(input, tag, |name, args| { match &name.expr { Expr::GlobPattern(string, is_quoted) => { assert_eq!(expected, string, "{tag}: incorrect name"); assert!(!*is_quoted); } other => { panic!("{tag}: Unexpected expression in command name position: {other:?}"); } } assert_eq!(0, args.len()); }) } #[rstest] #[case( r##"^r#'foo-external-call'#"##, "foo-external-call", "raw string with caret" )] #[case( r##"^r#'foo/external-call'#"##, "foo/external-call", "raw string with forward slash and caret" )] #[case( r##"^r#'foo\external-call'#"##, r"foo\external-call", "raw string with backslash and caret" )] pub fn test_external_call_head_raw_string( #[case] input: &str, #[case] expected: &str, #[case] tag: &str, ) { test_external_call(input, tag, |name, args| { match &name.expr { Expr::RawString(string) => { assert_eq!(expected, string, "{tag}: incorrect name"); } other => { panic!("{tag}: Unexpected expression in command name position: {other:?}"); } } assert_eq!(0, args.len()); }) } #[rstest] #[case("^'foo external call'", "foo external call", "single quote with caret")] #[case( "^'foo/external call'", "foo/external call", "single quote with forward slash and caret" )] #[case( r"^'foo\external call'", r"foo\external call", "single quote with backslash and caret" )] #[case( r#"^"foo external call""#, r#"foo external call"#, "double quote with caret" )] #[case( r#"^"foo/external call""#, r#"foo/external call"#, "double quote with forward slash and caret" )] #[case( r#"^"foo\\external call""#, r#"foo\external call"#, "double quote with backslash and caret" )] pub fn test_external_call_head_string( #[case] input: &str, #[case] expected: &str, #[case] tag: &str, ) { test_external_call(input, tag, |name, args| { match &name.expr { Expr::String(string) => { assert_eq!(expected, string); } other => {
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
true
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-parser/fuzz/fuzz_targets/parse.rs
crates/nu-parser/fuzz/fuzz_targets/parse.rs
#![no_main] use libfuzzer_sys::fuzz_target; use nu_parser::*; use nu_protocol::engine::{EngineState, StateWorkingSet}; fuzz_target!(|data: &[u8]| { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let _block = parse(&mut working_set, None, &data, true); });
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-parser/fuzz/fuzz_targets/parse_with_keywords.rs
crates/nu-parser/fuzz/fuzz_targets/parse_with_keywords.rs
#![no_main] use libfuzzer_sys::fuzz_target; use nu_cmd_lang::create_default_context; use nu_parser::*; use nu_protocol::engine::StateWorkingSet; fuzz_target!(|data: &[u8]| { let engine_state = create_default_context(); let mut working_set = StateWorkingSet::new(&engine_state); let _block = parse(&mut working_set, None, &data, true); });
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/lib.rs
crates/nu_plugin_polars/src/lib.rs
#![allow(clippy::result_large_err)] use std::{ cmp::Ordering, panic::{AssertUnwindSafe, catch_unwind}, }; use cache::cache_commands; pub use cache::{Cache, Cacheable}; use command::{ aggregation::aggregation_commands, boolean::boolean_commands, computation::computation_commands, core::core_commands, data::data_commands, datetime::datetime_commands, index::index_commands, integer::integer_commands, list::list_commands, string::string_commands, stub::PolarsCmd, }; use log::debug; use nu_plugin::{EngineInterface, Plugin, PluginCommand}; mod cache; mod cloud; pub mod dataframe; pub use dataframe::*; use nu_protocol::{ CustomValue, LabeledError, ShellError, Span, Spanned, Value, ast::Operator, casing::Casing, }; use tokio::runtime::Runtime; use values::CustomValueType; use crate::values::PolarsPluginCustomValue; pub trait EngineWrapper { fn get_env_var(&self, key: &str) -> Option<String>; fn use_color(&self) -> bool; fn set_gc_disabled(&self, disabled: bool) -> Result<(), ShellError>; } impl EngineWrapper for &EngineInterface { fn get_env_var(&self, key: &str) -> Option<String> { EngineInterface::get_env_var(self, key) .ok() .flatten() .map(|x| match x { Value::String { val, .. } => val, _ => "".to_string(), }) } fn use_color(&self) -> bool { self.get_config() .ok() .and_then(|config| config.color_config.get("use_color").cloned()) .unwrap_or(Value::bool(false, Span::unknown())) .is_true() } fn set_gc_disabled(&self, disabled: bool) -> Result<(), ShellError> { debug!("set_gc_disabled called with {disabled}"); EngineInterface::set_gc_disabled(self, disabled) } } pub struct PolarsPlugin { pub(crate) cache: Cache, /// For testing purposes only pub(crate) disable_cache_drop: bool, pub(crate) runtime: Runtime, } impl PolarsPlugin { pub fn new() -> Result<Self, ShellError> { Ok(Self { cache: Cache::default(), disable_cache_drop: false, runtime: Runtime::new().map_err(|e| ShellError::GenericError { error: format!("Could not instantiate tokio: {e}"), msg: "".into(), span: None, help: None, inner: vec![], })?, }) } } impl Plugin for PolarsPlugin { fn version(&self) -> String { env!("CARGO_PKG_VERSION").into() } fn commands(&self) -> Vec<Box<dyn PluginCommand<Plugin = Self>>> { let mut commands: Vec<Box<dyn PluginCommand<Plugin = Self>>> = vec![Box::new(PolarsCmd)]; commands.append(&mut aggregation_commands()); commands.append(&mut boolean_commands()); commands.append(&mut core_commands()); commands.append(&mut computation_commands()); commands.append(&mut data_commands()); commands.append(&mut datetime_commands()); commands.append(&mut index_commands()); commands.append(&mut integer_commands()); commands.append(&mut string_commands()); commands.append(&mut list_commands()); commands.append(&mut cache_commands()); commands } fn custom_value_dropped( &self, engine: &EngineInterface, custom_value: Box<dyn CustomValue>, ) -> Result<(), LabeledError> { debug!("custom_value_dropped called {custom_value:?}"); if !self.disable_cache_drop { let id = CustomValueType::try_from_custom_value(custom_value)?.id(); let _ = self.cache.remove(engine, &id, false); } Ok(()) } fn custom_value_to_base_value( &self, engine: &EngineInterface, custom_value: Spanned<Box<dyn CustomValue>>, ) -> Result<Value, LabeledError> { let result = match CustomValueType::try_from_custom_value(custom_value.item)? { CustomValueType::NuDataFrame(cv) => cv.custom_value_to_base_value(self, engine), CustomValueType::NuLazyFrame(cv) => cv.custom_value_to_base_value(self, engine), CustomValueType::NuExpression(cv) => cv.custom_value_to_base_value(self, engine), CustomValueType::NuLazyGroupBy(cv) => cv.custom_value_to_base_value(self, engine), CustomValueType::NuWhen(cv) => cv.custom_value_to_base_value(self, engine), CustomValueType::NuDataType(cv) => cv.custom_value_to_base_value(self, engine), CustomValueType::NuSchema(cv) => cv.custom_value_to_base_value(self, engine), }; Ok(result?) } fn custom_value_operation( &self, engine: &EngineInterface, left: Spanned<Box<dyn CustomValue>>, operator: Spanned<Operator>, right: Value, ) -> Result<Value, LabeledError> { let result = match CustomValueType::try_from_custom_value(left.item)? { CustomValueType::NuDataFrame(cv) => { cv.custom_value_operation(self, engine, left.span, operator, right) } CustomValueType::NuLazyFrame(cv) => { cv.custom_value_operation(self, engine, left.span, operator, right) } CustomValueType::NuExpression(cv) => { cv.custom_value_operation(self, engine, left.span, operator, right) } CustomValueType::NuLazyGroupBy(cv) => { cv.custom_value_operation(self, engine, left.span, operator, right) } CustomValueType::NuWhen(cv) => { cv.custom_value_operation(self, engine, left.span, operator, right) } CustomValueType::NuDataType(cv) => { cv.custom_value_operation(self, engine, left.span, operator, right) } CustomValueType::NuSchema(cv) => { cv.custom_value_operation(self, engine, left.span, operator, right) } }; Ok(result?) } fn custom_value_follow_path_int( &self, engine: &EngineInterface, custom_value: Spanned<Box<dyn CustomValue>>, index: Spanned<usize>, // TODO: check if we should respect these _optional: bool, ) -> Result<Value, LabeledError> { let result = match CustomValueType::try_from_custom_value(custom_value.item)? { CustomValueType::NuDataFrame(cv) => { cv.custom_value_follow_path_int(self, engine, custom_value.span, index) } CustomValueType::NuLazyFrame(cv) => { cv.custom_value_follow_path_int(self, engine, custom_value.span, index) } CustomValueType::NuExpression(cv) => { cv.custom_value_follow_path_int(self, engine, custom_value.span, index) } CustomValueType::NuLazyGroupBy(cv) => { cv.custom_value_follow_path_int(self, engine, custom_value.span, index) } CustomValueType::NuWhen(cv) => { cv.custom_value_follow_path_int(self, engine, custom_value.span, index) } CustomValueType::NuDataType(cv) => { cv.custom_value_follow_path_int(self, engine, custom_value.span, index) } CustomValueType::NuSchema(cv) => { cv.custom_value_follow_path_int(self, engine, custom_value.span, index) } }; Ok(result?) } fn custom_value_follow_path_string( &self, engine: &EngineInterface, custom_value: Spanned<Box<dyn CustomValue>>, column_name: Spanned<String>, // TODO: check if we should respect these _optional: bool, _casing: Casing, ) -> Result<Value, LabeledError> { let result = match CustomValueType::try_from_custom_value(custom_value.item)? { CustomValueType::NuDataFrame(cv) => { cv.custom_value_follow_path_string(self, engine, custom_value.span, column_name) } CustomValueType::NuLazyFrame(cv) => { cv.custom_value_follow_path_string(self, engine, custom_value.span, column_name) } CustomValueType::NuExpression(cv) => { cv.custom_value_follow_path_string(self, engine, custom_value.span, column_name) } CustomValueType::NuLazyGroupBy(cv) => { cv.custom_value_follow_path_string(self, engine, custom_value.span, column_name) } CustomValueType::NuWhen(cv) => { cv.custom_value_follow_path_string(self, engine, custom_value.span, column_name) } CustomValueType::NuDataType(cv) => { cv.custom_value_follow_path_string(self, engine, custom_value.span, column_name) } CustomValueType::NuSchema(cv) => { cv.custom_value_follow_path_string(self, engine, custom_value.span, column_name) } }; Ok(result?) } fn custom_value_partial_cmp( &self, engine: &EngineInterface, custom_value: Box<dyn CustomValue>, other_value: Value, ) -> Result<Option<Ordering>, LabeledError> { let result = match CustomValueType::try_from_custom_value(custom_value)? { CustomValueType::NuDataFrame(cv) => { cv.custom_value_partial_cmp(self, engine, other_value) } CustomValueType::NuLazyFrame(cv) => { cv.custom_value_partial_cmp(self, engine, other_value) } CustomValueType::NuExpression(cv) => { cv.custom_value_partial_cmp(self, engine, other_value) } CustomValueType::NuLazyGroupBy(cv) => { cv.custom_value_partial_cmp(self, engine, other_value) } CustomValueType::NuWhen(cv) => cv.custom_value_partial_cmp(self, engine, other_value), CustomValueType::NuDataType(cv) => { cv.custom_value_partial_cmp(self, engine, other_value) } CustomValueType::NuSchema(cv) => cv.custom_value_partial_cmp(self, engine, other_value), }; Ok(result?) } } pub(crate) fn handle_panic<F, R>(f: F, span: Span) -> Result<R, ShellError> where F: FnOnce() -> Result<R, ShellError>, { match catch_unwind(AssertUnwindSafe(f)) { Ok(inner_result) => inner_result, Err(_) => Err(ShellError::GenericError { error: "Panic occurred".into(), msg: "".into(), span: Some(span), help: None, inner: vec![], }), } } #[cfg(test)] pub mod test { use super::*; use crate::values::PolarsPluginObject; use nu_plugin_test_support::PluginTest; use nu_protocol::{ShellError, Span, engine::Command}; impl PolarsPlugin { /// Creates a new polars plugin in test mode pub fn new_test_mode() -> Result<Self, ShellError> { Ok(PolarsPlugin { disable_cache_drop: true, ..PolarsPlugin::new()? }) } } struct TestEngineWrapper; impl EngineWrapper for TestEngineWrapper { fn get_env_var(&self, key: &str) -> Option<String> { std::env::var(key).ok() } fn use_color(&self) -> bool { false } fn set_gc_disabled(&self, _disabled: bool) -> Result<(), ShellError> { Ok(()) } } pub fn test_polars_plugin_command(command: &impl PluginCommand) -> Result<(), ShellError> { test_polars_plugin_command_with_decls(command, vec![]) } pub fn test_polars_plugin_command_with_decls( command: &impl PluginCommand, decls: Vec<Box<dyn Command>>, ) -> Result<(), ShellError> { let plugin = PolarsPlugin::new_test_mode()?; let examples = command.examples(); // we need to cache values in the examples for example in &examples { if let Some(ref result) = example.result { // if it's a polars plugin object, try to cache it if let Ok(obj) = PolarsPluginObject::try_from_value(&plugin, result) { let id = obj.id(); plugin .cache .insert(TestEngineWrapper {}, id, obj, Span::test_data()) .unwrap(); } } } let mut plugin_test = PluginTest::new(command.name(), plugin.into())?; for decl in decls { let _ = plugin_test.add_decl(decl)?; } plugin_test.test_examples(&examples) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/main.rs
crates/nu_plugin_polars/src/main.rs
use nu_plugin::{MsgPackSerializer, serve_plugin}; use nu_plugin_polars::PolarsPlugin; fn main() { env_logger::init(); // Set config options via environment variable unsafe { // Extensions are required for certain things like aggregates with object dtypes to work // correctly. It is disabled by default because of unsafe code. // See https://docs.rs/polars/latest/polars/#user-guide for details std::env::set_var("POLARS_ALLOW_EXTENSION", "true"); } match PolarsPlugin::new() { Ok(ref plugin) => serve_plugin(plugin, MsgPackSerializer {}), Err(e) => { eprintln!("{e}"); std::process::exit(1); } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/cache/rm.rs
crates/nu_plugin_polars/src/cache/rm.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Type, Value, }; use uuid::Uuid; use crate::PolarsPlugin; #[derive(Clone)] pub struct CacheRemove; impl PluginCommand for CacheRemove { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars store-rm" } fn description(&self) -> &str { "Removes a stored Dataframe or other object from the plugin cache." } fn signature(&self) -> Signature { Signature::build(self.name()) .rest("keys", SyntaxShape::String, "Keys of objects to remove") .input_output_type(Type::Any, Type::List(Box::new(Type::String))) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Removes a stored ", example: r#"let df = ([[a b];[1 2] [3 4]] | polars into-df); polars store-ls | get key | first | polars store-rm $in"#, result: None, }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, _input: PipelineData, ) -> Result<PipelineData, LabeledError> { let msgs: Vec<Value> = call .rest::<String>(0)? .into_iter() .map(|ref key| remove_cache_entry(plugin, engine, key, call.head)) .collect::<Result<Vec<Value>, ShellError>>()?; Ok(PipelineData::value(Value::list(msgs, call.head), None)) } } fn remove_cache_entry( plugin: &PolarsPlugin, engine: &EngineInterface, key: &str, span: Span, ) -> Result<Value, ShellError> { let key = as_uuid(key, span)?; let msg = plugin .cache .remove(engine, &key, true)? .map(|_| format!("Removed: {key}")) .unwrap_or_else(|| format!("No value found for key: {key}")); Ok(Value::string(msg, span)) } fn as_uuid(s: &str, span: Span) -> Result<Uuid, ShellError> { Uuid::parse_str(s).map_err(|e| ShellError::GenericError { error: format!("Failed to convert key string to UUID: {e}"), msg: "".into(), span: Some(span), help: None, inner: vec![], }) } #[cfg(test)] mod test { use nu_command::{First, Get}; use nu_plugin_test_support::PluginTest; use nu_protocol::Span; use super::*; #[test] fn test_remove() -> Result<(), ShellError> { let plugin = PolarsPlugin::new_test_mode()?.into(); let pipeline_data = PluginTest::new("polars", plugin)? .add_decl(Box::new(First))? .add_decl(Box::new(Get))? .eval("let df = ([[a b];[1 2] [3 4]] | polars into-df); polars store-ls | get key | first | polars store-rm $in")?; let value = pipeline_data.into_value(Span::test_data())?; let msg = value .as_list()? .first() .expect("there should be a first entry") .as_str()?; assert!(msg.contains("Removed")); Ok(()) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/cache/list.rs
crates/nu_plugin_polars/src/cache/list.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, IntoPipelineData, LabeledError, PipelineData, Signature, Value, record, }; use crate::{PolarsPlugin, values::PolarsPluginObject}; #[derive(Clone)] pub struct ListDF; impl PluginCommand for ListDF { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars store-ls" } fn description(&self) -> &str { "Lists stored polars objects." } fn signature(&self) -> Signature { Signature::build(self.name()).category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Creates a new dataframe and shows it in the dataframe list", example: r#"let test = ([[a b];[1 2] [3 4]] | polars into-df); polars store-ls"#, result: None, }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, _input: PipelineData, ) -> Result<PipelineData, LabeledError> { let vals = plugin.cache.process_entries(|(key, value)| { let span_contents = engine.get_span_contents(value.span)?; let span_contents = String::from_utf8_lossy(&span_contents); match &value.value { PolarsPluginObject::NuDataFrame(df) => Ok(Some(Value::record( record! { "key" => Value::string(key.to_string(), call.head), "created" => Value::date(value.created, call.head), "columns" => Value::int(df.as_ref().width() as i64, call.head), "rows" => Value::int(df.as_ref().height() as i64, call.head), "type" => Value::string("DataFrame", call.head), "estimated_size" => Value::filesize(df.to_polars().estimated_size() as i64, call.head), "span_contents" => Value::string(span_contents, value.span), "span_start" => Value::int(value.span.start as i64, call.head), "span_end" => Value::int(value.span.end as i64, call.head), "reference_count" => Value::int(value.reference_count as i64, call.head), }, call.head, ))), PolarsPluginObject::NuLazyFrame(lf) => { let lf = lf.clone().collect(call.head)?; Ok(Some(Value::record( record! { "key" => Value::string(key.to_string(), call.head), "created" => Value::date(value.created, call.head), "columns" => Value::int(lf.as_ref().width() as i64, call.head), "rows" => Value::int(lf.as_ref().height() as i64, call.head), "type" => Value::string("LazyFrame", call.head), "estimated_size" => Value::filesize(lf.to_polars().estimated_size() as i64, call.head), "span_contents" => Value::string(span_contents, value.span), "span_start" => Value::int(value.span.start as i64, call.head), "span_end" => Value::int(value.span.end as i64, call.head), "reference_count" => Value::int(value.reference_count as i64, call.head), }, call.head, ))) } PolarsPluginObject::NuExpression(_) => Ok(Some(Value::record( record! { "key" => Value::string(key.to_string(), call.head), "created" => Value::date(value.created, call.head), "columns" => Value::nothing(call.head), "rows" => Value::nothing(call.head), "type" => Value::string("Expression", call.head), "estimated_size" => Value::nothing(call.head), "span_contents" => Value::string(span_contents, value.span), "span_start" => Value::int(value.span.start as i64, call.head), "span_end" => Value::int(value.span.end as i64, call.head), "reference_count" => Value::int(value.reference_count as i64, call.head), }, call.head, ))), PolarsPluginObject::NuLazyGroupBy(_) => Ok(Some(Value::record( record! { "key" => Value::string(key.to_string(), call.head), "columns" => Value::nothing(call.head), "rows" => Value::nothing(call.head), "type" => Value::string("LazyGroupBy", call.head), "estimated_size" => Value::nothing(call.head), "span_contents" => Value::string(span_contents, call.head), "span_start" => Value::int(call.head.start as i64, call.head), "span_end" => Value::int(call.head.end as i64, call.head), "reference_count" => Value::int(value.reference_count as i64, call.head), }, call.head, ))), PolarsPluginObject::NuWhen(_) => Ok(Some(Value::record( record! { "key" => Value::string(key.to_string(), call.head), "columns" => Value::nothing(call.head), "rows" => Value::nothing(call.head), "type" => Value::string("When", call.head), "estimated_size" => Value::nothing(call.head), "span_contents" => Value::string(span_contents.to_string(), call.head), "span_start" => Value::int(call.head.start as i64, call.head), "span_end" => Value::int(call.head.end as i64, call.head), "reference_count" => Value::int(value.reference_count as i64, call.head), }, call.head, ))), PolarsPluginObject::NuPolarsTestData(_, _) => Ok(Some(Value::record( record! { "key" => Value::string(key.to_string(), call.head), "columns" => Value::nothing(call.head), "rows" => Value::nothing(call.head), "type" => Value::string("When", call.head), "estimated_size" => Value::nothing(call.head), "span_contents" => Value::string(span_contents.to_string(), call.head), "span_start" => Value::int(call.head.start as i64, call.head), "span_end" => Value::int(call.head.end as i64, call.head), "reference_count" => Value::int(value.reference_count as i64, call.head), }, call.head, ))), PolarsPluginObject::NuDataType(_) => Ok(Some(Value::record( record! { "key" => Value::string(key.to_string(), call.head), "created" => Value::date(value.created, call.head), "columns" => Value::nothing(call.head), "rows" => Value::nothing(call.head), "type" => Value::string("DataType", call.head), "estimated_size" => Value::nothing(call.head), "span_contents" => Value::string(span_contents, value.span), "span_start" => Value::int(value.span.start as i64, call.head), "span_end" => Value::int(value.span.end as i64, call.head), "reference_count" => Value::int(value.reference_count as i64, call.head), }, call.head, ))), PolarsPluginObject::NuSchema(_) => Ok(Some(Value::record( record! { "key" => Value::string(key.to_string(), call.head), "created" => Value::date(value.created, call.head), "columns" => Value::nothing(call.head), "rows" => Value::nothing(call.head), "type" => Value::string("Schema", call.head), "estimated_size" => Value::nothing(call.head), "span_contents" => Value::string(span_contents, value.span), "span_start" => Value::int(value.span.start as i64, call.head), "span_end" => Value::int(value.span.end as i64, call.head), "reference_count" => Value::int(value.reference_count as i64, call.head), }, call.head, ))), } })?; let vals = vals.into_iter().flatten().collect(); let list = Value::list(vals, call.head); Ok(list.into_pipeline_data()) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/cache/mod.rs
crates/nu_plugin_polars/src/cache/mod.rs
mod get; mod list; mod rm; use std::{ collections::HashMap, sync::{Mutex, MutexGuard}, }; use chrono::{DateTime, FixedOffset, Local}; pub use list::ListDF; use nu_plugin::{EngineInterface, PluginCommand}; use nu_protocol::{LabeledError, ShellError, Span}; use uuid::Uuid; use crate::{EngineWrapper, PolarsPlugin, values::PolarsPluginObject}; use log::debug; #[derive(Debug, Clone)] pub struct CacheValue { pub uuid: Uuid, pub value: PolarsPluginObject, pub created: DateTime<FixedOffset>, pub span: Span, pub reference_count: i16, } #[derive(Default)] pub struct Cache { cache: Mutex<HashMap<Uuid, CacheValue>>, } impl Cache { fn lock(&self) -> Result<MutexGuard<'_, HashMap<Uuid, CacheValue>>, ShellError> { self.cache.lock().map_err(|e| ShellError::GenericError { error: format!("error acquiring cache lock: {e}"), msg: "".into(), span: None, help: None, inner: vec![], }) } /// Removes an item from the plugin cache. /// /// * `maybe_engine` - Current EngineInterface reference. Required outside of testing /// * `key` - The key of the cache entry to remove. /// * `force` - Delete even if there are multiple references pub fn remove( &self, engine: impl EngineWrapper, key: &Uuid, force: bool, ) -> Result<Option<CacheValue>, ShellError> { let mut lock = self.lock()?; let reference_count = lock.get_mut(key).map(|cache_value| { cache_value.reference_count -= 1; cache_value.reference_count }); let removed = if force || reference_count.unwrap_or_default() < 1 { let removed = lock.remove(key); debug!("PolarsPlugin: removing {key} from cache: {removed:?}"); removed } else { debug!("PolarsPlugin: decrementing reference count for {key}"); None }; if lock.is_empty() { // Once there are no more entries in the cache // we can turn plugin gc back on debug!("PolarsPlugin: Cache is empty enabling GC"); engine.set_gc_disabled(false).map_err(LabeledError::from)?; } drop(lock); Ok(removed) } /// Inserts an item into the plugin cache. /// The maybe_engine parameter is required outside of testing pub fn insert( &self, engine: impl EngineWrapper, uuid: Uuid, value: PolarsPluginObject, span: Span, ) -> Result<Option<CacheValue>, ShellError> { let mut lock = self.lock()?; debug!("PolarsPlugin: Inserting {uuid} into cache: {value:?}"); // turn off plugin gc the first time an entry is added to the cache // as we don't want the plugin to be garbage collected if there // is any live data debug!("PolarsPlugin: Cache has values disabling GC"); engine.set_gc_disabled(true).map_err(LabeledError::from)?; let cache_value = CacheValue { uuid, value, created: Local::now().into(), span, reference_count: 1, }; let result = lock.insert(uuid, cache_value); drop(lock); Ok(result) } pub fn get(&self, uuid: &Uuid, increment: bool) -> Result<Option<CacheValue>, ShellError> { let mut lock = self.lock()?; let result = lock.get_mut(uuid).map(|cv| { if increment { cv.reference_count += 1; } cv.clone() }); drop(lock); Ok(result) } pub fn process_entries<F, T>(&self, mut func: F) -> Result<Vec<T>, ShellError> where F: FnMut((&Uuid, &CacheValue)) -> Result<T, ShellError>, { let lock = self.lock()?; let mut vals: Vec<T> = Vec::new(); for entry in lock.iter() { let val = func(entry)?; vals.push(val); } drop(lock); Ok(vals) } } pub trait Cacheable: Sized + Clone { fn cache_id(&self) -> &Uuid; fn to_cache_value(&self) -> Result<PolarsPluginObject, ShellError>; fn from_cache_value(cv: PolarsPluginObject) -> Result<Self, ShellError>; fn cache( self, plugin: &PolarsPlugin, engine: &EngineInterface, span: Span, ) -> Result<Self, ShellError> { plugin.cache.insert( engine, self.cache_id().to_owned(), self.to_cache_value()?, span, )?; Ok(self) } fn get_cached(plugin: &PolarsPlugin, id: &Uuid) -> Result<Option<Self>, ShellError> { if let Some(cache_value) = plugin.cache.get(id, false)? { Ok(Some(Self::from_cache_value(cache_value.value)?)) } else { Ok(None) } } } pub(crate) fn cache_commands() -> Vec<Box<dyn PluginCommand<Plugin = PolarsPlugin>>> { vec![ Box::new(ListDF), Box::new(rm::CacheRemove), Box::new(get::CacheGet), ] } #[cfg(test)] mod test { use std::{cell::RefCell, rc::Rc}; use super::*; struct MockEngineWrapper { gc_enabled: Rc<RefCell<bool>>, } impl MockEngineWrapper { fn new(gc_enabled: bool) -> Self { Self { gc_enabled: Rc::new(RefCell::new(gc_enabled)), } } fn gc_enabled(&self) -> bool { *self.gc_enabled.borrow() } } impl EngineWrapper for &MockEngineWrapper { fn get_env_var(&self, _key: &str) -> Option<String> { unimplemented!() } fn use_color(&self) -> bool { unimplemented!() } fn set_gc_disabled(&self, disabled: bool) -> Result<(), ShellError> { let _ = self.gc_enabled.replace(!disabled); Ok(()) } } #[test] pub fn test_remove_plugin_cache_enable() { let mock_engine = MockEngineWrapper::new(false); let cache = Cache::default(); let mut lock = cache.cache.lock().expect("should be able to acquire lock"); let key0 = Uuid::new_v4(); lock.insert( key0, CacheValue { uuid: Uuid::new_v4(), value: PolarsPluginObject::NuPolarsTestData(Uuid::new_v4(), "object_0".into()), created: Local::now().into(), span: Span::unknown(), reference_count: 1, }, ); let key1 = Uuid::new_v4(); lock.insert( key1, CacheValue { uuid: Uuid::new_v4(), value: PolarsPluginObject::NuPolarsTestData(Uuid::new_v4(), "object_1".into()), created: Local::now().into(), span: Span::unknown(), reference_count: 1, }, ); drop(lock); let _ = cache .remove(&mock_engine, &key0, false) .expect("should be able to remove key0"); assert!(!mock_engine.gc_enabled()); let _ = cache .remove(&mock_engine, &key1, false) .expect("should be able to remove key1"); assert!(mock_engine.gc_enabled()); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/cache/get.rs
crates/nu_plugin_polars/src/cache/get.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Type, Value, }; use polars::{prelude::NamedFrom, series::Series}; use uuid::Uuid; use crate::{ PolarsPlugin, values::{CustomValueSupport, NuDataFrame, PolarsPluginType}, }; #[derive(Clone)] pub struct CacheGet; impl PluginCommand for CacheGet { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars store-get" } fn description(&self) -> &str { "Gets a Dataframe or other object from the plugin cache." } fn signature(&self) -> Signature { Signature::build(self.name()) .required("key", SyntaxShape::String, "Key of objects to get") .input_output_types( PolarsPluginType::types() .iter() .map(|t| (Type::Any, Type::from(*t))) .collect(), ) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Get a stored object", example: r#"let df = ([[a b];[1 2] [3 4]] | polars into-df); polars store-ls | get key | first | polars store-get $in"#, result: Some( NuDataFrame::try_from_series_vec( vec![ Series::new("a".into(), &[1_i64, 3]), Series::new("b".into(), &[2_i64, 4]), ], Span::test_data(), ) .expect("could not create dataframe") .into_value(Span::test_data()), ), }] } fn run( &self, plugin: &Self::Plugin, _engine: &EngineInterface, call: &EvaluatedCall, _input: PipelineData, ) -> Result<PipelineData, LabeledError> { let key = call .req::<String>(0) .and_then(|ref k| as_uuid(k, call.head))?; let value = if let Some(cache_value) = plugin.cache.get(&key, true)? { let polars_object = cache_value.value; polars_object.into_value(call.head) } else { Value::nothing(call.head) }; Ok(PipelineData::value(value, None)) } } fn as_uuid(s: &str, span: Span) -> Result<Uuid, ShellError> { Uuid::parse_str(s).map_err(|e| ShellError::GenericError { error: format!("Failed to convert key string to UUID: {e}"), msg: "".into(), span: Some(span), help: None, inner: vec![], }) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command_with_decls; use nu_command::{First, Get}; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command_with_decls(&CacheGet, vec![Box::new(Get), Box::new(First)]) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/utils.rs
crates/nu_plugin_polars/src/dataframe/utils.rs
use nu_protocol::{FromValue, ShellError, Value}; pub fn extract_strings(value: Value) -> Result<Vec<String>, ShellError> { let span = value.span(); match ( <String as FromValue>::from_value(value.clone()), <Vec<String> as FromValue>::from_value(value), ) { (Ok(col), Err(_)) => Ok(vec![col]), (Err(_), Ok(cols)) => Ok(cols), _ => Err(ShellError::IncompatibleParametersSingle { msg: "Expected a string or list of strings".into(), span, }), } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/mod.rs
crates/nu_plugin_polars/src/dataframe/mod.rs
use nu_protocol::{ShellError, Span}; pub mod command; mod utils; pub mod values; pub fn missing_flag_error(flag: &str, span: Span) -> ShellError { ShellError::GenericError { error: format!("Missing flag: {flag}"), msg: "".into(), span: Some(span), help: None, inner: vec![], } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/mod.rs
crates/nu_plugin_polars/src/dataframe/command/mod.rs
pub mod aggregation; pub mod boolean; pub mod computation; pub mod core; pub mod data; pub mod datetime; pub mod index; pub mod integer; pub mod list; pub mod string; pub mod stub;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/stub.rs
crates/nu_plugin_polars/src/dataframe/command/stub.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{Category, LabeledError, PipelineData, Signature, Type, Value}; use crate::PolarsPlugin; #[derive(Clone)] pub struct PolarsCmd; impl PluginCommand for PolarsCmd { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars" } fn description(&self) -> &str { "Operate with data in a dataframe format." } fn signature(&self) -> nu_protocol::Signature { Signature::build("polars") .category(Category::Custom("dataframe".into())) .input_output_types(vec![(Type::Nothing, Type::String)]) } fn extra_description(&self) -> &str { r#" You must use one of the subcommands below. Using this command as-is will only produce this help message. The following are the main datatypes (wrapped from Polars) that are used by these subcommands: Lazy and Strict dataframes (called `NuLazyFrame` and `NuDataFrame` in error messages) are the main data structure. Expressions, representing various column operations (called `NuExpression`), are passed to many commands such as `polars filter` or `polars with-column`. Most nushell operators are supported in these expressions, importantly arithmetic, comparison and boolean logical. Groupbys (`NuLazyGroupBy`), the output of a `polars group-by`, represent a grouped dataframe and are typically piped to the `polars agg` command with some column expressions for aggregation which then returns a dataframe. "# } fn run( &self, _plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, _input: PipelineData, ) -> Result<PipelineData, LabeledError> { Ok(PipelineData::value( Value::string(engine.get_help()?, call.head), None, )) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/string/str_replace.rs
crates/nu_plugin_polars/src/dataframe/command/string/str_replace.rs
use crate::{ PolarsPlugin, missing_flag_error, values::{ CustomValueSupport, NuExpression, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; use super::super::super::values::{Column, NuDataFrame}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use polars::prelude::{IntoSeries, StringNameSpaceImpl, lit}; #[derive(Clone)] pub struct StrReplace; impl PluginCommand for StrReplace { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars str-replace" } fn description(&self) -> &str { "Replace the leftmost (sub)string by a regex pattern." } fn signature(&self) -> Signature { Signature::build(self.name()) .required_named( "pattern", SyntaxShape::String, "Regex pattern to be matched", Some('p'), ) .required_named( "replace", SyntaxShape::String, "replacing string", Some('r'), ) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Replaces string in column", example: "[[a]; [abc] [abcabc]] | polars into-df | polars select (polars col a | polars str-replace --pattern ab --replace AB) | polars collect", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "a".to_string(), vec![Value::test_string("ABc"), Value::test_string("ABcabc")], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Replaces string", example: "[abc abc abc] | polars into-df | polars str-replace --pattern ab --replace AB", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "0".to_string(), vec![ Value::test_string("ABc"), Value::test_string("ABc"), Value::test_string("ABc"), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => command_df(plugin, engine, call, df), PolarsPluginObject::NuLazyFrame(lazy) => { command_df(plugin, engine, call, lazy.collect(call.head)?) } PolarsPluginObject::NuExpression(expr) => command_expr(plugin, engine, call, expr), _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } .map_err(LabeledError::from) } } fn command_expr( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, expr: NuExpression, ) -> Result<PipelineData, ShellError> { let pattern: String = call .get_flag("pattern")? .ok_or_else(|| missing_flag_error("pattern", call.head))?; let pattern = lit(pattern); let replace: String = call .get_flag("replace")? .ok_or_else(|| missing_flag_error("replace", call.head))?; let replace = lit(replace); let res: NuExpression = expr .into_polars() .str() .replace(pattern, replace, false) .into(); res.to_pipeline_data(plugin, engine, call.head) } fn command_df( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let pattern: String = call .get_flag("pattern")? .ok_or_else(|| missing_flag_error("pattern", call.head))?; let replace: String = call .get_flag("replace")? .ok_or_else(|| missing_flag_error("replace", call.head))?; let series = df.as_series(call.head)?; let chunked = series.str().map_err(|e| ShellError::GenericError { error: "Error conversion to string".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })?; let mut res = chunked .replace(&pattern, &replace) .map_err(|e| ShellError::GenericError { error: "Error finding pattern other".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })?; res.rename(series.name().to_owned()); let df = NuDataFrame::try_from_series_vec(vec![res.into_series()], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&StrReplace) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/string/to_lowercase.rs
crates/nu_plugin_polars/src/dataframe/command/string/to_lowercase.rs
use crate::{ PolarsPlugin, values::{ CustomValueSupport, NuExpression, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; use super::super::super::values::{Column, NuDataFrame}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Value, }; use polars::prelude::{IntoSeries, StringNameSpaceImpl}; #[derive(Clone)] pub struct ToLowerCase; impl PluginCommand for ToLowerCase { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars lowercase" } fn description(&self) -> &str { "Lowercase the strings in the column." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Modifies strings in a column to lowercase", example: "[[a]; [Abc]] | polars into-df | polars select (polars col a | polars lowercase) | polars collect", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "a".to_string(), vec![Value::test_string("abc")], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Modifies strings to lowercase", example: "[Abc aBc abC] | polars into-df | polars lowercase", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "0".to_string(), vec![ Value::test_string("abc"), Value::test_string("abc"), Value::test_string("abc"), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => command_df(plugin, engine, call, df), PolarsPluginObject::NuLazyFrame(lazy) => { command_df(plugin, engine, call, lazy.collect(call.head)?) } PolarsPluginObject::NuExpression(expr) => command_expr(plugin, engine, call, expr), _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command_expr( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, expr: NuExpression, ) -> Result<PipelineData, ShellError> { let res: NuExpression = expr.into_polars().str().to_lowercase().into(); res.to_pipeline_data(plugin, engine, call.head) } fn command_df( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let series = df.as_series(call.head)?; let casted = series.str().map_err(|e| ShellError::GenericError { error: "Error casting to string".into(), msg: e.to_string(), span: Some(call.head), help: Some("The str-slice command can only be used with string columns".into()), inner: vec![], })?; let mut res = casted.to_lowercase(); res.rename(series.name().to_owned()); let df = NuDataFrame::try_from_series_vec(vec![res.into_series()], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ToLowerCase) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/string/contains.rs
crates/nu_plugin_polars/src/dataframe/command/string/contains.rs
use crate::{ PolarsPlugin, values::{ CustomValueSupport, NuExpression, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; use super::super::super::values::{Column, NuDataFrame}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use polars::prelude::{IntoSeries, StringNameSpaceImpl, lit}; #[derive(Clone)] pub struct Contains; impl PluginCommand for Contains { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars contains" } fn description(&self) -> &str { "Checks if a pattern is contained in a string." } fn signature(&self) -> Signature { Signature::build(self.name()) .required( "pattern", SyntaxShape::String, "Regex pattern to be searched", ) .input_output_types(vec![ ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Returns boolean indicating if pattern was found in a column", example: "let df = [[a]; [abc] [acb] [acb]] | polars into-df; let df2 = $df | polars with-column [(polars col a | polars contains ab | polars as b)] | polars collect; $df2.b", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "b".to_string(), vec![ Value::test_bool(true), Value::test_bool(false), Value::test_bool(false), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Returns boolean indicating if pattern was found", example: "[abc acb acb] | polars into-df | polars contains ab", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "0".to_string(), vec![ Value::test_bool(true), Value::test_bool(false), Value::test_bool(false), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => command_df(plugin, engine, call, df), PolarsPluginObject::NuLazyFrame(lazy) => { let df = lazy.collect(call.head)?; command_df(plugin, engine, call, df) } PolarsPluginObject::NuExpression(expr) => command_expr(plugin, engine, call, expr), _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command_expr( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, expr: NuExpression, ) -> Result<PipelineData, ShellError> { let pattern: String = call.req(0)?; let res: NuExpression = expr .into_polars() .str() .contains(lit(pattern), false) .into(); res.to_pipeline_data(plugin, engine, call.head) } fn command_df( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let pattern: String = call.req(0)?; let series = df.as_series(call.head)?; let chunked = series.str().map_err(|e| ShellError::GenericError { error: "The contains command only with string columns".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })?; let res = chunked .contains(&pattern, false) .map_err(|e| ShellError::GenericError { error: "Error searching in series".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })?; let df = NuDataFrame::try_from_series_vec(vec![res.into_series()], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&Contains) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/string/str_join.rs
crates/nu_plugin_polars/src/dataframe/command/string/str_join.rs
use crate::{ PolarsPlugin, values::{ CustomValueSupport, NuExpression, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; use super::super::super::values::{Column, NuDataFrame}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use polars::{prelude::StringNameSpaceImpl, series::IntoSeries}; #[derive(Clone)] pub struct StrJoin; impl PluginCommand for StrJoin { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars str-join" } fn description(&self) -> &str { "Concatenates strings within a column or dataframes" } fn signature(&self) -> Signature { Signature::build(self.name()) .optional("other", SyntaxShape::Any, "Other dataframe with a single series of strings to be concatenated. Required when used with a dataframe, ignored when used as an expression.") .named("delimiter", SyntaxShape::String, "Delimiter to join strings within an expression. Other dataframe when used with a dataframe.", Some('d')) .switch("ignore-nulls", "Ignore null values. Only available when used as an expression.", Some('n')) .input_output_types(vec![ ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Join strings in a column", example: r#"[[a]; [abc] [abc] [abc]] | polars into-df | polars select (polars col a | polars str-join -d ',') | polars collect"#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "a".to_string(), vec![Value::test_string("abc,abc,abc")], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "StrJoin strings across two series", example: r#"let other = ([za xs cd] | polars into-df); [abc abc abc] | polars into-df | polars str-join $other"#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "0".to_string(), vec![ Value::test_string("abcza"), Value::test_string("abcxs"), Value::test_string("abccd"), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => command_df(plugin, engine, call, df), PolarsPluginObject::NuLazyFrame(lazy) => { command_df(plugin, engine, call, lazy.collect(call.head)?) } PolarsPluginObject::NuExpression(expr) => command_expr(plugin, engine, call, expr), _ => Err(cant_convert_err(&value, &[PolarsPluginType::NuExpression])), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command_expr( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, expr: NuExpression, ) -> Result<PipelineData, ShellError> { let delimiter = call .get_flag::<String>("delimiter")? .map(|x| x.to_string()) .unwrap_or_else(|| "".to_string()); let ignore_nulls = call.has_flag("ignore-nulls")?; let res: NuExpression = expr .into_polars() .str() .join(&delimiter, ignore_nulls) .into(); res.to_pipeline_data(plugin, engine, call.head) } fn command_df( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let other: Value = call.req(0).map_err(|_| ShellError::MissingParameter { param_name: "other".into(), span: call.head, })?; let other_span = other.span(); let other_df = NuDataFrame::try_from_value_coerce(plugin, &other, other_span)?; let other_series = other_df.as_series(other_span)?; let other_chunked = other_series.str().map_err(|e| ShellError::GenericError { error: "The str-join command only works with string columns".into(), msg: e.to_string(), span: Some(other_span), help: None, inner: vec![], })?; let series = df.as_series(call.head)?; let chunked = series.str().map_err(|e| ShellError::GenericError { error: "The str-join command only works only with string columns".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })?; let mut res = chunked.concat(other_chunked); res.rename(series.name().to_owned()); let df = NuDataFrame::try_from_series_vec(vec![res.into_series()], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&StrJoin) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/string/str_replace_all.rs
crates/nu_plugin_polars/src/dataframe/command/string/str_replace_all.rs
use crate::{ PolarsPlugin, missing_flag_error, values::{ CustomValueSupport, NuExpression, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; use super::super::super::values::{Column, NuDataFrame}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use polars::prelude::{IntoSeries, StringNameSpaceImpl, lit}; #[derive(Clone)] pub struct StrReplaceAll; impl PluginCommand for StrReplaceAll { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars str-replace-all" } fn description(&self) -> &str { "Replace all (sub)strings by a regex pattern." } fn signature(&self) -> Signature { Signature::build(self.name()) .required_named( "pattern", SyntaxShape::String, "Regex pattern to be matched", Some('p'), ) .required_named( "replace", SyntaxShape::String, "replacing string", Some('r'), ) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Replaces string in a column", example: "[[a]; [abac] [abac] [abac]] | polars into-df | polars select (polars col a | polars str-replace-all --pattern a --replace A) | polars collect", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "a".to_string(), vec![ Value::test_string("AbAc"), Value::test_string("AbAc"), Value::test_string("AbAc"), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Replaces string", example: "[abac abac abac] | polars into-df | polars str-replace-all --pattern a --replace A", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "0".to_string(), vec![ Value::test_string("AbAc"), Value::test_string("AbAc"), Value::test_string("AbAc"), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => command_df(plugin, engine, call, df), PolarsPluginObject::NuLazyFrame(lazy) => { command_df(plugin, engine, call, lazy.collect(call.head)?) } PolarsPluginObject::NuExpression(expr) => command_expr(plugin, engine, call, expr), _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } .map_err(LabeledError::from) } } fn command_expr( plugin: &PolarsPlugin, engine_state: &EngineInterface, call: &EvaluatedCall, expr: NuExpression, ) -> Result<PipelineData, ShellError> { let pattern: String = call .get_flag("pattern")? .ok_or_else(|| missing_flag_error("pattern", call.head))?; let pattern = lit(pattern); let replace: String = call .get_flag("replace")? .ok_or_else(|| missing_flag_error("replace", call.head))?; let replace = lit(replace); let res: NuExpression = expr .into_polars() .str() .replace_all(pattern, replace, false) .into(); res.to_pipeline_data(plugin, engine_state, call.head) } fn command_df( plugin: &PolarsPlugin, engine_state: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let pattern: String = call .get_flag("pattern")? .ok_or_else(|| missing_flag_error("pattern", call.head))?; let replace: String = call .get_flag("replace")? .ok_or_else(|| missing_flag_error("replace", call.head))?; let series = df.as_series(call.head)?; let chunked = series.str().map_err(|e| ShellError::GenericError { error: "Error conversion to string".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })?; let mut res = chunked .replace_all(&pattern, &replace) .map_err(|e| ShellError::GenericError { error: "Error finding pattern other".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })?; res.rename(series.name().to_owned()); let df = NuDataFrame::try_from_series_vec(vec![res.into_series()], call.head)?; df.to_pipeline_data(plugin, engine_state, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&StrReplaceAll) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/string/mod.rs
crates/nu_plugin_polars/src/dataframe/command/string/mod.rs
mod concat_str; mod contains; mod str_join; mod str_lengths; mod str_replace; mod str_replace_all; mod str_slice; mod str_split; mod str_strip_chars; mod to_lowercase; mod to_uppercase; use crate::PolarsPlugin; use nu_plugin::PluginCommand; pub use concat_str::ExprConcatStr; pub use contains::Contains; pub use str_join::StrJoin; pub use str_lengths::StrLengths; pub use str_replace::StrReplace; pub use str_replace_all::StrReplaceAll; pub use str_slice::StrSlice; pub use to_lowercase::ToLowerCase; pub use to_uppercase::ToUpperCase; pub(crate) fn string_commands() -> Vec<Box<dyn PluginCommand<Plugin = PolarsPlugin>>> { vec![ Box::new(ExprConcatStr), Box::new(Contains), Box::new(StrReplace), Box::new(StrReplaceAll), Box::new(str_split::StrSplit), Box::new(str_strip_chars::StrStripChars), Box::new(StrJoin), Box::new(StrLengths), Box::new(StrSlice), Box::new(ToLowerCase), Box::new(ToUpperCase), ] }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/string/str_lengths.rs
crates/nu_plugin_polars/src/dataframe/command/string/str_lengths.rs
use crate::{ PolarsPlugin, values::{ CustomValueSupport, NuExpression, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; use super::super::super::values::{Column, NuDataFrame}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Value, }; use polars::prelude::{IntoSeries, StringNameSpaceImpl}; #[derive(Clone)] pub struct StrLengths; impl PluginCommand for StrLengths { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars str-lengths" } fn description(&self) -> &str { "Get lengths of all strings." } fn signature(&self) -> Signature { Signature::build(self.name()) .switch( "bytes", "Get the length in bytes instead of chars.", Some('b'), ) .input_output_types(vec![ ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Returns string lengths for a column", example: "[[a]; [a] [ab] [abc]] | polars into-df | polars select (polars col a | polars str-lengths) | polars collect", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "a".to_string(), vec![Value::test_int(1), Value::test_int(2), Value::test_int(3)], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Returns string lengths", example: "[a ab abc] | polars into-df | polars str-lengths", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "0".to_string(), vec![Value::test_int(1), Value::test_int(2), Value::test_int(3)], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => command_df(plugin, engine, call, df), PolarsPluginObject::NuLazyFrame(lazy) => { command_df(plugin, engine, call, lazy.collect(call.head)?) } PolarsPluginObject::NuExpression(expr) => command_expr(plugin, engine, call, expr), _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command_expr( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, expr: NuExpression, ) -> Result<PipelineData, ShellError> { let res: NuExpression = if call.has_flag("bytes")? { expr.into_polars().str().len_bytes().into() } else { expr.into_polars().str().len_chars().into() }; res.to_pipeline_data(plugin, engine, call.head) } fn command_df( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let series = df.as_series(call.head)?; let chunked = series.str().map_err(|e| ShellError::GenericError { error: "Error casting to string".into(), msg: e.to_string(), span: Some(call.head), help: Some("The str-lengths command can only be used with string columns".into()), inner: vec![], })?; let res = if call.has_flag("bytes")? { chunked.as_ref().str_len_bytes().into_series() } else { chunked.as_ref().str_len_chars().into_series() }; let df = NuDataFrame::try_from_series_vec(vec![res], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&StrLengths) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/string/concat_str.rs
crates/nu_plugin_polars/src/dataframe/command/string/concat_str.rs
use crate::{ PolarsPlugin, dataframe::values::{Column, NuDataFrame, NuExpression}, values::{CustomValueSupport, PolarsPluginType}, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, Signature, Span, SyntaxShape, Type, Value, }; use polars::prelude::concat_str; #[derive(Clone)] pub struct ExprConcatStr; impl PluginCommand for ExprConcatStr { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars concat-str" } fn description(&self) -> &str { "Creates a concat string expression." } fn signature(&self) -> Signature { Signature::build(self.name()) .required( "separator", SyntaxShape::String, "Separator used during the concatenation", ) .required( "concat expressions", SyntaxShape::List(Box::new(SyntaxShape::Any)), "Expression(s) that define the string concatenation", ) .input_output_type(Type::Any, PolarsPluginType::NuExpression.into()) .category(Category::Custom("expression".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Creates a concat string expression", example: r#"let df = ([[a b c]; [one two 1] [three four 2]] | polars into-df); $df | polars with-column ((polars concat-str "-" [(polars col a) (polars col b) ((polars col c) * 2)]) | polars as concat)"#, result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "a".to_string(), vec![Value::test_string("one"), Value::test_string("three")], ), Column::new( "b".to_string(), vec![Value::test_string("two"), Value::test_string("four")], ), Column::new( "c".to_string(), vec![Value::test_int(1), Value::test_int(2)], ), Column::new( "concat".to_string(), vec![ Value::test_string("one-two-2"), Value::test_string("three-four-4"), ], ), ], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }] } fn search_terms(&self) -> Vec<&str> { vec!["join", "connect", "update"] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let separator: String = call.req(0)?; let value: Value = call.req(1)?; let expressions = NuExpression::extract_exprs(plugin, value)?; let expr: NuExpression = concat_str(expressions, &separator, false).into(); expr.to_pipeline_data(plugin, engine, call.head) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } #[cfg(test)] mod test { use crate::test::test_polars_plugin_command; use super::*; #[test] fn test_examples() -> Result<(), nu_protocol::ShellError> { test_polars_plugin_command(&ExprConcatStr) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/string/str_slice.rs
crates/nu_plugin_polars/src/dataframe/command/string/str_slice.rs
use crate::{ PolarsPlugin, values::{ CustomValueSupport, NuExpression, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; use super::super::super::values::{Column, NuDataFrame}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use polars::{ prelude::{Expr, IntoSeries, NamedFrom, Null, StringNameSpaceImpl, lit}, series::Series, }; #[derive(Clone)] pub struct StrSlice; impl PluginCommand for StrSlice { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars str-slice" } fn description(&self) -> &str { "Slices the string from the start position until the selected length." } fn signature(&self) -> Signature { Signature::build(self.name()) .required("start", SyntaxShape::Int, "start of slice") .named("length", SyntaxShape::Int, "optional length", Some('l')) .input_output_types(vec![ ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Creates slices from the strings in a specified column", example: "[[a]; [abcded] [abc321] [abc123]] | polars into-df | polars select (polars col a | polars str-slice 1 --length 2) | polars collect", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "a".to_string(), vec![ Value::test_string("bc"), Value::test_string("bc"), Value::test_string("bc"), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Creates slices from the strings", example: "[abcded abc321 abc123] | polars into-df | polars str-slice 1 --length 2", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "0".to_string(), vec![ Value::test_string("bc"), Value::test_string("bc"), Value::test_string("bc"), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Creates slices from the strings without length", example: "[abcded abc321 abc123] | polars into-df | polars str-slice 1", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "0".to_string(), vec![ Value::test_string("bcded"), Value::test_string("bc321"), Value::test_string("bc123"), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => command_df(plugin, engine, call, df), PolarsPluginObject::NuLazyFrame(lazy) => { command_df(plugin, engine, call, lazy.collect(call.head)?) } PolarsPluginObject::NuExpression(expr) => command_expr(plugin, engine, call, expr), _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command_expr( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, expr: NuExpression, ) -> Result<PipelineData, ShellError> { let start = lit(call.req::<i64>(0)?); let length: Expr = call .get_flag::<i64>("length")? .map(lit) .unwrap_or(lit(Null {})); let res: NuExpression = expr.into_polars().str().slice(start, length).into(); res.to_pipeline_data(plugin, engine, call.head) } fn command_df( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let start: i64 = call.req(0)?; let start = Series::new("".into(), &[start]).into(); let length: Option<i64> = call.get_flag("length")?; let length = match length { Some(v) => Series::new("".into(), &[v as u64]), None => Series::new_null("".into(), 1), } .into(); let series = df.as_series(call.head)?; let chunked = series.str().map_err(|e| ShellError::GenericError { error: "Error casting to string".into(), msg: e.to_string(), span: Some(call.head), help: Some("The str-slice command can only be used with string columns".into()), inner: vec![], })?; let res = chunked .str_slice(&start, &length) .map_err(|e| ShellError::GenericError { error: "Dataframe Error".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })? .with_name(series.name().to_owned()); let df = NuDataFrame::try_from_series_vec(vec![res.into_series()], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&StrSlice) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/string/str_split.rs
crates/nu_plugin_polars/src/dataframe/command/string/str_split.rs
use crate::{ PolarsPlugin, values::{CustomValueSupport, NuDataFrame, NuExpression, PolarsPluginType}, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, Signature, Span, Spanned, SyntaxShape, Value, }; use polars::df; #[derive(Clone)] pub struct StrSplit; impl PluginCommand for StrSplit { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars str-split" } fn description(&self) -> &str { "Split the string by a substring. The resulting dtype is list<str>." } fn signature(&self) -> Signature { Signature::build(self.name()) .required("expr", SyntaxShape::Any, "Separator expression") .input_output_types(vec![( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), )]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Split the string by comma, then create a new row for each string", example: r#"[[a]; ["one,two,three"]] | polars into-df | polars select (polars col a | polars str-split "," | polars explode) | polars collect"#, result: Some( NuDataFrame::from( df!( "a" => ["one", "two", "three"] ) .expect("Should be able to create a dataframe"), ) .into_value(Span::test_data()), ), }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let separator = call.req::<Spanned<Value>>(0).and_then(|sep| { let sep_expr = NuExpression::try_from_value(plugin, &sep.item)?; Ok(Spanned { item: sep_expr, span: sep.span, }) })?; let expr = NuExpression::try_from_pipeline(plugin, input, call.head)?; let res: NuExpression = expr .into_polars() .str() .split(separator.item.into_polars()) .into(); res.to_pipeline_data(plugin, engine, call.head) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } #[cfg(test)] mod test { use nu_protocol::ShellError; use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&StrSplit) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/string/str_strip_chars.rs
crates/nu_plugin_polars/src/dataframe/command/string/str_strip_chars.rs
use crate::{ PolarsPlugin, values::{ CustomValueSupport, NuExpression, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; use super::super::super::values::{Column, NuDataFrame}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use polars::prelude::Expr; #[derive(Clone)] pub struct StrStripChars; impl PluginCommand for StrStripChars { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars str-strip-chars" } fn description(&self) -> &str { "Strips specified characters from strings in a column" } fn signature(&self) -> Signature { Signature::build(self.name()) .required( "pattern", SyntaxShape::Any, "Characters to strip as either a string or polars expression", ) .switch("start", "Strip from start of strings only", Some('s')) .switch("end", "Strip from end of strings only", Some('e')) .input_output_types(vec![( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), )]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Strip characters from both ends of strings in a column", example: r#"[[text]; ["!!!hello!!!"] ["!!!world!!!"] ["!!!test!!!"]] | polars into-df | polars select (polars col text | polars str-strip-chars "!") | polars collect"#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "text".to_string(), vec![ Value::test_string("hello"), Value::test_string("world"), Value::test_string("test"), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Strip characters from both ends of strings in a column using an expression", example: r#"[[text]; ["!!!hello!!!"] ["!!!world!!!"] ["!!!test!!!"]] | polars into-df | polars select (polars col text | polars str-strip-chars (polars lit "!")) | polars collect"#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "text".to_string(), vec![ Value::test_string("hello"), Value::test_string("world"), Value::test_string("test"), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Strip characters from end of strings in a column", example: r#"[[text]; ["hello!!!"] ["world!!!"] ["test!!!"]] | polars into-df | polars select (polars col text | polars str-strip-chars --end "!") | polars collect"#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "text".to_string(), vec![ Value::test_string("hello"), Value::test_string("world"), Value::test_string("test"), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Strip characters from start of strings in a column", example: r#"[[text]; ["!!!hello"] ["!!!world"] ["!!!test"]] | polars into-df | polars select (polars col text | polars str-strip-chars --start "!") | polars collect"#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "text".to_string(), vec![ Value::test_string("hello"), Value::test_string("world"), Value::test_string("test"), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuExpression(expr) => command_expr(plugin, engine, call, expr), _ => Err(cant_convert_err(&value, &[PolarsPluginType::NuExpression])), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command_expr( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, expr: NuExpression, ) -> Result<PipelineData, ShellError> { let pattern_expr: Expr = call .req::<Value>(0) .and_then(|ref v| NuExpression::try_from_value(plugin, v)) .or(call .req::<String>(0) .map(polars::prelude::lit) .map(NuExpression::from))? .into_polars(); let strip_start = call.has_flag("start")?; let strip_end = call.has_flag("end")?; let res: NuExpression = if strip_start { // Use strip_chars_start when --start flag is provided expr.into_polars() .str() .strip_chars_start(pattern_expr) .into() } else if strip_end { // Use strip_chars_end when --end flag is provided expr.into_polars() .str() .strip_chars_end(pattern_expr) .into() } else { // Use strip_chars when no flags are provided (both ends) expr.into_polars().str().strip_chars(pattern_expr).into() }; res.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&StrStripChars) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/string/to_uppercase.rs
crates/nu_plugin_polars/src/dataframe/command/string/to_uppercase.rs
use crate::{ PolarsPlugin, values::{ CustomValueSupport, NuExpression, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; use super::super::super::values::{Column, NuDataFrame}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Value, }; use polars::prelude::{IntoSeries, StringNameSpaceImpl}; #[derive(Clone)] pub struct ToUpperCase; impl PluginCommand for ToUpperCase { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars uppercase" } fn description(&self) -> &str { "Uppercase the strings in the column." } fn search_terms(&self) -> Vec<&str> { vec!["capitalize", "caps", "capital"] } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Modifies strings in a column to uppercase", example: "[[a]; [Abc]] | polars into-df | polars select (polars col a | polars uppercase) | polars collect", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "a".to_string(), vec![Value::test_string("ABC")], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Modifies strings to uppercase", example: "[Abc aBc abC] | polars into-df | polars uppercase", result: Some( NuDataFrame::try_from_columns( vec![Column::new( "0".to_string(), vec![ Value::test_string("ABC"), Value::test_string("ABC"), Value::test_string("ABC"), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => command_df(plugin, engine, call, df), PolarsPluginObject::NuLazyFrame(lazy) => { command_df(plugin, engine, call, lazy.collect(call.head)?) } PolarsPluginObject::NuExpression(expr) => command_expr(plugin, engine, call, expr), _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command_expr( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, expr: NuExpression, ) -> Result<PipelineData, ShellError> { let res: NuExpression = expr.into_polars().str().to_uppercase().into(); res.to_pipeline_data(plugin, engine, call.head) } fn command_df( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let series = df.as_series(call.head)?; let casted = series.str().map_err(|e| ShellError::GenericError { error: "Error casting to string".into(), msg: e.to_string(), span: Some(call.head), help: Some("The str-slice command can only be used with string columns".into()), inner: vec![], })?; let mut res = casted.to_uppercase(); res.rename(series.name().clone()); let df = NuDataFrame::try_from_series_vec(vec![res.into_series()], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ToUpperCase) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/datetime/get_ordinal.rs
crates/nu_plugin_polars/src/dataframe/command/datetime/get_ordinal.rs
use crate::{ PolarsPlugin, values::{ CustomValueSupport, NuDataFrame, NuExpression, NuLazyFrame, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{Category, Example, LabeledError, PipelineData, ShellError, Signature, Span}; use polars::{ prelude::{DatetimeMethods, IntoSeries, NamedFrom, col}, series::Series, }; #[derive(Clone)] pub struct GetOrdinal; impl PluginCommand for GetOrdinal { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars get-ordinal" } fn description(&self) -> &str { "Gets ordinal from date." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Returns ordinal from a date", example: r#"let dt = ('2020-08-04T16:39:18+00:00' | into datetime --timezone 'UTC'); let df = ([$dt $dt] | polars into-df); $df | polars get-ordinal"#, result: Some( NuDataFrame::try_from_series( Series::new("0".into(), &[217i16, 217]), Span::test_data(), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Returns ordinal from a date in an expression", example: r#"let dt = ('2020-08-04T16:39:18+00:00' | into datetime --timezone 'UTC'); let df = ([$dt $dt] | polars into-df); $df | polars select (polars col 0 | polars get-ordinal)"#, result: Some( NuDataFrame::try_from_series( Series::new("0".into(), &[217i16, 217]), Span::test_data(), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuLazyFrame(lazy) => command_lazy(plugin, engine, call, lazy), PolarsPluginObject::NuDataFrame(df) => command_eager(plugin, engine, call, df), PolarsPluginObject::NuExpression(expr) => { let res: NuExpression = expr.into_polars().dt().ordinal_day().into(); res.to_pipeline_data(plugin, engine, call.head) } _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, ) -> Result<PipelineData, ShellError> { NuLazyFrame::new( false, lazy.to_polars().select([col("*").dt().ordinal_day()]), ) .to_pipeline_data(plugin, engine, call.head) } fn command_eager( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let series = df.as_series(call.head)?; let casted = series.datetime().map_err(|e| ShellError::GenericError { error: "Error casting to datetime type".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })?; let res = casted.ordinal().into_series(); let df = NuDataFrame::try_from_series_vec(vec![res], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command_with_decls; use nu_command::IntoDatetime; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command_with_decls(&GetOrdinal, vec![Box::new(IntoDatetime)]) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/datetime/strftime.rs
crates/nu_plugin_polars/src/dataframe/command/datetime/strftime.rs
use crate::{ PolarsPlugin, values::{ CustomValueSupport, NuExpression, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; use super::super::super::values::{Column, NuDataFrame}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use polars::prelude::IntoSeries; #[derive(Clone)] pub struct StrFTime; impl PluginCommand for StrFTime { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars strftime" } fn description(&self) -> &str { "Formats date based on string rule." } fn signature(&self) -> Signature { Signature::build(self.name()) .required("fmt", SyntaxShape::String, "Format rule") .input_output_types(vec![ ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Formats date column as a string", example: r#"let date = '2020-08-04T16:39:18+00:00' | into datetime --timezone 'UTC'; let df = ([[a]; [$date]] | polars into-df); let df2 = $df | polars with-column [(polars col a | polars strftime "%Y/%m/%d" | polars as b)] | polars collect; $df2.b"#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "b".to_string(), vec![Value::test_string("2020/08/04")], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Formats date", example: r#"let dt = ('2020-08-04T16:39:18+00:00' | into datetime --timezone 'UTC'); let df = ([$dt $dt] | polars into-df); $df | polars strftime "%Y/%m/%d""#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "0".to_string(), vec![ Value::test_string("2020/08/04"), Value::test_string("2020/08/04"), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuDataFrame(df) => command_df(plugin, engine, call, df), PolarsPluginObject::NuLazyFrame(lazy) => { command_df(plugin, engine, call, lazy.collect(call.head)?) } PolarsPluginObject::NuExpression(expr) => command_expr(plugin, engine, call, expr), _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command_expr( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, expr: NuExpression, ) -> Result<PipelineData, ShellError> { let fmt: String = call.req(0)?; let res: NuExpression = expr.into_polars().dt().strftime(&fmt).into(); res.to_pipeline_data(plugin, engine, call.head) } fn command_df( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let fmt: String = call.req(0)?; let series = df.as_series(call.head)?; let casted = series.datetime().map_err(|e| ShellError::GenericError { error: "Error casting to date".into(), msg: e.to_string(), span: Some(call.head), help: Some("The str-slice command can only be used with string columns".into()), inner: vec![], })?; let res = casted .strftime(&fmt) .map_err(|e| ShellError::GenericError { error: "Error formatting datetime".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })? .into_series(); let df = NuDataFrame::try_from_series_vec(vec![res.into_series()], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command_with_decls; use nu_command::IntoDatetime; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command_with_decls(&StrFTime, vec![Box::new(IntoDatetime)]) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/datetime/get_minute.rs
crates/nu_plugin_polars/src/dataframe/command/datetime/get_minute.rs
use crate::{ PolarsPlugin, values::{ CustomValueSupport, NuDataFrame, NuExpression, NuLazyFrame, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{Category, Example, LabeledError, PipelineData, ShellError, Signature, Span}; use polars::{ prelude::{DatetimeMethods, IntoSeries, NamedFrom, col}, series::Series, }; #[derive(Clone)] pub struct GetMinute; impl PluginCommand for GetMinute { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars get-minute" } fn description(&self) -> &str { "Gets minute from date." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Returns minute from a date", example: r#"let dt = ('2020-08-04T16:39:18+00:00' | into datetime --timezone 'UTC'); let df = ([$dt $dt] | polars into-df); $df | polars get-minute"#, result: Some( NuDataFrame::try_from_series( Series::new("0".into(), &[39i8, 39]), Span::test_data(), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Returns minute from a date", example: r#"let dt = ('2020-08-04T16:39:18+00:00' | into datetime --timezone 'UTC'); let df = ([$dt $dt] | polars into-df); $df | polars select (polars col 0 | polars get-minute)"#, result: Some( NuDataFrame::try_from_series( Series::new("0".into(), &[39i8, 39]), Span::test_data(), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuLazyFrame(lazy) => command_lazy(plugin, engine, call, lazy), PolarsPluginObject::NuDataFrame(df) => command_eager(plugin, engine, call, df), PolarsPluginObject::NuExpression(expr) => { let res: NuExpression = expr.into_polars().dt().minute().into(); res.to_pipeline_data(plugin, engine, call.head) } _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, ) -> Result<PipelineData, ShellError> { NuLazyFrame::new(false, lazy.to_polars().select([col("*").dt().minute()])) .to_pipeline_data(plugin, engine, call.head) } fn command_eager( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let series = df.as_series(call.head)?; let casted = series.datetime().map_err(|e| ShellError::GenericError { error: "Error casting to datetime type".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })?; let res = casted.minute().into_series(); let df = NuDataFrame::try_from_series_vec(vec![res], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command_with_decls; use nu_command::IntoDatetime; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command_with_decls(&GetMinute, vec![Box::new(IntoDatetime)]) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/datetime/as_date.rs
crates/nu_plugin_polars/src/dataframe/command/datetime/as_date.rs
use crate::{ PolarsPlugin, values::{ Column, CustomValueSupport, NuDataFrame, NuExpression, NuLazyFrame, NuSchema, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; use chrono::DateTime; use std::sync::Arc; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, record, }; use polars::prelude::{DataType, Field, IntoSeries, Schema, StringMethods, StrptimeOptions, col}; #[derive(Clone)] pub struct AsDate; impl PluginCommand for AsDate { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars as-date" } fn description(&self) -> &str { r#"Converts string to date."# } fn extra_description(&self) -> &str { r#"Format example: "%Y-%m-%d" => 2021-12-31 "%d-%m-%Y" => 31-12-2021 "%Y%m%d" => 2021319 (2021-03-19)"# } fn signature(&self) -> Signature { Signature::build(self.name()) .required("format", SyntaxShape::String, "formatting date string") .switch("not-exact", "the format string may be contained in the date (e.g. foo-2021-01-01-bar could match 2021-01-01)", Some('n')) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Converts string to date", example: r#"["2021-12-30" "2021-12-31"] | polars into-df | polars as-date "%Y-%m-%d""#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "date".to_string(), vec![ // Nushell's Value::date only maps to DataType::Datetime and not DataType::Date // We therefore force the type to be DataType::Date in the schema Value::date( DateTime::parse_from_str( "2021-12-30 00:00:00 +0000", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), Value::date( DateTime::parse_from_str( "2021-12-31 00:00:00 +0000", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), ], )], Some(NuSchema::new(Arc::new(Schema::from_iter(vec![ Field::new("date".into(), DataType::Date), ])))), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Converts string to date", example: r#"["2021-12-30" "2021-12-31 21:00:00"] | polars into-df | polars as-date "%Y-%m-%d" --not-exact"#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "date".to_string(), vec![ // Nushell's Value::date only maps to DataType::Datetime and not DataType::Date // We therefore force the type to be DataType::Date in the schema Value::date( DateTime::parse_from_str( "2021-12-30 00:00:00 +0000", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), Value::date( DateTime::parse_from_str( "2021-12-31 00:00:00 +0000", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), ], )], Some(NuSchema::new(Arc::new(Schema::from_iter(vec![ Field::new("date".into(), DataType::Date), ])))), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Converts string to date in an expression", example: r#"["2021-12-30" "2021-12-31 21:00:00"] | polars into-lazy | polars select (polars col 0 | polars as-date "%Y-%m-%d" --not-exact)"#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "date".to_string(), vec![ // Nushell's Value::date only maps to DataType::Datetime and not DataType::Date // We therefore force the type to be DataType::Date in the schema Value::date( DateTime::parse_from_str( "2021-12-30 00:00:00 +0000", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), Value::date( DateTime::parse_from_str( "2021-12-31 00:00:00 +0000", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), ], )], Some(NuSchema::new(Arc::new(Schema::from_iter(vec![ Field::new("date".into(), DataType::Date), ])))), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Output is of date type", example: r#"["2021-12-30" "2021-12-31 21:00:00"] | polars into-df | polars as-date "%Y-%m-%d" --not-exact | polars schema"#, result: Some(Value::record( record! { "date" => Value::string("date", Span::test_data()), }, Span::test_data(), )), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let format: String = call.req(0)?; let not_exact = call.has_flag("not-exact")?; let value = input.into_value(call.head)?; let options = StrptimeOptions { format: Some(format.into()), strict: true, exact: !not_exact, cache: Default::default(), }; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuLazyFrame(lazy) => command_lazy(plugin, engine, call, lazy, options), PolarsPluginObject::NuDataFrame(df) => command_eager(plugin, engine, call, df, options), PolarsPluginObject::NuExpression(expr) => { let res: NuExpression = expr.into_polars().str().to_date(options).into(); res.to_pipeline_data(plugin, engine, call.head) } _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, options: StrptimeOptions, ) -> Result<PipelineData, ShellError> { NuLazyFrame::new( false, lazy.to_polars().select([col("*").str().to_date(options)]), ) .to_pipeline_data(plugin, engine, call.head) } fn command_eager( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, options: StrptimeOptions, ) -> Result<PipelineData, ShellError> { let format = if let Some(format) = options.format { format.to_string() } else { unreachable!("`format` will never be None") }; let not_exact = !options.exact; let series = df.as_series(call.head)?; let casted = series.str().map_err(|e| ShellError::GenericError { error: "Error casting to string".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })?; let res = if not_exact { casted.as_date_not_exact(Some(format.as_str())) } else { casted.as_date(Some(format.as_str()), false) }; let mut res = res .map_err(|e| ShellError::GenericError { error: "Error creating datetime".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })? .into_series(); res.rename("date".into()); let df = NuDataFrame::try_from_series_vec(vec![res], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&AsDate) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/datetime/get_week.rs
crates/nu_plugin_polars/src/dataframe/command/datetime/get_week.rs
use crate::{ PolarsPlugin, values::{ CustomValueSupport, NuDataFrame, NuExpression, NuLazyFrame, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{Category, Example, LabeledError, PipelineData, ShellError, Signature, Span}; use polars::{ prelude::{DatetimeMethods, IntoSeries, NamedFrom, col}, series::Series, }; #[derive(Clone)] pub struct GetWeek; impl PluginCommand for GetWeek { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars get-week" } fn description(&self) -> &str { "Gets week from date." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Returns week from a date", example: r#"let dt = ('2020-08-04T16:39:18+00:00' | into datetime --timezone 'UTC'); let df = ([$dt $dt] | polars into-df); $df | polars get-week"#, result: Some( NuDataFrame::try_from_series( Series::new("0".into(), &[32i8, 32]), Span::test_data(), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Returns week from a date in an expression", example: r#"let dt = ('2020-08-04T16:39:18+00:00' | into datetime --timezone 'UTC'); let df = ([$dt $dt] | polars into-df); $df | polars select (polars col 0 | polars get-week)"#, result: Some( NuDataFrame::try_from_series( Series::new("0".into(), &[32i8, 32]), Span::test_data(), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuLazyFrame(lazy) => command_lazy(plugin, engine, call, lazy), PolarsPluginObject::NuDataFrame(df) => command_eager(plugin, engine, call, df), PolarsPluginObject::NuExpression(expr) => { let res: NuExpression = expr.into_polars().dt().week().into(); res.to_pipeline_data(plugin, engine, call.head) } _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, ) -> Result<PipelineData, ShellError> { NuLazyFrame::new(false, lazy.to_polars().select([col("*").dt().week()])) .to_pipeline_data(plugin, engine, call.head) } fn command_eager( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let series = df.as_series(call.head)?; let casted = series.datetime().map_err(|e| ShellError::GenericError { error: "Error casting to datetime type".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })?; let res = casted.week().into_series(); let df = NuDataFrame::try_from_series_vec(vec![res], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command_with_decls; use nu_command::IntoDatetime; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command_with_decls(&GetWeek, vec![Box::new(IntoDatetime)]) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/datetime/as_datetime.rs
crates/nu_plugin_polars/src/dataframe/command/datetime/as_datetime.rs
use crate::{ PolarsPlugin, command::datetime::timezone_from_str, dataframe::values::str_to_time_unit, values::{ Column, CustomValueSupport, NuDataFrame, NuExpression, NuLazyFrame, NuSchema, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; use chrono::DateTime; use polars_plan::plans::DynLiteralValue; use std::sync::Arc; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Spanned, SyntaxShape, Value, }; use polars::prelude::{ DataType, Expr, Field, IntoSeries, LiteralValue, PlSmallStr, Schema, StringMethods, StrptimeOptions, TimeUnit, TimeZone, col, }; #[derive(Clone)] pub struct AsDateTime; impl PluginCommand for AsDateTime { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars as-datetime" } fn description(&self) -> &str { r#"Converts string to datetime."# } fn extra_description(&self) -> &str { r#"Format example: "%y/%m/%d %H:%M:%S" => 21/12/31 12:54:98 "%y-%m-%d %H:%M:%S" => 2021-12-31 24:58:01 "%y/%m/%d %H:%M:%S" => 21/12/31 24:58:01 "%y%m%d %H:%M:%S" => 210319 23:58:50 "%Y/%m/%d %H:%M:%S" => 2021/12/31 12:54:98 "%Y-%m-%d %H:%M:%S" => 2021-12-31 24:58:01 "%Y/%m/%d %H:%M:%S" => 2021/12/31 24:58:01 "%Y%m%d %H:%M:%S" => 20210319 23:58:50 "%FT%H:%M:%S" => 2019-04-18T02:45:55 "%FT%H:%M:%S.%6f" => microseconds "%FT%H:%M:%S.%9f" => nanoseconds"# } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ]) .required("format", SyntaxShape::String, "formatting date time string") .switch("not-exact", "the format string may be contained in the date (e.g. foo-2021-01-01-bar could match 2021-01-01)", Some('n')) .switch("naive", "the input datetimes should be parsed as naive (i.e., not timezone-aware). Ignored if input is an expression.", None) .named( "ambiguous", SyntaxShape::OneOf(vec![SyntaxShape::String, SyntaxShape::Nothing]), r#"Determine how to deal with ambiguous datetimes: `raise` (default): raise error `earliest`: use the earliest datetime `latest`: use the latest datetime `null`: set to null Used only when input is a lazyframe or expression and ignored otherwise"#, Some('a'), ) .category(Category::Custom("dataframe".into())) .named("time-unit", SyntaxShape::String, "time unit for the output datetime. One of: ns, us, ms. Default is ns", None) .named("time-zone", SyntaxShape::String, "time zone for the output datetime. E.g. 'UTC', 'America/New_York'", None) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Converts string to datetime", example: r#"["2021-12-30 00:00:00 -0400" "2021-12-31 00:00:00 -0400"] | polars into-df | polars as-datetime "%Y-%m-%d %H:%M:%S %z""#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "datetime".to_string(), vec![ Value::date( DateTime::parse_from_str( "2021-12-30 00:00:00 -0400", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), Value::date( DateTime::parse_from_str( "2021-12-31 00:00:00 -0400", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), ], )], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Converts string to datetime with high resolutions", example: r#"["2021-12-30 00:00:00.123456789" "2021-12-31 00:00:00.123456789"] | polars into-df | polars as-datetime "%Y-%m-%d %H:%M:%S.%9f" --naive"#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "datetime".to_string(), vec![ Value::date( DateTime::parse_from_str( "2021-12-30 00:00:00.123456789 +0000", "%Y-%m-%d %H:%M:%S.%9f %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), Value::date( DateTime::parse_from_str( "2021-12-31 00:00:00.123456789 +0000", "%Y-%m-%d %H:%M:%S.%9f %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), ], )], Some(NuSchema::new(Arc::new(Schema::from_iter(vec![ Field::new( "datetime".into(), DataType::Datetime(TimeUnit::Nanoseconds, None), ), ])))), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Converts string to datetime using the `--not-exact` flag even with excessive symbols", example: r#"["2021-12-30 00:00:00 GMT+4"] | polars into-df | polars as-datetime "%Y-%m-%d %H:%M:%S" --not-exact --naive"#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "datetime".to_string(), vec![Value::date( DateTime::parse_from_str( "2021-12-30 00:00:00 +0000", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), )], )], Some(NuSchema::new(Arc::new(Schema::from_iter(vec![ Field::new( "datetime".into(), DataType::Datetime(TimeUnit::Nanoseconds, None), ), ])))), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Converts string to datetime using the `--not-exact` flag even with excessive symbols in an expression", example: r#"["2025-11-02 00:00:00", "2025-11-02 01:00:00", "2025-11-02 02:00:00", "2025-11-02 03:00:00"] | polars into-df | polars select (polars col 0 | polars as-datetime "%Y-%m-%d %H:%M:%S")"#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "datetime".to_string(), vec![ Value::date( DateTime::parse_from_str( "2025-11-02 00:00:00 +0000", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), Value::date( DateTime::parse_from_str( "2025-11-02 01:00:00 +0000", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), Value::date( DateTime::parse_from_str( "2025-11-02 02:00:00 +0000", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), Value::date( DateTime::parse_from_str( "2025-11-02 03:00:00 +0000", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), ], )], Some(NuSchema::new(Arc::new(Schema::from_iter(vec![ Field::new( "datetime".into(), DataType::Datetime(TimeUnit::Nanoseconds, None), ), ])))), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let format: String = call.req(0)?; let not_exact = call.has_flag("not-exact")?; let tz_aware = !call.has_flag("naive")?; let time_unit: Option<TimeUnit> = call .get_flag::<Spanned<String>>("time-unit")? .map(|s| str_to_time_unit(&s.item, s.span)) .transpose()?; let time_zone: Option<TimeZone> = call .get_flag::<Spanned<String>>("time-zone")? .map(|s| timezone_from_str(&s.item, Some(s.span))) .transpose()?; let value = input.into_value(call.head)?; let options = StrptimeOptions { format: Some(format.into()), strict: true, exact: !not_exact, cache: Default::default(), }; let ambiguous = match call.get_flag::<Value>("ambiguous")? { Some(v @ Value::String { .. }) => { let span = v.span(); let val = v.into_string()?; match val.as_str() { "raise" | "earliest" | "latest" => Ok(val), _ => Err(ShellError::GenericError { error: "Invalid argument value".into(), msg: "`ambiguous` must be one of raise, earliest, latest, or null".into(), span: Some(span), help: None, inner: vec![], }), } } Some(Value::Nothing { .. }) => Ok("null".into()), Some(_) => unreachable!("Argument only accepts string or null."), None => Ok("raise".into()), } .map_err(LabeledError::from)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuLazyFrame(lazy) => command_lazy( plugin, engine, call, LazyParams::new(lazy, options, ambiguous, time_unit, time_zone), ), PolarsPluginObject::NuDataFrame(df) => command_eager( plugin, engine, call, EagerParams::new(df, options, tz_aware, time_unit, time_zone), ), PolarsPluginObject::NuExpression(expr) => { let res: NuExpression = expr .into_polars() .str() .to_datetime( time_unit, time_zone, options, Expr::Literal(LiteralValue::Dyn(DynLiteralValue::Str( PlSmallStr::from_string(ambiguous), ))), ) .into(); res.to_pipeline_data(plugin, engine, call.head) } _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } } struct LazyParams { lazy: NuLazyFrame, options: StrptimeOptions, ambiguous: String, time_unit: Option<TimeUnit>, time_zone: Option<TimeZone>, } impl LazyParams { fn new( lazy: NuLazyFrame, options: StrptimeOptions, ambiguous: String, time_unit: Option<TimeUnit>, time_zone: Option<TimeZone>, ) -> Self { Self { lazy, options, ambiguous, time_unit, time_zone, } } } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, LazyParams { lazy, options, ambiguous, time_unit, time_zone, }: LazyParams, ) -> Result<PipelineData, ShellError> { NuLazyFrame::new( false, lazy.to_polars().select([col("*").str().to_datetime( time_unit, time_zone, options, Expr::Literal(LiteralValue::Dyn(DynLiteralValue::Str( PlSmallStr::from_string(ambiguous), ))), )]), ) .to_pipeline_data(plugin, engine, call.head) } struct EagerParams { df: NuDataFrame, options: StrptimeOptions, tz_aware: bool, time_unit: Option<TimeUnit>, time_zone: Option<TimeZone>, } impl EagerParams { fn new( df: NuDataFrame, options: StrptimeOptions, tz_aware: bool, time_unit: Option<TimeUnit>, time_zone: Option<TimeZone>, ) -> Self { Self { df, options, tz_aware, time_unit, time_zone, } } } fn command_eager( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, EagerParams { df, options, tz_aware, time_unit, time_zone, }: EagerParams, ) -> Result<PipelineData, ShellError> { let format = if let Some(format) = options.format { format.to_string() } else { unreachable!("`format` will never be None") }; let not_exact = !options.exact; let series = df.as_series(call.head)?; let casted = series.str().map_err(|e| ShellError::GenericError { error: "Error casting to string".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })?; let res = if not_exact { casted.as_datetime_not_exact( Some(format.as_str()), time_unit.unwrap_or(TimeUnit::Nanoseconds), tz_aware, time_zone.as_ref(), &Default::default(), true, ) } else { casted.as_datetime( Some(format.as_str()), time_unit.unwrap_or(TimeUnit::Nanoseconds), false, tz_aware, time_zone.as_ref(), &Default::default(), ) }; let mut res = res .map_err(|e| ShellError::GenericError { error: "Error creating datetime".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })? .into_series(); res.rename("datetime".into()); let df = NuDataFrame::try_from_series_vec(vec![res], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command_with_decls; use nu_command::IntoDatetime; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command_with_decls(&AsDateTime, vec![Box::new(IntoDatetime)]) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/datetime/get_nanosecond.rs
crates/nu_plugin_polars/src/dataframe/command/datetime/get_nanosecond.rs
use crate::{ PolarsPlugin, values::{ CustomValueSupport, NuDataFrame, NuExpression, NuLazyFrame, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{Category, Example, LabeledError, PipelineData, ShellError, Signature, Span}; use polars::{ prelude::{DatetimeMethods, IntoSeries, NamedFrom, col}, series::Series, }; #[derive(Clone)] pub struct GetNanosecond; impl PluginCommand for GetNanosecond { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars get-nanosecond" } fn description(&self) -> &str { "Gets nanosecond from date." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Returns nanosecond from a date", example: r#"let dt = ('2020-08-04T16:39:18+00:00' | into datetime --timezone 'UTC'); let df = ([$dt $dt] | polars into-df); $df | polars get-nanosecond"#, result: Some( NuDataFrame::try_from_series( Series::new("0".into(), &[0i32, 0]), Span::test_data(), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Returns nanosecond from a date", example: r#"let dt = ('2020-08-04T16:39:18+00:00' | into datetime --timezone 'UTC'); let df = ([$dt $dt] | polars into-df); $df | polars select (polars col 0 | polars get-nanosecond)"#, result: Some( NuDataFrame::try_from_series( Series::new("0".into(), &[0i32, 0]), Span::test_data(), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuLazyFrame(lazy) => command_lazy(plugin, engine, call, lazy), PolarsPluginObject::NuDataFrame(df) => command_eager(plugin, engine, call, df), PolarsPluginObject::NuExpression(expr) => { let res: NuExpression = expr.into_polars().dt().nanosecond().into(); res.to_pipeline_data(plugin, engine, call.head) } _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, ) -> Result<PipelineData, ShellError> { NuLazyFrame::new(false, lazy.to_polars().select([col("*").dt().nanosecond()])) .to_pipeline_data(plugin, engine, call.head) } fn command_eager( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let series = df.as_series(call.head)?; let casted = series.datetime().map_err(|e| ShellError::GenericError { error: "Error casting to datetime type".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })?; let res = casted.nanosecond().into_series(); let df = NuDataFrame::try_from_series_vec(vec![res], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command_with_decls; use nu_command::IntoDatetime; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command_with_decls(&GetNanosecond, vec![Box::new(IntoDatetime)]) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/datetime/datepart.rs
crates/nu_plugin_polars/src/dataframe/command/datetime/datepart.rs
use crate::values::{NuExpression, PolarsPluginType}; use std::sync::Arc; use crate::{ PolarsPlugin, dataframe::values::{Column, NuDataFrame, NuSchema}, values::CustomValueSupport, }; use chrono::{DateTime, FixedOffset}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Spanned, SyntaxShape, Value, }; use polars::{ datatypes::{DataType, TimeUnit}, prelude::{Field, NamedFrom, Schema}, series::Series, }; #[derive(Clone)] pub struct ExprDatePart; impl PluginCommand for ExprDatePart { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars datepart" } fn description(&self) -> &str { "Creates an expression for capturing the specified datepart in a column." } fn signature(&self) -> Signature { Signature::build(self.name()) .required( "Datepart name", SyntaxShape::String, "Part of the date to capture. Possible values are year, quarter, month, week, weekday, day, hour, minute, second, millisecond, microsecond, nanosecond", ) .input_output_type( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ) .category(Category::Custom("expression".into())) } fn examples(&self) -> Vec<Example<'_>> { let dt = DateTime::<FixedOffset>::parse_from_str( "2021-12-30T01:02:03.123456789 +0000", "%Y-%m-%dT%H:%M:%S.%9f %z", ) .expect("date calculation should not fail in test"); vec![ Example { description: "Creates an expression to capture the year date part", example: r#"[["2021-12-30T01:02:03.123456789"]] | polars into-df | polars as-datetime "%Y-%m-%dT%H:%M:%S.%9f" --naive | polars with-column [(polars col datetime | polars datepart year | polars as datetime_year )]"#, result: Some( NuDataFrame::try_from_columns( vec![ Column::new("datetime".to_string(), vec![Value::test_date(dt)]), Column::new("datetime_year".to_string(), vec![Value::test_int(2021)]), ], Some(NuSchema::new(Arc::new(Schema::from_iter(vec![ Field::new( "datetime".into(), DataType::Datetime(TimeUnit::Nanoseconds, None), ), Field::new("datetime_year".into(), DataType::Int64), ])))), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Creates an expression to capture multiple date parts", example: r#"[["2021-12-30T01:02:03.123456789"]] | polars into-df | polars as-datetime "%Y-%m-%dT%H:%M:%S.%9f" --naive | polars with-column [ (polars col datetime | polars datepart year | polars as datetime_year ), (polars col datetime | polars datepart month | polars as datetime_month ), (polars col datetime | polars datepart day | polars as datetime_day ), (polars col datetime | polars datepart hour | polars as datetime_hour ), (polars col datetime | polars datepart minute | polars as datetime_minute ), (polars col datetime | polars datepart second | polars as datetime_second ), (polars col datetime | polars datepart nanosecond | polars as datetime_ns ) ]"#, result: Some( NuDataFrame::try_from_series_vec( vec![ Series::new("datetime".into(), &[dt.timestamp_nanos_opt()]) .cast(&DataType::Datetime(TimeUnit::Nanoseconds, None)) .expect("Error casting to datetime type"), Series::new("datetime_year".into(), &[2021_i64]), // i32 was coerced to i64 Series::new("datetime_month".into(), &[12_i8]), Series::new("datetime_day".into(), &[30_i8]), Series::new("datetime_hour".into(), &[1_i8]), Series::new("datetime_minute".into(), &[2_i8]), Series::new("datetime_second".into(), &[3_i8]), Series::new("datetime_ns".into(), &[123456789_i64]), // i32 was coerced to i64 ], Span::test_data(), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn search_terms(&self) -> Vec<&str> { vec![ "year", "month", "week", "weekday", "quarter", "day", "hour", "minute", "second", "millisecond", "microsecond", "nanosecond", ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let part: Spanned<String> = call.req(0)?; let expr = NuExpression::try_from_pipeline(plugin, input, call.head)?; let expr_dt = expr.into_polars().dt(); let expr: NuExpression = match part.item.as_str() { "year" => expr_dt.year(), "quarter" => expr_dt.quarter(), "month" => expr_dt.month(), "week" => expr_dt.week(), "day" => expr_dt.day(), "hour" => expr_dt.hour(), "minute" => expr_dt.minute(), "second" => expr_dt.second(), "millisecond" => expr_dt.millisecond(), "microsecond" => expr_dt.microsecond(), "nanosecond" => expr_dt.nanosecond(), _ => { return Err(LabeledError::from(ShellError::UnsupportedInput { msg: format!("{} is not a valid datepart, expected one of year, month, day, hour, minute, second, millisecond, microsecond, nanosecond", part.item), input: "value originates from here".to_string(), msg_span: call.head, input_span: part.span, })) } }.into(); expr.to_pipeline_data(plugin, engine, call.head) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ExprDatePart) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/datetime/get_day.rs
crates/nu_plugin_polars/src/dataframe/command/datetime/get_day.rs
use crate::{ PolarsPlugin, values::{ CustomValueSupport, NuDataFrame, NuExpression, NuLazyFrame, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{Category, Example, LabeledError, PipelineData, ShellError, Signature, Span}; use polars::{ prelude::{DatetimeMethods, IntoSeries, NamedFrom, col}, series::Series, }; #[derive(Clone)] pub struct GetDay; impl PluginCommand for GetDay { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars get-day" } fn description(&self) -> &str { "Gets day from date." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Returns day from a date", example: r#"let dt = ('2020-08-04T16:39:18+00:00' | into datetime --timezone 'UTC'); let df = ([$dt $dt] | polars into-df); $df | polars get-day"#, result: Some( NuDataFrame::try_from_series( Series::new("0".into(), &[4i8, 4]), Span::test_data(), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Returns day from a date in an expression", example: r#"let dt = ('2020-08-04T16:39:18+00:00' | into datetime --timezone 'UTC'); let df = ([$dt $dt] | polars into-df); $df | polars select (polars col 0 | polars get-day)"#, result: Some( NuDataFrame::try_from_series( Series::new("0".into(), &[4i8, 4]), Span::test_data(), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn extra_description(&self) -> &str { "" } fn search_terms(&self) -> Vec<&str> { vec![] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuLazyFrame(lazy) => command_lazy(plugin, engine, call, lazy), PolarsPluginObject::NuDataFrame(df) => command_eager(plugin, engine, call, df), PolarsPluginObject::NuExpression(expr) => { let res: NuExpression = expr.into_polars().dt().day().into(); res.to_pipeline_data(plugin, engine, call.head) } _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, ) -> Result<PipelineData, ShellError> { NuLazyFrame::new(false, lazy.to_polars().select([col("*").dt().day()])) .to_pipeline_data(plugin, engine, call.head) } fn command_eager( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let series = df.as_series(call.head)?; let casted = series.datetime().map_err(|e| ShellError::GenericError { error: "Error casting to datetime type".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })?; let res = casted.day().into_series(); let df = NuDataFrame::try_from_series_vec(vec![res], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command_with_decls; use nu_command::IntoDatetime; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command_with_decls(&GetDay, vec![Box::new(IntoDatetime)]) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/datetime/convert_time_zone.rs
crates/nu_plugin_polars/src/dataframe/command/datetime/convert_time_zone.rs
use crate::values::{Column, NuDataFrame, NuSchema}; use crate::{ PolarsPlugin, dataframe::values::NuExpression, values::{CustomValueSupport, PolarsPluginObject, PolarsPluginType, cant_convert_err}, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, Signature, Span, Spanned, SyntaxShape, Value, }; use chrono::DateTime; use polars::prelude::*; use super::timezone_from_str; #[derive(Clone)] pub struct ConvertTimeZone; impl PluginCommand for ConvertTimeZone { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars convert-time-zone" } fn description(&self) -> &str { "Convert datetime to target timezone." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), )]) .required( "time_zone", SyntaxShape::String, "Timezone for the Datetime Series. Pass `null` to unset time zone.", ) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Convert timezone for timezone-aware datetime", example: r#"["2025-04-10 09:30:00 -0400" "2025-04-10 10:30:00 -0400"] | polars into-df | polars as-datetime "%Y-%m-%d %H:%M:%S %z" | polars select (polars col datetime | polars convert-time-zone "Europe/Lisbon")"#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "datetime".to_string(), vec![ Value::date( DateTime::parse_from_str( "2025-04-10 14:30:00 +0100", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), Value::date( DateTime::parse_from_str( "2025-04-10 15:30:00 +0100", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), ], )], Some(NuSchema::new(Arc::new(Schema::from_iter(vec![ Field::new( "datetime".into(), DataType::Datetime( TimeUnit::Nanoseconds, TimeZone::opt_try_new(Some("Europe/Lisbon")) .expect("timezone should be valid"), ), ), ])))), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Timezone conversions for timezone-naive datetime will assume the original timezone is UTC", example: r#"["2025-04-10 09:30:00" "2025-04-10 10:30:00"] | polars into-df | polars as-datetime "%Y-%m-%d %H:%M:%S" --naive | polars select (polars col datetime | polars convert-time-zone "America/New_York")"#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "datetime".to_string(), vec![ Value::date( DateTime::parse_from_str( "2025-04-10 05:30:00 -0400", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), Value::date( DateTime::parse_from_str( "2025-04-10 06:30:00 -0400", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), ], )], Some(NuSchema::new(Arc::new(Schema::from_iter(vec![ Field::new( "datetime".into(), DataType::Datetime( TimeUnit::Nanoseconds, TimeZone::opt_try_new(Some("America/New_York")) .expect("timezone should be valid"), ), ), ])))), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuExpression(expr) => { let time_zone_spanned: Spanned<String> = call.req(0)?; let time_zone = timezone_from_str(&time_zone_spanned.item, Some(time_zone_spanned.span))?; let expr: NuExpression = expr.into_polars().dt().convert_time_zone(time_zone).into(); expr.to_pipeline_data(plugin, engine, call.head) } _ => Err(cant_convert_err(&value, &[PolarsPluginType::NuExpression])), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; use nu_protocol::ShellError; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ConvertTimeZone) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/datetime/get_year.rs
crates/nu_plugin_polars/src/dataframe/command/datetime/get_year.rs
use crate::{ PolarsPlugin, values::{ CustomValueSupport, NuDataFrame, NuExpression, NuLazyFrame, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{Category, Example, LabeledError, PipelineData, ShellError, Signature, Span}; use polars::{ prelude::{DatetimeMethods, IntoSeries, NamedFrom, col}, series::Series, }; #[derive(Clone)] pub struct GetYear; impl PluginCommand for GetYear { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars get-year" } fn description(&self) -> &str { "Gets year from date." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Returns year from a date", example: r#"let dt = ('2020-08-04T16:39:18+00:00' | into datetime --timezone 'UTC'); let df = ([$dt $dt] | polars into-df); $df | polars get-year"#, result: Some( NuDataFrame::try_from_series( Series::new("0".into(), &[2020i32, 2020]), Span::test_data(), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Returns year from a date in an expression", example: r#"let dt = ('2020-08-04T16:39:18+00:00' | into datetime --timezone 'UTC'); let df = ([$dt $dt] | polars into-df); $df | polars select (polars col 0 | polars get-year)"#, result: Some( NuDataFrame::try_from_series( Series::new("0".into(), &[2020i32, 2020]), Span::test_data(), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuLazyFrame(lazy) => command_lazy(plugin, engine, call, lazy), PolarsPluginObject::NuDataFrame(df) => command_eager(plugin, engine, call, df), PolarsPluginObject::NuExpression(expr) => { let res: NuExpression = expr.into_polars().dt().year().into(); res.to_pipeline_data(plugin, engine, call.head) } _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, ) -> Result<PipelineData, ShellError> { NuLazyFrame::new(false, lazy.to_polars().select([col("*").dt().year()])) .to_pipeline_data(plugin, engine, call.head) } fn command_eager( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let series = df.as_series(call.head)?; let casted = series.datetime().map_err(|e| ShellError::GenericError { error: "Error casting to datetime type".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })?; let res = casted.year().into_series(); let df = NuDataFrame::try_from_series_vec(vec![res], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command_with_decls; use nu_command::IntoDatetime; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command_with_decls(&GetYear, vec![Box::new(IntoDatetime)]) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/datetime/mod.rs
crates/nu_plugin_polars/src/dataframe/command/datetime/mod.rs
mod as_date; mod as_datetime; mod convert_time_zone; mod datepart; mod get_day; mod get_hour; mod get_minute; mod get_month; mod get_nanosecond; mod get_ordinal; mod get_second; mod get_week; mod get_weekday; mod get_year; mod replace_time_zone; mod strftime; mod truncate; use crate::PolarsPlugin; use nu_plugin::PluginCommand; pub use as_date::AsDate; pub use as_datetime::AsDateTime; pub use convert_time_zone::ConvertTimeZone; pub use datepart::ExprDatePart; pub use get_day::GetDay; pub use get_hour::GetHour; pub use get_minute::GetMinute; pub use get_month::GetMonth; pub use get_nanosecond::GetNanosecond; pub use get_ordinal::GetOrdinal; pub use get_second::GetSecond; pub use get_week::GetWeek; pub use get_weekday::GetWeekDay; pub use get_year::GetYear; use nu_protocol::{ShellError, Span}; use polars::prelude::{PlSmallStr, TimeZone}; pub use replace_time_zone::ReplaceTimeZone; pub use strftime::StrFTime; pub use truncate::Truncate; pub(crate) fn datetime_commands() -> Vec<Box<dyn PluginCommand<Plugin = PolarsPlugin>>> { vec![ Box::new(AsDate), Box::new(AsDateTime), Box::new(ConvertTimeZone), Box::new(ExprDatePart), Box::new(GetDay), Box::new(GetHour), Box::new(GetMinute), Box::new(GetMonth), Box::new(GetNanosecond), Box::new(GetOrdinal), Box::new(GetSecond), Box::new(GetWeek), Box::new(GetWeekDay), Box::new(GetYear), Box::new(ReplaceTimeZone), Box::new(StrFTime), Box::new(Truncate), ] } pub fn timezone_from_str(zone_str: &str, span: Option<Span>) -> Result<TimeZone, ShellError> { TimeZone::opt_try_new(Some(PlSmallStr::from_str(zone_str))) .map_err(|e| ShellError::GenericError { error: format!("Invalid timezone: {zone_str} : {e}"), msg: "".into(), span, help: None, inner: vec![], })? .ok_or(ShellError::GenericError { error: format!("Invalid timezone {zone_str}"), msg: "".into(), span, help: None, inner: vec![], }) } pub fn timezone_utc() -> TimeZone { TimeZone::opt_try_new(Some(PlSmallStr::from_str("UTC"))) .expect("UTC timezone should always be valid") .expect("UTC timezone should always be present") } #[cfg(test)] mod test { use super::*; #[test] fn test_timezone_from_str() -> Result<(), ShellError> { let tz = timezone_from_str("America/New_York", None)?; assert_eq!(tz.to_string(), "America/New_York"); Ok(()) } #[test] fn test_timezone_utc() { let tz = timezone_utc(); assert_eq!(tz.to_string(), "UTC"); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/datetime/replace_time_zone.rs
crates/nu_plugin_polars/src/dataframe/command/datetime/replace_time_zone.rs
use crate::values::{Column, NuDataFrame, NuSchema}; use crate::{ PolarsPlugin, dataframe::values::NuExpression, values::{CustomValueSupport, PolarsPluginObject, PolarsPluginType, cant_convert_err}, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Spanned, SyntaxShape, Value, }; use chrono::DateTime; use polars::prelude::*; use polars_plan::plans::DynLiteralValue; use super::timezone_from_str; #[derive(Clone)] pub struct ReplaceTimeZone; impl PluginCommand for ReplaceTimeZone { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars replace-time-zone" } fn description(&self) -> &str { "Replace the timezone information in a datetime column." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), )]) .required( "time_zone", SyntaxShape::String, "Timezone for the Datetime Series. Pass `null` to unset time zone.", ) .named( "ambiguous", SyntaxShape::OneOf(vec![SyntaxShape::String, SyntaxShape::Nothing]), r#"Determine how to deal with ambiguous datetimes: `raise` (default): raise error `earliest`: use the earliest datetime `latest`: use the latest datetime `null`: set to null"#, Some('a'), ) .named( "nonexistent", SyntaxShape::OneOf(vec![SyntaxShape::String, SyntaxShape::Nothing]), r#"Determine how to deal with non-existent datetimes: raise (default) or null."#, Some('n'), ) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Apply timezone to a naive datetime", example: r#"["2021-12-30 00:00:00" "2021-12-31 00:00:00"] | polars into-df | polars as-datetime "%Y-%m-%d %H:%M:%S" --naive | polars select (polars col datetime | polars replace-time-zone "America/New_York")"#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "datetime".to_string(), vec![ Value::date( DateTime::parse_from_str( "2021-12-30 00:00:00 -0500", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), Value::date( DateTime::parse_from_str( "2021-12-31 00:00:00 -0500", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), ], )], Some(NuSchema::new(Arc::new(Schema::from_iter(vec![ Field::new( "datetime".into(), DataType::Datetime( TimeUnit::Nanoseconds, TimeZone::opt_try_new(Some("America/New_York")) .expect("timezone should be valid"), ), ), ])))), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Apply timezone with ambiguous datetime", example: r#"["2025-11-02 00:00:00", "2025-11-02 01:00:00", "2025-11-02 02:00:00", "2025-11-02 03:00:00"] | polars into-df | polars as-datetime "%Y-%m-%d %H:%M:%S" --naive | polars select (polars col datetime | polars replace-time-zone "America/New_York" --ambiguous null)"#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "datetime".to_string(), vec![ Value::date( DateTime::parse_from_str( "2025-11-02 00:00:00 -0400", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), Value::nothing(Span::test_data()), Value::date( DateTime::parse_from_str( "2025-11-02 02:00:00 -0500", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), Value::date( DateTime::parse_from_str( "2025-11-02 03:00:00 -0500", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), ], )], Some(NuSchema::new(Arc::new(Schema::from_iter(vec![ Field::new( "datetime".into(), DataType::Datetime( TimeUnit::Nanoseconds, TimeZone::opt_try_new(Some("America/New_York")) .expect("timezone should be valid"), ), ), ])))), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Apply timezone with nonexistent datetime", example: r#"["2025-03-09 01:00:00", "2025-03-09 02:00:00", "2025-03-09 03:00:00", "2025-03-09 04:00:00"] | polars into-df | polars as-datetime "%Y-%m-%d %H:%M:%S" --naive | polars select (polars col datetime | polars replace-time-zone "America/New_York" --nonexistent null)"#, result: Some( NuDataFrame::try_from_columns( vec![Column::new( "datetime".to_string(), vec![ Value::date( DateTime::parse_from_str( "2025-03-09 01:00:00 -0500", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), Value::nothing(Span::test_data()), Value::date( DateTime::parse_from_str( "2025-03-09 03:00:00 -0400", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), Value::date( DateTime::parse_from_str( "2025-03-09 04:00:00 -0400", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), ], )], Some(NuSchema::new(Arc::new(Schema::from_iter(vec![ Field::new( "datetime".into(), DataType::Datetime( TimeUnit::Nanoseconds, TimeZone::opt_try_new(Some("America/New_York")) .expect("timezone should be valid"), ), ), ])))), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); let value = input.into_value(call.head)?; let ambiguous = match call.get_flag::<Value>("ambiguous")? { Some(v @ Value::String { .. }) => { let span = v.span(); let val = v.into_string()?; match val.as_str() { "raise" | "earliest" | "latest" => Ok(val), _ => Err(ShellError::GenericError { error: "Invalid argument value".into(), msg: "`ambiguous` must be one of raise, earliest, latest, or null".into(), span: Some(span), help: None, inner: vec![], }), } } Some(Value::Nothing { .. }) => Ok("null".into()), Some(_) => unreachable!("Argument only accepts string or null."), None => Ok("raise".into()), } .map_err(LabeledError::from)?; let nonexistent = match call.get_flag::<Value>("nonexistent")? { Some(v @ Value::String { .. }) => match v.as_str()? { "raise" => Ok(NonExistent::Raise), _ => Err(ShellError::GenericError { error: "Invalid argument value".into(), msg: "`nonexistent` must be one of raise or null".into(), span: Some(v.span()), help: None, inner: vec![], }), }, Some(Value::Nothing { .. }) => Ok(NonExistent::Null), Some(_) => unreachable!("Argument only accepts string or null."), None => Ok(NonExistent::Raise), } .map_err(LabeledError::from)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuExpression(expr) => { let time_zone_spanned: Spanned<String> = call.req(0)?; let time_zone = timezone_from_str(&time_zone_spanned.item, Some(time_zone_spanned.span))?; let expr: NuExpression = expr .into_polars() .dt() .replace_time_zone( Some(time_zone), Expr::Literal(LiteralValue::Dyn(DynLiteralValue::Str( PlSmallStr::from_string(ambiguous), ))), nonexistent, ) .into(); expr.to_pipeline_data(plugin, engine, call.head) } _ => Err(cant_convert_err(&value, &[PolarsPluginType::NuExpression])), } .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; use nu_protocol::ShellError; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ReplaceTimeZone) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/datetime/get_second.rs
crates/nu_plugin_polars/src/dataframe/command/datetime/get_second.rs
use crate::{ PolarsPlugin, values::{ CustomValueSupport, NuDataFrame, NuExpression, NuLazyFrame, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{Category, Example, LabeledError, PipelineData, ShellError, Signature, Span}; use polars::{ prelude::{DatetimeMethods, IntoSeries, NamedFrom, col}, series::Series, }; #[derive(Clone)] pub struct GetSecond; impl PluginCommand for GetSecond { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars get-second" } fn description(&self) -> &str { "Gets second from date." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Returns second from a date", example: r#"let dt = ('2020-08-04T16:39:18+00:00' | into datetime --timezone 'UTC'); let df = ([$dt $dt] | polars into-df); $df | polars get-second"#, result: Some( NuDataFrame::try_from_series( Series::new("0".into(), &[18i8, 18]), Span::test_data(), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Returns second from a date in an expression", example: r#"let dt = ('2020-08-04T16:39:18+00:00' | into datetime --timezone 'UTC'); let df = ([$dt $dt] | polars into-df); $df | polars select (polars col 0 | polars get-second)"#, result: Some( NuDataFrame::try_from_series( Series::new("0".into(), &[18i8, 18]), Span::test_data(), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuLazyFrame(lazy) => command_lazy(plugin, engine, call, lazy), PolarsPluginObject::NuDataFrame(df) => command_eager(plugin, engine, call, df), PolarsPluginObject::NuExpression(expr) => { let res: NuExpression = expr.into_polars().dt().second().into(); res.to_pipeline_data(plugin, engine, call.head) } _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, ) -> Result<PipelineData, ShellError> { NuLazyFrame::new(false, lazy.to_polars().select([col("*").dt().second()])) .to_pipeline_data(plugin, engine, call.head) } fn command_eager( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let series = df.as_series(call.head)?; let casted = series.datetime().map_err(|e| ShellError::GenericError { error: "Error casting to datetime type".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })?; let res = casted.second().into_series(); let df = NuDataFrame::try_from_series_vec(vec![res], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command_with_decls; use nu_command::IntoDatetime; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command_with_decls(&GetSecond, vec![Box::new(IntoDatetime)]) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/datetime/truncate.rs
crates/nu_plugin_polars/src/dataframe/command/datetime/truncate.rs
use crate::{ PolarsPlugin, values::{ Column, CustomValueSupport, NuDataFrame, NuExpression, NuSchema, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; use std::sync::Arc; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, }; use chrono::DateTime; use polars::prelude::{DataType, Expr, Field, LiteralValue, PlSmallStr, Schema, TimeUnit}; use polars_plan::plans::DynLiteralValue; #[derive(Clone)] pub struct Truncate; impl PluginCommand for Truncate { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars truncate" } fn description(&self) -> &str { "Divide the date/datetime range into buckets." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), )]) .required( "every", SyntaxShape::OneOf(vec![SyntaxShape::Duration, SyntaxShape::String]), "Period length for every interval (can be duration or str)", ) .category(Category::Custom("expression".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Truncate a series of dates by period length", example: r#"seq date -b 2025-01-01 --periods 4 --increment 6wk -o "%Y-%m-%d %H:%M:%S" | polars into-df | polars as-datetime "%F %H:%M:%S" --naive | polars select datetime (polars col datetime | polars truncate 5d37m | polars as truncated)"#, result: Some( NuDataFrame::try_from_columns( vec![ Column::new( "datetime".to_string(), vec![ Value::date( DateTime::parse_from_str( "2025-01-01 00:00:00 +0000", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), Value::date( DateTime::parse_from_str( "2025-02-12 00:00:00 +0000", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), Value::date( DateTime::parse_from_str( "2025-03-26 00:00:00 +0000", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), Value::date( DateTime::parse_from_str( "2025-05-07 00:00:00 +0000", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), ], ), Column::new( "truncated".to_string(), vec![ Value::date( DateTime::parse_from_str( "2024-12-30 16:49:00 +0000", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), Value::date( DateTime::parse_from_str( "2025-02-08 21:45:00 +0000", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), Value::date( DateTime::parse_from_str( "2025-03-21 02:41:00 +0000", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), Value::date( DateTime::parse_from_str( "2025-05-05 08:14:00 +0000", "%Y-%m-%d %H:%M:%S %z", ) .expect("date calculation should not fail in test"), Span::test_data(), ), ], ), ], Some(NuSchema::new(Arc::new(Schema::from_iter(vec![ Field::new( "datetime".into(), DataType::Datetime(TimeUnit::Nanoseconds, None), ), Field::new( "truncated".into(), DataType::Datetime(TimeUnit::Nanoseconds, None), ), ])))), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } fn extra_description(&self) -> &str { r#"Each date/datetime is mapped to the start of its bucket using the corresponding local datetime. Note that weekly buckets start on Monday. Ambiguous results are localised using the DST offset of the original timestamp - for example, truncating '2022-11-06 01:30:00 CST' by '1h' results in '2022-11-06 01:00:00 CST', whereas truncating '2022-11-06 01:30:00 CDT' by '1h' results in '2022-11-06 01:00:00 CDT'. See Notes in documentation for full list of compatible string values for `every`: https://docs.pola.rs/api/python/stable/reference/expressions/api/polars.Expr.dt.truncate.html"# } fn search_terms(&self) -> Vec<&str> { vec![] } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let value = input.into_value(call.head)?; let every = match call.req(0)? { // handle Value::Duration input for maximum compatibility // duration types are always stored as nanoseconds Value::Duration { val, .. } => Ok(format!("{val}ns")), Value::String { val, .. } => Ok(val.clone()), x => Err(ShellError::IncompatibleParametersSingle { msg: format!("Expected duration or str type but got {}", x.get_type()), span: value.span(), }), }?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuExpression(expr) => { let res: NuExpression = expr .into_polars() .dt() .truncate(Expr::Literal(LiteralValue::Dyn(DynLiteralValue::Str( PlSmallStr::from_string(every), )))) .into(); res.to_pipeline_data(plugin, engine, call.head) } _ => Err(cant_convert_err(&value, &[PolarsPluginType::NuExpression])), } } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command_with_decls; use nu_command::SeqDate; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command_with_decls(&Truncate, vec![Box::new(SeqDate)]) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/datetime/get_hour.rs
crates/nu_plugin_polars/src/dataframe/command/datetime/get_hour.rs
use crate::{ PolarsPlugin, values::{ CustomValueSupport, NuExpression, NuLazyFrame, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; use super::super::super::values::NuDataFrame; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{Category, Example, LabeledError, PipelineData, ShellError, Signature, Span}; use polars::{ prelude::{DatetimeMethods, IntoSeries, NamedFrom, col}, series::Series, }; #[derive(Clone)] pub struct GetHour; impl PluginCommand for GetHour { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars get-hour" } fn description(&self) -> &str { "Gets hour from datetime." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Returns hour from a date", example: r#"let dt = ('2020-08-04T16:39:18+00:00' | into datetime --timezone 'UTC'); let df = ([$dt $dt] | polars into-df); $df | polars get-hour"#, result: Some( NuDataFrame::try_from_series( Series::new("0".into(), &[16i8, 16]), Span::test_data(), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Returns hour from a date in a lazyframe", example: r#"let dt = ('2020-08-04T16:39:18+00:00' | into datetime --timezone 'UTC'); let df = ([$dt $dt] | polars into-lazy); $df | polars get-hour"#, result: Some( NuDataFrame::try_from_series( Series::new("0".into(), &[16i8, 16]), Span::test_data(), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Returns hour from a date in an expression", example: r#"let dt = ('2020-08-04T16:39:18+00:00' | into datetime --timezone 'UTC'); let df = ([$dt $dt] | polars into-df); $df | polars select (polars col 0 | polars get-hour)"#, result: Some( NuDataFrame::try_from_series( Series::new("0".into(), &[16i8, 16]), Span::test_data(), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuLazyFrame(lazy) => command_lazy(plugin, engine, call, lazy), PolarsPluginObject::NuDataFrame(df) => command_eager(plugin, engine, call, df), PolarsPluginObject::NuExpression(expr) => { let res: NuExpression = expr.into_polars().dt().hour().into(); res.to_pipeline_data(plugin, engine, call.head) } _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, ) -> Result<PipelineData, ShellError> { NuLazyFrame::new(false, lazy.to_polars().select([col("*").dt().hour()])) .to_pipeline_data(plugin, engine, call.head) } fn command_eager( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let series = df.as_series(call.head)?; let casted = series.datetime().map_err(|e| ShellError::GenericError { error: "Error casting to datetime type".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })?; let res = casted.hour().into_series(); let df = NuDataFrame::try_from_series_vec(vec![res], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command_with_decls; use nu_command::IntoDatetime; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command_with_decls(&GetHour, vec![Box::new(IntoDatetime)]) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/datetime/get_month.rs
crates/nu_plugin_polars/src/dataframe/command/datetime/get_month.rs
use crate::{ PolarsPlugin, values::{ CustomValueSupport, NuDataFrame, NuExpression, NuLazyFrame, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{Category, Example, LabeledError, PipelineData, ShellError, Signature, Span}; use polars::{ prelude::{DatetimeMethods, IntoSeries, NamedFrom, col}, series::Series, }; #[derive(Clone)] pub struct GetMonth; impl PluginCommand for GetMonth { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars get-month" } fn description(&self) -> &str { "Gets month from date." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Returns month from a date", example: r#"let dt = ('2020-08-04T16:39:18+00:00' | into datetime --timezone 'UTC'); let df = ([$dt $dt] | polars into-df); $df | polars get-month"#, result: Some( NuDataFrame::try_from_series( Series::new("0".into(), &[8i8, 8]), Span::test_data(), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Returns month from a date in an expression", example: r#"let dt = ('2020-08-04T16:39:18+00:00' | into datetime --timezone 'UTC'); let df = ([$dt $dt] | polars into-df); $df | polars select (polars col 0 | polars get-month)"#, result: Some( NuDataFrame::try_from_series( Series::new("0".into(), &[8i8, 8]), Span::test_data(), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuLazyFrame(lazy) => command_lazy(plugin, engine, call, lazy), PolarsPluginObject::NuDataFrame(df) => command_eager(plugin, engine, call, df), PolarsPluginObject::NuExpression(expr) => { let res: NuExpression = expr.into_polars().dt().month().into(); res.to_pipeline_data(plugin, engine, call.head) } _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, ) -> Result<PipelineData, ShellError> { NuLazyFrame::new(false, lazy.to_polars().select([col("*").dt().month()])) .to_pipeline_data(plugin, engine, call.head) } fn command_eager( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let series = df.as_series(call.head)?; let casted = series.datetime().map_err(|e| ShellError::GenericError { error: "Error casting to datetime type".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })?; let res = casted.month().into_series(); let df = NuDataFrame::try_from_series_vec(vec![res], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command_with_decls; use nu_command::IntoDatetime; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command_with_decls(&GetMonth, vec![Box::new(IntoDatetime)]) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/datetime/get_weekday.rs
crates/nu_plugin_polars/src/dataframe/command/datetime/get_weekday.rs
use crate::{ PolarsPlugin, values::{ CustomValueSupport, NuDataFrame, NuExpression, NuLazyFrame, PolarsPluginObject, PolarsPluginType, cant_convert_err, }, }; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{Category, Example, LabeledError, PipelineData, ShellError, Signature, Span}; use polars::{ prelude::{DatetimeMethods, IntoSeries, NamedFrom, col}, series::Series, }; #[derive(Clone)] pub struct GetWeekDay; impl PluginCommand for GetWeekDay { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars get-weekday" } fn description(&self) -> &str { "Gets weekday from date." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ( PolarsPluginType::NuExpression.into(), PolarsPluginType::NuExpression.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Returns weekday from a date", example: r#"let dt = ('2020-08-04T16:39:18+00:00' | into datetime --timezone 'UTC'); let df = ([$dt $dt] | polars into-df); $df | polars get-weekday"#, result: Some( NuDataFrame::try_from_series( Series::new("0".into(), &[2i8, 2]), Span::test_data(), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, Example { description: "Returns weekday from a date", example: r#"let dt = ('2020-08-04T16:39:18+00:00' | into datetime --timezone 'UTC'); let df = ([$dt $dt] | polars into-df); $df | polars select (polars col 0 | polars get-weekday)"#, result: Some( NuDataFrame::try_from_series( Series::new("0".into(), &[2i8, 2]), Span::test_data(), ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }, ] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let metadata = input.metadata(); command(plugin, engine, call, input) .map_err(LabeledError::from) .map(|pd| pd.set_metadata(metadata)) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let value = input.into_value(call.head)?; match PolarsPluginObject::try_from_value(plugin, &value)? { PolarsPluginObject::NuLazyFrame(lazy) => command_lazy(plugin, engine, call, lazy), PolarsPluginObject::NuDataFrame(df) => command_eager(plugin, engine, call, df), PolarsPluginObject::NuExpression(expr) => { let res: NuExpression = expr.into_polars().dt().weekday().into(); res.to_pipeline_data(plugin, engine, call.head) } _ => Err(cant_convert_err( &value, &[ PolarsPluginType::NuDataFrame, PolarsPluginType::NuLazyFrame, PolarsPluginType::NuExpression, ], )), } } fn command_lazy( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, lazy: NuLazyFrame, ) -> Result<PipelineData, ShellError> { NuLazyFrame::new(false, lazy.to_polars().select([col("*").dt().weekday()])) .to_pipeline_data(plugin, engine, call.head) } fn command_eager( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, df: NuDataFrame, ) -> Result<PipelineData, ShellError> { let series = df.as_series(call.head)?; let casted = series.datetime().map_err(|e| ShellError::GenericError { error: "Error casting to datetime type".into(), msg: e.to_string(), span: Some(call.head), help: None, inner: vec![], })?; let res = casted.weekday().into_series(); let df = NuDataFrame::try_from_series_vec(vec![res], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command_with_decls; use nu_command::IntoDatetime; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command_with_decls(&GetWeekDay, vec![Box::new(IntoDatetime)]) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_polars/src/dataframe/command/index/arg_min.rs
crates/nu_plugin_polars/src/dataframe/command/index/arg_min.rs
use crate::{PolarsPlugin, values::CustomValueSupport}; use crate::values::{Column, NuDataFrame, PolarsPluginType}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, PipelineData, ShellError, Signature, Span, Value, }; use polars::prelude::{ArgAgg, IntoSeries, NewChunkedArray, UInt32Chunked}; #[derive(Clone)] pub struct ArgMin; impl PluginCommand for ArgMin { type Plugin = PolarsPlugin; fn name(&self) -> &str { "polars arg-min" } fn description(&self) -> &str { "Return index for min value in series." } fn search_terms(&self) -> Vec<&str> { vec!["argmin", "minimum", "least", "smallest", "lowest"] } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( PolarsPluginType::NuDataFrame.into(), PolarsPluginType::NuDataFrame.into(), ), ( PolarsPluginType::NuLazyFrame.into(), PolarsPluginType::NuLazyFrame.into(), ), ]) .category(Category::Custom("dataframe".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Returns index for min value", example: "[1 3 2] | polars into-df | polars arg-min", result: Some( NuDataFrame::try_from_columns( vec![Column::new("arg_min".to_string(), vec![Value::test_int(0)])], None, ) .expect("simple df for test should not fail") .into_value(Span::test_data()), ), }] } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { command(plugin, engine, call, input).map_err(LabeledError::from) } } fn command( plugin: &PolarsPlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, ShellError> { let df = NuDataFrame::try_from_pipeline_coerce(plugin, input, call.head)?; let series = df.as_series(call.head)?; let res = series.arg_min(); let chunked = match res { Some(index) => UInt32Chunked::from_slice("arg_min".into(), &[index as u32]), None => UInt32Chunked::from_slice("arg_min".into(), &[]), }; let res = chunked.into_series(); let df = NuDataFrame::try_from_series_vec(vec![res], call.head)?; df.to_pipeline_data(plugin, engine, call.head) } #[cfg(test)] mod test { use super::*; use crate::test::test_polars_plugin_command; #[test] fn test_examples() -> Result<(), ShellError> { test_polars_plugin_command(&ArgMin) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false