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-base/src/wrap_call.rs
crates/nu-cmd-base/src/wrap_call.rs
use nu_engine::CallExt; use nu_protocol::{ DeclId, FromValue, ShellError, Span, engine::{Call, EngineState, Stack, StateWorkingSet}, }; /// A helper utility to aid in implementing commands which have the same behavior for `run` and `run_const`. /// /// Only supports functions in [`Call`] and [`CallExt`] which have a `const` suffix. /// /// To use, the actual command logic should be moved to a function. Then, `eval` and `eval_const` can be implemented like this: /// ```rust /// # use nu_engine::command_prelude::*; /// # use nu_cmd_base::WrapCall; /// # fn do_command_logic(call: WrapCall) -> Result<PipelineData, ShellError> { Ok(PipelineData::empty()) } /// /// # struct Command {} /// # impl Command { /// fn run(&self, engine_state: &EngineState, stack: &mut Stack, call: &Call) -> Result<PipelineData, ShellError> { /// let call = WrapCall::Eval(engine_state, stack, call); /// do_command_logic(call) /// } /// /// fn run_const(&self, working_set: &StateWorkingSet, call: &Call) -> Result<PipelineData, ShellError> { /// let call = WrapCall::ConstEval(working_set, call); /// do_command_logic(call) /// } /// # } /// ``` /// /// Then, the typical [`Call`] and [`CallExt`] operations can be called using destructuring: /// /// ```rust /// # use nu_engine::command_prelude::*; /// # use nu_cmd_base::WrapCall; /// # let call = WrapCall::Eval(&EngineState::new(), &mut Stack::new(), &Call::new(Span::unknown())); /// # fn do_command_logic(call: WrapCall) -> Result<(), ShellError> { /// let (call, required): (_, String) = call.req(0)?; /// let (call, flag): (_, Option<i64>) = call.get_flag("number")?; /// # Ok(()) /// # } /// ``` /// /// A new `WrapCall` instance has to be returned after each function to ensure /// that there is only ever one copy of mutable [`Stack`] reference. pub enum WrapCall<'a> { Eval(&'a EngineState, &'a mut Stack, &'a Call<'a>), ConstEval(&'a StateWorkingSet<'a>, &'a Call<'a>), } /// Macro to choose between the non-const and const versions of each [`Call`]/[`CallExt`] function macro_rules! proxy { ($self:ident , $eval:ident , $const:ident , $( $args:expr ),*) => { match $self { WrapCall::Eval(engine_state, stack, call) => { Call::$eval(call, engine_state, stack, $( $args ),*) .map(|val| (WrapCall::Eval(engine_state, stack, call), val)) }, WrapCall::ConstEval(working_set, call) => { Call::$const(call, working_set, $( $args ),*) .map(|val| (WrapCall::ConstEval(working_set, call), val)) }, } }; } impl WrapCall<'_> { pub fn head(&self) -> Span { match self { WrapCall::Eval(_, _, call) => call.head, WrapCall::ConstEval(_, call) => call.head, } } pub fn decl_id(&self) -> DeclId { match self { WrapCall::Eval(_, _, call) => call.decl_id, WrapCall::ConstEval(_, call) => call.decl_id, } } pub fn has_flag<T: FromValue>(self, flag_name: &str) -> Result<(Self, bool), ShellError> { proxy!(self, has_flag, has_flag_const, flag_name) } pub fn get_flag<T: FromValue>(self, name: &str) -> Result<(Self, Option<T>), ShellError> { proxy!(self, get_flag, get_flag_const, name) } pub fn req<T: FromValue>(self, pos: usize) -> Result<(Self, T), ShellError> { proxy!(self, req, req_const, pos) } pub fn rest<T: FromValue>(self, pos: usize) -> Result<(Self, Vec<T>), ShellError> { proxy!(self, rest, rest_const, pos) } pub fn opt<T: FromValue>(self, pos: usize) -> Result<(Self, Option<T>), ShellError> { proxy!(self, opt, opt_const, pos) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-base/src/formats/mod.rs
crates/nu-cmd-base/src/formats/mod.rs
pub mod to;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-base/src/formats/to/mod.rs
crates/nu-cmd-base/src/formats/to/mod.rs
pub mod delimited;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-base/src/formats/to/delimited.rs
crates/nu-cmd-base/src/formats/to/delimited.rs
use indexmap::{IndexSet, indexset}; use nu_protocol::Value; pub fn merge_descriptors(values: &[Value]) -> Vec<String> { let mut ret: Vec<String> = vec![]; let mut seen: IndexSet<String> = indexset! {}; for value in values { let data_descriptors = match value { Value::Record { val, .. } => val.columns().cloned().collect(), _ => vec!["".to_string()], }; for desc in data_descriptors { if !desc.is_empty() && !seen.contains(&desc) { seen.insert(desc.to_string()); ret.push(desc.to_string()); } } } ret }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-lsp/src/ast.rs
crates/nu-lsp/src/ast.rs
use crate::Id; use nu_protocol::{ DeclId, ModuleId, Span, ast::{Argument, Block, Call, Expr, Expression, FindMapResult, ListItem, PathMember, Traverse}, engine::StateWorkingSet, }; use std::sync::Arc; /// Adjust span if quoted fn strip_quotes(span: Span, working_set: &StateWorkingSet) -> (Box<[u8]>, Span) { let text = working_set.get_span_contents(span); if text.len() > 1 && ((text.starts_with(b"\"") && text.ends_with(b"\"")) || (text.starts_with(b"'") && text.ends_with(b"'"))) { ( text.get(1..text.len() - 1) .expect("Invalid quoted span!") .into(), Span::new(span.start.saturating_add(1), span.end.saturating_sub(1)), ) } else { (text.into(), span) } } /// Trim leading `$` sign For variable references `$foo` fn strip_dollar_sign(span: Span, working_set: &StateWorkingSet<'_>) -> (Box<[u8]>, Span) { let content = working_set.get_span_contents(span); if content.starts_with(b"$") { ( content[1..].into(), Span::new(span.start.saturating_add(1), span.end), ) } else { (content.into(), span) } } /// For a command call with head span content of `module name command name`, /// return the span of `command name`, /// while the actual command name is simply `command name` fn command_name_span_from_call_head( working_set: &StateWorkingSet, decl_id: DeclId, head_span: Span, ) -> Span { let name = working_set.get_decl(decl_id).name(); // shortcut for most cases if name.len() == head_span.end.saturating_sub(head_span.start) { return head_span; } let head_content = working_set.get_span_contents(head_span); let mut head_words = head_content.split(|c| *c == b' ').collect::<Vec<_>>(); let mut name_words = name.split(' ').collect::<Vec<_>>(); let mut matched_len = name_words.len() - 1; while let Some(name_word) = name_words.pop() { while let Some(head_word) = head_words.pop() { // for extra spaces, like those in the `command name` example if head_word.is_empty() && !name_word.is_empty() { matched_len += 1; continue; } if name_word.as_bytes() == head_word { matched_len += head_word.len(); break; } else { // no such command name substring in head span // probably an alias command, returning the whole head span return head_span; } } if name_words.len() > head_words.len() { return head_span; } } Span::new(head_span.end.saturating_sub(matched_len), head_span.end) } fn try_find_id_in_misc( call: &Call, working_set: &StateWorkingSet, location: Option<&usize>, id_ref: Option<&Id>, ) -> Option<(Id, Span)> { let call_name = working_set.get_decl(call.decl_id).name(); match call_name { "def" | "export def" => try_find_id_in_def(call, working_set, location, id_ref), "module" | "export module" => try_find_id_in_mod(call, working_set, location, id_ref), "use" | "export use" | "hide" => try_find_id_in_use(call, working_set, location, id_ref), "overlay use" | "overlay hide" => { try_find_id_in_overlay(call, working_set, location, id_ref) } _ => None, } } /// For situations like /// ```nushell /// def foo [] {} /// # |__________ location /// ``` /// `def` is an internal call with name/signature/closure as its arguments /// /// # Arguments /// - `location`: None if no `contains` check required /// - `id`: None if no id equal check required fn try_find_id_in_def( call: &Call, working_set: &StateWorkingSet, location: Option<&usize>, id_ref: Option<&Id>, ) -> Option<(Id, Span)> { // skip if the id to search is not a declaration id if let Some(id_ref) = id_ref && !matches!(id_ref, Id::Declaration(_)) { return None; } let mut span = None; for arg in call.arguments.iter() { if location.is_none_or(|pos| arg.span().contains(*pos)) { // String means this argument is the name if let Argument::Positional(expr) = arg && let Expr::String(_) = &expr.expr { span = Some(expr.span); break; } // if we do care the location, // reaching here means this argument is not the name if location.is_some() { return None; } } } let block_span_of_this_def = call.positional_iter().last()?.span; let decl_on_spot = |decl_id: &DeclId| -> bool { working_set .get_decl(*decl_id) .block_id() .and_then(|block_id| working_set.get_block(block_id).span) .is_some_and(|block_span| block_span == block_span_of_this_def) }; let (_, span) = strip_quotes(span?, working_set); let id_found = if let Some(id_r) = id_ref { let Id::Declaration(decl_id_ref) = id_r else { return None; }; decl_on_spot(decl_id_ref).then_some(id_r.clone())? } else { // Find declaration by name, e.g. `workspace.find_decl`, is not reliable // considering shadowing and overlay prefixes // TODO: get scope by position // https://github.com/nushell/nushell/issues/15291 Id::Declaration((0..working_set.num_decls()).rev().find_map(|id| { let decl_id = DeclId::new(id); decl_on_spot(&decl_id).then_some(decl_id) })?) }; Some((id_found, span)) } /// For situations like /// ```nushell /// module foo {} /// # |__________ location /// ``` /// `module` is an internal call with name/signature/closure as its arguments /// /// # Arguments /// - `location`: None if no `contains` check required /// - `id`: None if no id equal check required fn try_find_id_in_mod( call: &Call, working_set: &StateWorkingSet, location: Option<&usize>, id_ref: Option<&Id>, ) -> Option<(Id, Span)> { // skip if the id to search is not a module id if let Some(id_ref) = id_ref && !matches!(id_ref, Id::Module(_, _)) { return None; } let check_location = |span: &Span| location.is_none_or(|pos| span.contains(*pos)); call.arguments.first().and_then(|arg| { if !check_location(&arg.span()) { return None; } match arg { Argument::Positional(expr) => { let name = expr.as_string()?; let module_id = working_set.find_module(name.as_bytes()).or_else(|| { // in case the module is hidden let mut any_id = true; let mut id_num_ref = 0; if let Some(Id::Module(id_ref, _)) = id_ref { any_id = false; id_num_ref = id_ref.get(); } let block_span = call.arguments.last()?.span(); (0..working_set.num_modules()) .rfind(|id| { (any_id || id_num_ref == *id) && working_set.get_module(ModuleId::new(*id)).span.is_some_and( |mod_span| { mod_span.start <= block_span.start + 1 && block_span.start <= mod_span.start && block_span.end >= mod_span.end && block_span.end <= mod_span.end + 1 }, ) }) .map(ModuleId::new) })?; let found_id = Id::Module(module_id, name.as_bytes().into()); let found_span = strip_quotes(arg.span(), working_set).1; id_ref .is_none_or(|id_r| found_id == *id_r) .then_some((found_id, found_span)) } _ => None, } }) } /// Find id in use/hide command /// `hide foo.nu bar` or `use foo.nu [bar baz]` /// /// # Arguments /// - `location`: None if no `contains` check required /// - `id`: None if no id equal check required fn try_find_id_in_use( call: &Call, working_set: &StateWorkingSet, location: Option<&usize>, id_ref: Option<&Id>, ) -> Option<(Id, Span)> { // NOTE: `call.parser_info` contains a 'import_pattern' field for `use`/`hide` commands, // If it's missing, usually it means the PWD env is not correctly set, // checkout `new_engine_state` in lib.rs let Expression { expr: Expr::ImportPattern(import_pattern), .. } = call.get_parser_info("import_pattern")? else { return None; }; let module_id = import_pattern.head.id?; let find_by_name = |name: &[u8]| { let module = working_set.get_module(module_id); match id_ref { Some(Id::Variable(var_id_ref, name_ref)) => module .constants .get(name) .cloned() .or_else(|| { // NOTE: This is for the module record variable: // https://www.nushell.sh/book/modules/using_modules.html#importing-constants // The definition span is located at the head of the `use` command. (name_ref.as_ref() == name && call .head .contains_span(working_set.get_variable(*var_id_ref).declaration_span)) .then_some(*var_id_ref) }) .and_then(|var_id| { (var_id == *var_id_ref).then_some(Id::Variable(var_id, name.into())) }), Some(Id::Declaration(decl_id_ref)) => module.decls.get(name).and_then(|decl_id| { (*decl_id == *decl_id_ref).then_some(Id::Declaration(*decl_id)) }), // this is only for argument `members` Some(Id::Module(module_id_ref, name_ref)) => { module.submodules.get(name).and_then(|module_id| { (*module_id == *module_id_ref && name_ref.as_ref() == name) .then_some(Id::Module(*module_id, name.into())) }) } None => module .submodules .get(name) .map(|id| Id::Module(*id, name.into())) .or(module.decls.get(name).cloned().map(Id::Declaration)) .or(module .constants .get(name) .map(|id| Id::Variable(*id, name.into()))), _ => None, } }; let check_location = |span: &Span| location.is_none_or(|pos| span.contains(*pos)); // Get module id if required let module_name = call.arguments.first()?; let span = module_name.span(); let (span_content, clean_span) = strip_quotes(span, working_set); if let Some(Id::Module(id_ref, name_ref)) = id_ref { // still need to check the rest, if id not matched if module_id == *id_ref && name_ref == &span_content { return Some((Id::Module(module_id, span_content), clean_span)); } } if let Some(pos) = location { // first argument of `use`/`hide` should always be module name if span.contains(*pos) { return Some((Id::Module(module_id, span_content), clean_span)); } } let search_in_list_items = |items: &Vec<ListItem>| { items.iter().find_map(|item| { let item_expr = item.expr(); check_location(&item_expr.span) .then_some(item_expr) .and_then(|e| { let name = e.as_string()?; Some(( find_by_name(name.as_bytes())?, strip_quotes(item_expr.span, working_set).1, )) }) }) }; for arg in call.arguments.get(1..)?.iter().rev() { let Argument::Positional(expr) = arg else { continue; }; if !check_location(&expr.span) { continue; } let matched = match &expr.expr { Expr::String(name) => { find_by_name(name.as_bytes()).map(|id| (id, strip_quotes(expr.span, working_set).1)) } Expr::List(items) => search_in_list_items(items), Expr::FullCellPath(fcp) => { let Expr::List(items) = &fcp.head.expr else { return None; }; search_in_list_items(items) } _ => None, }; if matched.is_some() || location.is_some() { return matched; } } None } /// Find id in use/hide command /// /// TODO: rename of `overlay use as new_name`, `overlay use --prefix` /// /// # Arguments /// - `location`: None if no `contains` check required /// - `id`: None if no id equal check required fn try_find_id_in_overlay( call: &Call, working_set: &StateWorkingSet, location: Option<&usize>, id_ref: Option<&Id>, ) -> Option<(Id, Span)> { // skip if the id to search is not a module id if let Some(id_ref) = id_ref && !matches!(id_ref, Id::Module(_, _)) { return None; } let check_location = |span: &Span| location.is_none_or(|pos| span.contains(*pos)); let module_from_parser_info = |span: Span, name: &str| { let Expression { expr: Expr::Overlay(Some(module_id)), .. } = call.get_parser_info("overlay_expr")? else { return None; }; let found_id = Id::Module(*module_id, name.as_bytes().into()); id_ref .is_none_or(|id_r| found_id == *id_r) .then_some((found_id, strip_quotes(span, working_set).1)) }; // NOTE: `overlay_expr` doesn't exist for `overlay hide` let module_from_overlay_name = |name: &str, span: Span| { let found_id = Id::Module( working_set.find_overlay(name.as_bytes())?.origin, name.as_bytes().into(), ); id_ref .is_none_or(|id_r| found_id == *id_r) .then_some((found_id, strip_quotes(span, working_set).1)) }; // check `as alias` first for arg in call.arguments.iter().rev() { let Argument::Positional(expr) = arg else { continue; }; if !check_location(&expr.span) { continue; }; let matched = match &expr.expr { Expr::String(name) => module_from_parser_info(expr.span, name) .or_else(|| module_from_overlay_name(name, expr.span)), // keyword 'as' Expr::Keyword(kwd) => match &kwd.expr.expr { Expr::String(name) => module_from_parser_info(kwd.expr.span, name) .or_else(|| module_from_overlay_name(name, kwd.expr.span)), _ => None, }, _ => None, }; if matched.is_some() || location.is_some() { return matched; } } None } fn find_id_in_expr( expr: &Expression, working_set: &StateWorkingSet, location: &usize, ) -> FindMapResult<(Id, Span)> { // skip the entire expression if the location is not in it if !expr.span.contains(*location) { return FindMapResult::Stop; } let span = expr.span; match &expr.expr { Expr::VarDecl(var_id) | Expr::Var(var_id) => { let (name, clean_span) = strip_dollar_sign(span, working_set); FindMapResult::Found((Id::Variable(*var_id, name), clean_span)) } Expr::Call(call) => { if call.head.contains(*location) { let span = command_name_span_from_call_head(working_set, call.decl_id, call.head); FindMapResult::Found((Id::Declaration(call.decl_id), span)) } else { try_find_id_in_misc(call, working_set, Some(location), None) .map(FindMapResult::Found) .unwrap_or_default() } } Expr::ExternalCall(head, _) => { if head.span.contains(*location) && let Expr::GlobPattern(cmd, _) = &head.expr { return FindMapResult::Found((Id::External(cmd.clone()), head.span)); } FindMapResult::Continue } Expr::FullCellPath(fcp) => { if fcp.head.span.contains(*location) { FindMapResult::Continue } else { let Expression { expr: Expr::Var(var_id), .. } = fcp.head else { return FindMapResult::Continue; }; let tail: Vec<PathMember> = fcp .tail .clone() .into_iter() .take_while(|pm| pm.span().start <= *location) .collect(); let Some(span) = tail.last().map(|pm| pm.span()) else { return FindMapResult::Stop; }; FindMapResult::Found((Id::CellPath(var_id, tail), span)) } } Expr::Overlay(Some(module_id)) => { FindMapResult::Found((Id::Module(*module_id, [].into()), span)) } // terminal value expressions Expr::Bool(_) | Expr::Binary(_) | Expr::DateTime(_) | Expr::Directory(_, _) | Expr::Filepath(_, _) | Expr::Float(_) | Expr::Garbage | Expr::GlobPattern(_, _) | Expr::Int(_) | Expr::Nothing | Expr::RawString(_) | Expr::Signature(_) | Expr::String(_) => FindMapResult::Found((Id::Value(expr.ty.clone()), span)), _ => FindMapResult::Continue, } } /// find the leaf node at the given location from ast pub(crate) fn find_id( ast: &Arc<Block>, working_set: &StateWorkingSet, location: &usize, ) -> Option<(Id, Span)> { let closure = |e| find_id_in_expr(e, working_set, location); ast.find_map(working_set, &closure) } fn find_reference_by_id_in_expr( expr: &Expression, working_set: &StateWorkingSet, id: &Id, ) -> Vec<Span> { match (&expr.expr, id) { (Expr::Var(vid1), Id::Variable(vid2, _)) if *vid1 == *vid2 => vec![Span::new( // we want to exclude the `$` sign for renaming expr.span.start.saturating_add(1), expr.span.end, )], (Expr::VarDecl(vid1), Id::Variable(vid2, _)) if *vid1 == *vid2 => vec![expr.span], // also interested in `var_id` in call.arguments of `use` command // and `module_id` in `module` command (Expr::Call(call), _) => match id { Id::Declaration(decl_id) if call.decl_id == *decl_id => { vec![command_name_span_from_call_head( working_set, call.decl_id, call.head, )] } // Check for misc matches (use, module, etc.) _ => try_find_id_in_misc(call, working_set, None, Some(id)) .map(|(_, span_found)| span_found) .into_iter() .collect::<Vec<_>>(), }, _ => vec![], } } pub(crate) fn find_reference_by_id( ast: &Arc<Block>, working_set: &StateWorkingSet, id: &Id, ) -> Vec<Span> { let mut results = Vec::new(); let closure = |e| find_reference_by_id_in_expr(e, working_set, id); ast.flat_map(working_set, &closure, &mut results); results }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-lsp/src/workspace.rs
crates/nu-lsp/src/workspace.rs
use crate::{ Id, LanguageServer, ast::{self, find_id, find_reference_by_id}, path_to_uri, span_to_range, uri_to_path, }; use lsp_textdocument::FullTextDocument; use lsp_types::{ DocumentHighlight, DocumentHighlightKind, DocumentHighlightParams, Location, PrepareRenameResponse, ProgressToken, Range, ReferenceParams, RenameParams, TextDocumentPositionParams, TextEdit, Uri, WorkspaceEdit, WorkspaceFolder, }; use miette::{IntoDiagnostic, Result, miette}; use nu_glob::Uninterruptible; use nu_protocol::{ Span, engine::{EngineState, StateWorkingSet}, }; use std::{ collections::{BTreeMap, HashMap, HashSet}, fs, path::Path, sync::Arc, }; /// Message type indicating ranges of interest in each doc #[derive(Debug)] pub(crate) struct RangePerDoc { pub uri: Uri, pub ranges: Vec<Range>, } /// Message sent from background thread to main #[derive(Debug)] pub(crate) enum InternalMessage { RangeMessage(RangePerDoc), Cancelled(ProgressToken), Finished(ProgressToken), OnGoing(ProgressToken, u32), } fn find_nu_scripts_in_folder(folder_uri: &Uri) -> Result<nu_glob::Paths> { let path = uri_to_path(folder_uri); if !path.is_dir() { return Err(miette!("\nworkspace folder does not exist.")); } let pattern = format!("{}/**/*.nu", path.to_string_lossy()); nu_glob::glob(&pattern, Uninterruptible).into_diagnostic() } /// HACK: when current file is imported (use keyword) by others in the workspace, /// it will get parsed a second time via `parse_module_block`, so that its definitions' /// ids are renewed, making it harder to track the references. /// /// FIXME: cross-file shadowing can still cause false-positive/false-negative cases /// /// This is a workaround to track the new id struct IDTracker { /// ID to search, renewed on `parse_module_block` pub id: Id, /// Span of the original instance under the cursor pub span: Span, /// Name of the definition pub name: Box<[u8]>, /// Span of the original file where the request comes from pub file_span: Span, /// The redundant parsing should only happen once pub renewed: bool, } impl IDTracker { fn new(id: Id, span: Span, file_span: Span, working_set: &StateWorkingSet) -> Self { let name = match &id { Id::Variable(_, name) | Id::Module(_, name) => name.clone(), // NOTE: search by the canonical command name, some weird aliasing will be missing Id::Declaration(decl_id) => working_set.get_decl(*decl_id).name().as_bytes().into(), _ => working_set.get_span_contents(span).into(), }; Self { id, span, name, file_span, renewed: false, } } } impl LanguageServer { /// Get initial workspace folders from initialization response pub(crate) fn initialize_workspace_folders( &mut self, init_params: serde_json::Value, ) -> Option<()> { if let Some(array) = init_params.get("workspaceFolders") { let folders: Vec<WorkspaceFolder> = serde_json::from_value(array.clone()).ok()?; for folder in folders { self.workspace_folders.insert(folder.name.clone(), folder); } } Some(()) } /// Highlight all occurrences of the text at cursor, in current file pub(crate) fn document_highlight( &mut self, params: &DocumentHighlightParams, ) -> Option<Vec<DocumentHighlight>> { let path_uri = &params.text_document_position_params.text_document.uri; let mut engine_state = self.new_engine_state(Some(path_uri)); let (block, file_span, working_set) = self.parse_file(&mut engine_state, path_uri, false)?; let docs = &self.docs.lock().ok()?; let file = docs.get_document(path_uri)?; let location = file.offset_at(params.text_document_position_params.position) as usize + file_span.start; let (id, cursor_span) = find_id(&block, &working_set, &location)?; let mut refs = find_reference_by_id(&block, &working_set, &id); let definition_span = Self::find_definition_span_by_id(&working_set, &id); if let Some(extra_span) = Self::reference_not_in_ast(&id, &working_set, definition_span, file_span, cursor_span) && !refs.contains(&extra_span) { refs.push(extra_span); } Some( refs.iter() .map(|span| DocumentHighlight { range: span_to_range(span, file, file_span.start), kind: Some(DocumentHighlightKind::TEXT), }) .collect(), ) } /// The rename request only happens after the client received a `PrepareRenameResponse`, /// and a new name typed in, could happen before ranges ready for all files in the workspace folder pub(crate) fn rename(&mut self, params: &RenameParams) -> Option<WorkspaceEdit> { // changes in WorkspaceEdit have mutable key #[allow(clippy::mutable_key_type)] let changes: HashMap<Uri, Vec<TextEdit>> = self .occurrences .iter() .map(|(uri, ranges)| { ( uri.clone(), ranges .iter() .map(|range| TextEdit { range: *range, new_text: params.new_name.to_owned(), }) .collect(), ) }) .collect(); Some(WorkspaceEdit { changes: Some(changes), ..Default::default() }) } /// Goto references response /// # Arguments /// - `timeout`: timeout in milliseconds, when timeout /// 1. Respond with all ranges found so far /// 2. Cancel the background thread pub(crate) fn references( &mut self, params: &ReferenceParams, timeout: u128, ) -> Option<Vec<Location>> { self.occurrences = BTreeMap::new(); // start with a clean engine state self.need_parse = true; let path_uri = &params.text_document_position.text_document.uri; let mut engine_state = self.new_engine_state(Some(path_uri)); let (mut working_set, id, span, file_span) = self .parse_and_find( &mut engine_state, path_uri, params.text_document_position.position, ) .ok()?; let mut id_tracker = IDTracker::new(id.clone(), span, file_span, &working_set); let Some(workspace_uri) = self .get_workspace_folder_by_uri(path_uri) .map(|folder| folder.uri.clone()) else { let definition_span = Self::find_definition_span_by_id(&working_set, &id); return Some( Self::find_reference_in_file( &mut working_set, self.docs.lock().ok()?.get_document(path_uri)?, uri_to_path(path_uri).as_path(), &mut id_tracker, definition_span, ) .into_iter() .map(|range| Location { uri: path_uri.clone(), range, }) .collect(), ); }; let token = params .work_done_progress_params .work_done_token .clone() .unwrap_or(ProgressToken::Number(1)); // make sure the parsing result of current file is merged in the state let engine_state = self.new_engine_state(Some(path_uri)); self.channels = self .find_reference_in_workspace( engine_state, workspace_uri, token.clone(), "Finding references ...".to_string(), id_tracker, ) .ok(); // TODO: WorkDoneProgress -> PartialResults for quicker response // currently not enabled by `lsp_types` but hackable in `server_capabilities` json let time_start = std::time::Instant::now(); loop { if self.handle_internal_messages().ok()? { break; } if time_start.elapsed().as_millis() > timeout { self.send_progress_end(token, Some("Timeout".to_string())) .ok()?; self.cancel_background_thread(); self.channels = None; break; } } Some( self.occurrences .iter() .flat_map(|(uri, ranges)| { ranges.iter().map(|range| Location { uri: uri.clone(), range: *range, }) }) .collect(), ) } /// 1. Parse current file to find the content at the cursor that is suitable for a workspace wide renaming /// 2. Parse all nu scripts in the same workspace folder, with the variable/command name in it. /// 3. Store the results in `self.occurrences` for later rename quest pub(crate) fn prepare_rename(&mut self, request: lsp_server::Request) -> Result<()> { let params: TextDocumentPositionParams = serde_json::from_value(request.params).into_diagnostic()?; self.occurrences = BTreeMap::new(); // start with a clean engine state self.need_parse = true; let path_uri = &params.text_document.uri; let mut engine_state = self.new_engine_state(Some(path_uri)); let (mut working_set, id, span, file_span) = self.parse_and_find(&mut engine_state, path_uri, params.position)?; if let Id::Value(_) = id { return Err(miette!("\nRename only works for variable/command.")); } if Self::find_definition_span_by_id(&working_set, &id).is_none() { return Err(miette!( "\nDefinition not found.\nNot allowed to rename built-ins." )); } let docs = match self.docs.lock() { Ok(it) => it, Err(err) => return Err(miette!(err.to_string())), }; let file = docs .get_document(path_uri) .ok_or_else(|| miette!("\nFailed to get document"))?; let range = span_to_range(&span, file, file_span.start); let response = PrepareRenameResponse::Range(range); self.connection .sender .send(lsp_server::Message::Response(lsp_server::Response { id: request.id, result: serde_json::to_value(response).ok(), error: None, })) .into_diagnostic()?; let mut id_tracker = IDTracker::new(id.clone(), span, file_span, &working_set); let Some(workspace_uri) = self .get_workspace_folder_by_uri(path_uri) .map(|folder| folder.uri.clone()) else { let definition_span = Self::find_definition_span_by_id(&working_set, &id); self.occurrences.insert( path_uri.clone(), Self::find_reference_in_file( &mut working_set, file, uri_to_path(path_uri).as_path(), &mut id_tracker, definition_span, ), ); return Ok(()); }; // now continue parsing on other files in the workspace // make sure the parsing result of current file is merged in the state let engine_state = self.new_engine_state(Some(path_uri)); self.channels = self .find_reference_in_workspace( engine_state, workspace_uri, ProgressToken::Number(0), "Preparing rename ...".to_string(), id_tracker, ) .ok(); Ok(()) } fn find_reference_in_file( working_set: &mut StateWorkingSet, file: &FullTextDocument, fp: &Path, id_tracker: &mut IDTracker, definition_span: Option<Span>, ) -> Vec<Range> { let block = nu_parser::parse( working_set, fp.to_str(), file.get_content(None).as_bytes(), false, ); // NOTE: Renew the id if there's a module with the same span as the original file. // This requires that the initial parsing results get merged in the engine_state. // Pay attention to the `self.need_parse = true` and `merge_delta` assignments // in function `prepare_rename`/`references` if (!id_tracker.renewed) && working_set .find_module_by_span(id_tracker.file_span) .is_some() { if let Some(new_block) = working_set.find_block_by_span(id_tracker.file_span) && let Some((new_id, _)) = ast::find_id(&new_block, working_set, &id_tracker.span.start) { id_tracker.id = new_id; } id_tracker.renewed = true; } let mut refs: Vec<Span> = find_reference_by_id(&block, working_set, &id_tracker.id); let file_span = working_set .get_span_for_filename(fp.to_string_lossy().as_ref()) .unwrap_or(Span::unknown()); if let Some(extra_span) = Self::reference_not_in_ast( &id_tracker.id, working_set, definition_span, file_span, id_tracker.span, ) && !refs.contains(&extra_span) { refs.push(extra_span) } // add_block to avoid repeated parsing working_set.add_block(block); refs.iter() .map(|span| span_to_range(span, file, file_span.start)) .collect() } /// NOTE: for arguments whose declaration is in a signature /// which is not covered in the AST fn reference_not_in_ast( id: &Id, working_set: &StateWorkingSet, definition_span: Option<Span>, file_span: Span, sample_span: Span, ) -> Option<Span> { if let (Id::Variable(_, name_ref), Some(decl_span)) = (&id, definition_span) && file_span.contains_span(decl_span) && decl_span.end > decl_span.start { let content = working_set.get_span_contents(decl_span); let leading_dashes = content .iter() // remove leading dashes for flags .take_while(|c| *c == &b'-') .count(); let start = decl_span.start + leading_dashes; return content.get(leading_dashes..).and_then(|name| { name.starts_with(name_ref).then_some(Span { start, end: start + sample_span.end - sample_span.start, }) }); } None } /// Time consuming task running in a background thread /// communicating with the main thread using `InternalMessage` fn find_reference_in_workspace( &self, engine_state: EngineState, workspace_uri: Uri, token: ProgressToken, message: String, mut id_tracker: IDTracker, ) -> Result<( crossbeam_channel::Sender<bool>, Arc<crossbeam_channel::Receiver<InternalMessage>>, )> { let (data_sender, data_receiver) = crossbeam_channel::unbounded::<InternalMessage>(); let (cancel_sender, cancel_receiver) = crossbeam_channel::bounded::<bool>(1); let engine_state = Arc::new(engine_state); let text_documents = self.docs.clone(); self.send_progress_begin(token.clone(), message)?; std::thread::spawn(move || -> Result<()> { let mut working_set = StateWorkingSet::new(&engine_state); let mut scripts: HashSet<_> = match find_nu_scripts_in_folder(&workspace_uri) { Ok(it) => it, Err(_) => { data_sender .send(InternalMessage::Cancelled(token.clone())) .ok(); return Ok(()); } } .filter_map(|p| p.ok()) .collect(); // For unsaved new files let mut opened_scripts = HashSet::new(); let docs = match text_documents.lock() { Ok(it) => it, Err(err) => return Err(miette!(err.to_string())), }; for uri in docs.documents().keys() { let fp = uri_to_path(uri); opened_scripts.insert(fp.clone()); scripts.insert(fp); } drop(docs); let len = scripts.len(); let definition_span = Self::find_definition_span_by_id(&working_set, &id_tracker.id); let bytes_to_search = id_tracker.name.to_owned(); let finder = memchr::memmem::Finder::new(&bytes_to_search); for (i, fp) in scripts.iter().enumerate() { #[cfg(test)] std::thread::sleep(std::time::Duration::from_millis(200)); // cancel the loop on cancellation message from main thread if cancel_receiver.try_recv().is_ok() { data_sender .send(InternalMessage::Cancelled(token.clone())) .into_diagnostic()?; return Ok(()); } let percentage = (i * 100 / len) as u32; let uri = path_to_uri(fp); let file = if opened_scripts.contains(fp) { let docs = match text_documents.lock() { Ok(it) => it, Err(err) => return Err(miette!(err.to_string())), }; let Some(file) = docs.get_document(&uri) else { continue; }; let doc_copy = FullTextDocument::new("nu".to_string(), 0, file.get_content(None).into()); drop(docs); doc_copy } else { let file_bytes = match fs::read(fp) { Ok(it) => it, Err(_) => { // continue on fs error continue; } }; // skip if the file does not contain what we're looking for if finder.find(&file_bytes).is_none() { // progress without any data data_sender .send(InternalMessage::OnGoing(token.clone(), percentage)) .into_diagnostic()?; continue; } FullTextDocument::new( "nu".to_string(), 0, String::from_utf8_lossy(&file_bytes).into(), ) }; let ranges = Self::find_reference_in_file( &mut working_set, &file, fp, &mut id_tracker, definition_span, ); data_sender .send(InternalMessage::RangeMessage(RangePerDoc { uri, ranges })) .ok(); data_sender .send(InternalMessage::OnGoing(token.clone(), percentage)) .ok(); } data_sender .send(InternalMessage::Finished(token)) .into_diagnostic() }); Ok((cancel_sender, Arc::new(data_receiver))) } fn get_workspace_folder_by_uri(&self, uri: &Uri) -> Option<&WorkspaceFolder> { let uri_string = uri.to_string(); self.workspace_folders.iter().find_map(|(_, folder)| { uri_string .starts_with(&folder.uri.to_string()) .then_some(folder) }) } } #[cfg(test)] mod tests { use crate::path_to_uri; use crate::tests::{initialize_language_server, open, open_unchecked, send_hover_request}; use assert_json_diff::assert_json_eq; use lsp_server::{Connection, Message}; use lsp_types::notification::{LogMessage, Notification, Progress}; use lsp_types::{ DocumentHighlightParams, InitializeParams, PartialResultParams, Position, ReferenceContext, ReferenceParams, RenameParams, TextDocumentIdentifier, TextDocumentPositionParams, Uri, WorkDoneProgressParams, WorkspaceFolder, request, request::Request, }; use nu_test_support::fs::fixtures; use rstest::rstest; // Helper functions to reduce JSON duplication fn make_range( start_line: u32, start_char: u32, end_line: u32, end_char: u32, ) -> serde_json::Value { serde_json::json!({ "start": { "line": start_line, "character": start_char }, "end": { "line": end_line, "character": end_char } }) } fn make_location_ref( uri_suffix: &str, start_line: u32, start_char: u32, end_line: u32, end_char: u32, ) -> serde_json::Value { serde_json::json!({ "uri": uri_suffix, "range": make_range(start_line, start_char, end_line, end_char) }) } fn make_text_edit( start_line: u32, start_char: u32, end_line: u32, end_char: u32, ) -> serde_json::Value { serde_json::json!({ "range": make_range(start_line, start_char, end_line, end_char), "newText": "new" }) } fn make_highlight( start_line: u32, start_char: u32, end_line: u32, end_char: u32, ) -> serde_json::Value { serde_json::json!({ "range": make_range(start_line, start_char, end_line, end_char), "kind": 1 }) } fn send_reference_request( client_connection: &Connection, uri: Uri, line: u32, character: u32, num: usize, ) -> Vec<Message> { client_connection .sender .send(Message::Request(lsp_server::Request { id: 1.into(), method: request::References::METHOD.to_string(), params: serde_json::to_value(ReferenceParams { text_document_position: TextDocumentPositionParams { text_document: TextDocumentIdentifier { uri }, position: Position { line, character }, }, context: ReferenceContext { include_declaration: true, }, partial_result_params: PartialResultParams::default(), work_done_progress_params: WorkDoneProgressParams::default(), }) .unwrap(), })) .unwrap(); (0..num) .map(|_| { client_connection .receiver .recv_timeout(std::time::Duration::from_secs(2)) .unwrap() }) .collect() } fn send_rename_prepare_request( client_connection: &Connection, uri: Uri, line: u32, character: u32, num: usize, immediate_cancellation: bool, ) -> Vec<Message> { client_connection .sender .send(Message::Request(lsp_server::Request { id: 1.into(), method: request::PrepareRenameRequest::METHOD.to_string(), params: serde_json::to_value(TextDocumentPositionParams { text_document: TextDocumentIdentifier { uri: uri.clone() }, position: Position { line, character }, }) .unwrap(), })) .unwrap(); // use a hover request to interrupt if immediate_cancellation { send_hover_request(client_connection, uri, line, character); } (0..num) .map(|_| { client_connection .receiver .recv_timeout(std::time::Duration::from_secs(2)) .unwrap() }) .collect() } fn send_rename_request( client_connection: &Connection, uri: Uri, line: u32, character: u32, ) -> Message { client_connection .sender .send(Message::Request(lsp_server::Request { id: 1.into(), method: request::Rename::METHOD.to_string(), params: serde_json::to_value(RenameParams { text_document_position: TextDocumentPositionParams { text_document: TextDocumentIdentifier { uri }, position: Position { line, character }, }, new_name: "new".to_string(), work_done_progress_params: WorkDoneProgressParams::default(), }) .unwrap(), })) .unwrap(); client_connection .receiver .recv_timeout(std::time::Duration::from_secs(2)) .unwrap() } fn send_document_highlight_request( client_connection: &Connection, uri: Uri, line: u32, character: u32, ) -> Message { client_connection .sender .send(Message::Request(lsp_server::Request { id: 1.into(), method: request::DocumentHighlightRequest::METHOD.to_string(), params: serde_json::to_value(DocumentHighlightParams { text_document_position_params: TextDocumentPositionParams { text_document: TextDocumentIdentifier { uri }, position: Position { line, character }, }, partial_result_params: PartialResultParams::default(), work_done_progress_params: WorkDoneProgressParams::default(), }) .unwrap(), })) .unwrap(); client_connection .receiver .recv_timeout(std::time::Duration::from_secs(2)) .unwrap() } /// Should not exit on malformed init_params #[test] fn malformed_init_params() { let (client_connection, _recv) = initialize_language_server( None, Some(serde_json::json!({ "workspaceFolders": serde_json::Value::Null })), ); let mut script = fixtures(); script.push("lsp/workspace/foo.nu"); let script = path_to_uri(&script); let notification = open_unchecked(&client_connection, script.clone()); assert_json_eq!( notification, serde_json::json!({ "method": "textDocument/publishDiagnostics", "params": { "uri": script, "diagnostics": [] } }) ); } #[rstest] #[case::command_reference( "foo.nu", (0, 12), true, vec![make_location_ref("bar", 4, 2, 4, 7), make_location_ref("foo", 0, 11, 0, 16)], )] #[case::single_file_without_workspace_folder_param( "foo.nu", (0, 12), false, vec![make_location_ref("foo", 0, 11, 0, 16)], )] #[case::new_file( "no_such_file.nu", (0, 5), true, vec![make_location_ref("no_such_file", 0, 4, 0, 7)], )] #[case::new_file_without_workspace_folder_param( "no_such_file.nu", (0, 5), false, vec![make_location_ref("no_such_file", 0, 4, 0, 7)], )] #[case::quoted_command_reference( "bar.nu", (0, 23), true, vec![make_location_ref("bar", 5, 4, 5, 11), make_location_ref("foo", 6, 13, 6, 20)], )] #[case::module_path_reference( "baz.nu", (0, 12), true, vec![make_location_ref("bar", 0, 4, 0, 12), make_location_ref("baz", 6, 4, 6, 12)], )] fn reference_in_workspace( #[case] main_file: &str, #[case] cursor_position: (u32, u32), #[case] with_workspace_folder: bool, #[case] expected_refs: Vec<serde_json::Value>, ) { let mut script = fixtures(); script.push("lsp/workspace"); let (client_connection, _recv) = initialize_language_server( None, serde_json::to_value(InitializeParams { workspace_folders: with_workspace_folder.then_some(vec![WorkspaceFolder { uri: path_to_uri(&script), name: "random name".to_string(), }]), ..Default::default() }) .ok(), ); script.push(main_file); let file_exists = script.is_file(); let script = path_to_uri(&script); if file_exists { open_unchecked(&client_connection, script.clone()); } else { let _ = open( &client_connection, script.clone(), Some("def foo [] {}".into()), ); } let message_num = if with_workspace_folder { if file_exists { 6 } else { 7 } } else { 1 }; let (line, character) = cursor_position; let messages = send_reference_request( &client_connection, script.clone(), line, character, message_num, ); assert_eq!(messages.len(), message_num); let mut has_response = false; for message in messages { match message { Message::Notification(n) => assert_eq!(n.method, Progress::METHOD), Message::Response(r) => { has_response = true; let result = r.result.unwrap(); let array = result.as_array().unwrap(); for expected_ref in &expected_refs { let mut expected = expected_ref.clone(); let uri_placeholder = expected["uri"].as_str().unwrap(); let actual_uri = if uri_placeholder == main_file.strip_suffix(".nu").unwrap() { script.to_string() } else { script .to_string() .replace(main_file.strip_suffix(".nu").unwrap(), uri_placeholder) }; expected["uri"] = serde_json::json!(actual_uri); assert!(array.contains(&expected)); } } _ => panic!("unexpected message type"), } } assert!(has_response); } #[rstest] #[case::quoted_command( "foo.nu", (6, 12), (6, 11), make_range(6, 13, 6, 20), vec![ ("foo", vec![make_text_edit(6, 13, 6, 20)]), ("bar", vec![make_text_edit(5, 4, 5, 11), make_text_edit(0, 22, 0, 29)]) ] )] #[case::module_command( "baz.nu", (1, 47), (6, 11), make_range(1, 41, 1, 56), vec![ ("foo", vec![make_text_edit(10, 16, 10, 29)]), ("baz", vec![make_text_edit(1, 41, 1, 56), make_text_edit(2, 0, 2, 5), make_text_edit(9, 20, 9, 33)]) ] )] #[case::command_argument( "foo.nu", (3, 5), (3, 5), make_range(3, 3, 3, 8), vec![("foo", vec![make_text_edit(3, 3, 3, 8), make_text_edit(1, 4, 1, 9)])] )] fn rename_operations( #[case] main_file: &str, #[case] prepare_position: (u32, u32), #[case] rename_position: (u32, u32), #[case] expected_prepare: serde_json::Value, #[case] expected_changes: Vec<(&str, Vec<serde_json::Value>)>, ) { let mut script = fixtures(); script.push("lsp/workspace"); let (client_connection, _recv) = initialize_language_server( None, serde_json::to_value(InitializeParams { workspace_folders: Some(vec![WorkspaceFolder {
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
true
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-lsp/src/diagnostics.rs
crates/nu-lsp/src/diagnostics.rs
use crate::{LanguageServer, span_to_range}; use lsp_types::{ Diagnostic, DiagnosticSeverity, PublishDiagnosticsParams, Uri, notification::{Notification, PublishDiagnostics}, }; use miette::{IntoDiagnostic, Result, miette}; impl LanguageServer { pub(crate) fn publish_diagnostics_for_file(&mut self, uri: Uri) -> Result<()> { let mut engine_state = self.new_engine_state(Some(&uri)); engine_state.generate_nu_constant(); let Some((_, span, working_set)) = self.parse_file(&mut engine_state, &uri, true) else { return Ok(()); }; let mut diagnostics = PublishDiagnosticsParams { uri: uri.clone(), diagnostics: Vec::new(), version: None, }; let docs = match self.docs.lock() { Ok(it) => it, Err(err) => return Err(miette!(err.to_string())), }; let file = docs .get_document(&uri) .ok_or_else(|| miette!("\nFailed to get document"))?; for err in working_set.parse_errors.iter() { let message = err.to_string(); diagnostics.diagnostics.push(Diagnostic { range: span_to_range(&err.span(), file, span.start), severity: Some(DiagnosticSeverity::ERROR), message, ..Default::default() }); } for warn in working_set.parse_warnings.iter() { let message = warn.to_string(); diagnostics.diagnostics.push(Diagnostic { range: span_to_range(&warn.span(), file, span.start), severity: Some(DiagnosticSeverity::WARNING), message, ..Default::default() }); } self.connection .sender .send(lsp_server::Message::Notification( lsp_server::Notification::new(PublishDiagnostics::METHOD.to_string(), diagnostics), )) .into_diagnostic() } } #[cfg(test)] mod tests { use crate::path_to_uri; use crate::tests::{initialize_language_server, open_unchecked, update}; use assert_json_diff::assert_json_eq; use nu_test_support::fs::fixtures; use rstest::rstest; #[rstest] #[case::file_with_no_issues("pwd.nu", None, serde_json::json!([]))] #[case::file_fixed_by_update("var.nu", Some(("$env", lsp_types::Range { start: lsp_types::Position { line: 0, character: 6 }, end: lsp_types::Position { line: 0, character: 30 }, })), serde_json::json!([]))] #[case::variable_does_not_exist("var.nu", None, serde_json::json!([{ "range": { "start": { "line": 0, "character": 6 }, "end": { "line": 0, "character": 30 } }, "message": "Variable not found.", "severity": 1 }]))] fn publish_diagnostics( #[case] filename: &str, #[case] update_op: Option<(&str, lsp_types::Range)>, #[case] expected_diagnostics: serde_json::Value, ) { let (client_connection, _recv) = initialize_language_server(None, None); let mut script = fixtures(); script.push("lsp/diagnostics"); script.push(filename); let script = path_to_uri(&script); let mut notification = open_unchecked(&client_connection, script.clone()); // For files that need fixing, open first then update if let Some((text, range)) = update_op { notification = update( &client_connection, script.clone(), String::from(text), Some(range), ); }; assert_json_eq!( notification, serde_json::json!({ "method": "textDocument/publishDiagnostics", "params": { "uri": script, "diagnostics": expected_diagnostics } }) ); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-lsp/src/goto.rs
crates/nu-lsp/src/goto.rs
use std::path::Path; use crate::{Id, LanguageServer, path_to_uri, span_to_range}; use lsp_textdocument::FullTextDocument; use lsp_types::{GotoDefinitionParams, GotoDefinitionResponse, Location}; use nu_protocol::Span; use nu_protocol::engine::{CachedFile, StateWorkingSet}; impl LanguageServer { fn get_location_by_span<'a>( &self, files: impl Iterator<Item = &'a CachedFile>, span: &Span, ) -> Option<Location> { for cached_file in files.into_iter() { if cached_file.covered_span.contains(span.start) { let path = Path::new(&*cached_file.name); // skip nu-std files // TODO: maybe find them in vendor directories? if path.is_relative() { let _ = self.send_log_message( lsp_types::MessageType::WARNING, format!( "Location found in file {path:?}, but absolute path is expected. Skipping..." ), ); continue; } let target_uri = path_to_uri(path); if let Some(file) = self.docs.lock().ok()?.get_document(&target_uri) { return Some(Location { uri: target_uri, range: span_to_range(span, file, cached_file.covered_span.start), }); } else { if !path.is_file() { return None; } // in case where the document is not opened yet, // typically included by the `use/source` command let temp_doc = FullTextDocument::new( "nu".to_string(), 0, String::from_utf8_lossy(cached_file.content.as_ref()).to_string(), ); return Some(Location { uri: target_uri, range: span_to_range(span, &temp_doc, cached_file.covered_span.start), }); } } } None } pub(crate) fn find_definition_span_by_id( working_set: &StateWorkingSet, id: &Id, ) -> Option<Span> { match id { Id::Declaration(decl_id) => { let block_id = working_set.get_decl(*decl_id).block_id()?; working_set.get_block(block_id).span } Id::Variable(var_id, _) => { let var = working_set.get_variable(*var_id); Some(var.declaration_span) } Id::Module(module_id, _) => { let module = working_set.get_module(*module_id); module.span } Id::CellPath(var_id, cell_path) => { let var = working_set.get_variable(*var_id); Some( var.const_val .as_ref() .and_then(|val| val.follow_cell_path(cell_path).ok()) .map(|val| val.span()) .unwrap_or(var.declaration_span), ) } _ => None, } } pub(crate) fn goto_definition( &mut self, params: &GotoDefinitionParams, ) -> Option<GotoDefinitionResponse> { let path_uri = &params.text_document_position_params.text_document.uri; let mut engine_state = self.new_engine_state(Some(path_uri)); let (working_set, id, _, _) = self .parse_and_find( &mut engine_state, path_uri, params.text_document_position_params.position, ) .ok()?; Some(GotoDefinitionResponse::Scalar(self.get_location_by_span( working_set.files(), &Self::find_definition_span_by_id(&working_set, &id)?, )?)) } } #[cfg(test)] mod tests { use crate::path_to_uri; use crate::tests::{initialize_language_server, open, open_unchecked, result_from_message}; use assert_json_diff::assert_json_eq; use lsp_server::{Connection, Message, Notification}; use lsp_types::{ GotoDefinitionParams, PartialResultParams, Position, TextDocumentIdentifier, TextDocumentPositionParams, Uri, WorkDoneProgressParams, request::{GotoDefinition, Request}, }; use nu_test_support::fs::{fixtures, root}; use rstest::rstest; fn send_goto_definition_request( client_connection: &Connection, uri: Uri, line: u32, character: u32, ) -> Message { client_connection .sender .send(Message::Request(lsp_server::Request { id: 2.into(), method: GotoDefinition::METHOD.to_string(), params: serde_json::to_value(GotoDefinitionParams { text_document_position_params: TextDocumentPositionParams { text_document: TextDocumentIdentifier { uri }, position: Position { line, character }, }, work_done_progress_params: WorkDoneProgressParams::default(), partial_result_params: PartialResultParams::default(), }) .unwrap(), })) .unwrap(); client_connection .receiver .recv_timeout(std::time::Duration::from_secs(2)) .unwrap() } #[test] fn goto_definition_for_none_existing_file() { let (client_connection, _recv) = initialize_language_server(None, None); let mut none_existent_path = root(); none_existent_path.push("none-existent.nu"); let script = path_to_uri(&none_existent_path); let resp = send_goto_definition_request(&client_connection, script, 0, 0); assert_json_eq!(result_from_message(resp), serde_json::Value::Null); } #[rstest] #[case::variable("goto/var.nu", (2, 12), None, (0, 4), Some((0, 12)))] #[case::command("goto/command.nu", (4, 1), None, (0, 17), Some((2, 1)))] #[case::command_unicode("goto/command_unicode.nu", (4, 2), None, (0, 19), Some((2, 1)))] #[case::command_parameter("goto/command.nu", (1, 14), None, (0, 11), Some((0, 15)))] #[case::variable_in_else_block("goto/else.nu", (1, 21), None, (0, 4), Some((0, 7)))] #[case::variable_in_match_guard("goto/match.nu", (2, 9), None, (0, 4), Some((0, 7)))] #[case::variable_in_each("goto/collect.nu", (1, 16), None, (0, 4), Some((0, 7)))] #[case::module("goto/module.nu", (3, 15), None, (1, 29), Some((1, 30)))] #[case::module_in_another_file("goto/use_module.nu", (0, 23), Some("goto/module.nu"), (1, 29), Some((1, 30)))] #[case::module_in_hide("goto/use_module.nu", (3, 6), Some("goto/module.nu"), (1, 29), Some((1, 30)))] #[case::overlay_first("goto/use_module.nu", (1, 20), Some("goto/module.nu"), (0, 0), None)] #[case::overlay_second("goto/use_module.nu", (1, 25), Some("goto/module.nu"), (0, 0), None)] #[case::overlay_third("goto/use_module.nu", (2, 30), Some("goto/module.nu"), (0, 0), None)] #[case::cell_path_first("hover/use.nu", (2, 7), Some("hover/cell_path.nu"), (1, 10), None)] #[case::cell_path_second("hover/use.nu", (2, 9), Some("hover/cell_path.nu"), (1, 17), None)] fn goto_definition_single_request( #[case] filename: &str, #[case] cursor_position: (u32, u32), #[case] expected_file: Option<&str>, #[case] expected_start: (usize, usize), #[case] expected_end: Option<(usize, usize)>, ) { let (client_connection, _recv) = initialize_language_server(None, None); let mut script = fixtures(); script.push("lsp"); script.push(filename); let script = path_to_uri(&script); open_unchecked(&client_connection, script.clone()); let (line, character) = cursor_position; let resp = send_goto_definition_request(&client_connection, script.clone(), line, character); let result = result_from_message(resp); let mut target_uri = script.to_string(); if let Some(name) = expected_file { target_uri = target_uri.replace(filename, name); } assert_json_eq!(result["uri"], serde_json::json!(target_uri)); let (line, character) = expected_start; assert_json_eq!( result["range"]["start"], serde_json::json!({ "line": line, "character": character }) ); if let Some((line, character)) = expected_end { assert_json_eq!( result["range"]["end"], serde_json::json!({ "line": line, "character": character }) ); } } #[test] // https://github.com/nushell/nushell/issues/16539 fn goto_definition_in_new_file() { let (client_connection, _recv) = initialize_language_server(None, None); let mut script = fixtures(); script.push("lsp/no_such_file.nu"); let script = path_to_uri(&script); let file_content = r#"def foo [] {}; foo"#; let _ = open( &client_connection, script.clone(), Some(file_content.into()), ); let resp = send_goto_definition_request( &client_connection, script.clone(), 0, file_content.len() as u32 - 1, ); let result = result_from_message(resp); assert_json_eq!( result, serde_json::json!({ "uri": script, "range": { "start": { "line": 0, "character": 11 }, "end": { "line": 0, "character": 13 } } }) ); } #[test] fn goto_definition_on_stdlib_should_not_panic() { let (client_connection, _recv) = initialize_language_server(None, None); let mut script = fixtures(); script.push("lsp/goto/use_module.nu"); let script = path_to_uri(&script); open_unchecked(&client_connection, script.clone()); let resp = send_goto_definition_request(&client_connection, script, 7, 19); match resp { Message::Notification(Notification { params, .. }) => { assert!( params["message"] .to_string() .contains("absolute path is expected") ); } _ => panic!("Unexpected message!"), } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-lsp/src/lib.rs
crates/nu-lsp/src/lib.rs
#![doc = include_str!("../README.md")] use lsp_server::{Connection, IoThreads, Message, Response, ResponseError}; use lsp_textdocument::{FullTextDocument, TextDocuments}; use lsp_types::{ InlayHint, MessageType, OneOf, Position, Range, ReferencesOptions, RenameOptions, SemanticToken, SemanticTokenType, SemanticTokensLegend, SemanticTokensOptions, SemanticTokensServerCapabilities, ServerCapabilities, SignatureHelpOptions, TextDocumentSyncKind, Uri, WorkDoneProgressOptions, WorkspaceFolder, WorkspaceFoldersServerCapabilities, WorkspaceServerCapabilities, request::{self, Request}, }; use miette::{IntoDiagnostic, Result, miette}; use nu_protocol::{ DeclId, ModuleId, Span, Type, Value, VarId, ast::{Block, PathMember}, engine::{EngineState, StateDelta, StateWorkingSet}, }; use std::{ collections::BTreeMap, path::{Path, PathBuf}, str::FromStr, sync::Arc, sync::Mutex, time::Duration, }; use symbols::SymbolCache; use workspace::{InternalMessage, RangePerDoc}; mod ast; mod completion; mod diagnostics; mod goto; mod hints; mod hover; mod notification; mod semantic_tokens; mod signature; mod symbols; mod workspace; #[derive(Debug, Clone, PartialEq)] pub(crate) enum Id { Variable(VarId, Box<[u8]>), Declaration(DeclId), Value(Type), Module(ModuleId, Box<[u8]>), CellPath(VarId, Vec<PathMember>), External(String), } pub struct LanguageServer { connection: Connection, io_threads: Option<IoThreads>, docs: Arc<Mutex<TextDocuments>>, initial_engine_state: EngineState, symbol_cache: SymbolCache, inlay_hints: BTreeMap<Uri, Vec<InlayHint>>, semantic_tokens: BTreeMap<Uri, Vec<SemanticToken>>, workspace_folders: BTreeMap<String, WorkspaceFolder>, /// for workspace wide requests occurrences: BTreeMap<Uri, Vec<Range>>, channels: Option<( crossbeam_channel::Sender<bool>, Arc<crossbeam_channel::Receiver<InternalMessage>>, )>, /// set to true when text changes need_parse: bool, /// cache `StateDelta` to avoid repeated parsing cached_state_delta: Option<StateDelta>, } pub(crate) fn path_to_uri(path: impl AsRef<Path>) -> Uri { Uri::from_str( url::Url::from_file_path(path) .expect("Failed to convert path to Url") .as_str(), ) .expect("Failed to convert Url to lsp_types::Uri.") } pub(crate) fn uri_to_path(uri: &Uri) -> PathBuf { url::Url::from_str(uri.as_str()) .expect("Failed to convert Uri to Url") .to_file_path() .expect("Failed to convert Url to path") } pub(crate) fn span_to_range(span: &Span, file: &FullTextDocument, offset: usize) -> Range { let start = file.position_at(span.start.saturating_sub(offset) as u32); let end = file.position_at(span.end.saturating_sub(offset) as u32); Range { start, end } } impl LanguageServer { pub fn initialize_stdio_connection(engine_state: EngineState) -> Result<Self> { let (connection, io_threads) = Connection::stdio(); Self::initialize_connection(connection, Some(io_threads), engine_state) } fn initialize_connection( connection: Connection, io_threads: Option<IoThreads>, engine_state: EngineState, ) -> Result<Self> { Ok(Self { connection, io_threads, docs: Arc::new(Mutex::new(TextDocuments::new())), initial_engine_state: engine_state, symbol_cache: SymbolCache::new(), inlay_hints: BTreeMap::new(), semantic_tokens: BTreeMap::new(), workspace_folders: BTreeMap::new(), occurrences: BTreeMap::new(), channels: None, need_parse: true, cached_state_delta: None, }) } pub fn serve_requests(mut self) -> Result<()> { let work_done_progress_options = WorkDoneProgressOptions { work_done_progress: Some(true), }; let server_capabilities = serde_json::to_value(ServerCapabilities { completion_provider: Some(lsp_types::CompletionOptions::default()), definition_provider: Some(OneOf::Left(true)), document_highlight_provider: Some(OneOf::Left(true)), document_symbol_provider: Some(OneOf::Left(true)), hover_provider: Some(lsp_types::HoverProviderCapability::Simple(true)), inlay_hint_provider: Some(OneOf::Left(true)), references_provider: Some(OneOf::Right(ReferencesOptions { work_done_progress_options, })), rename_provider: Some(OneOf::Right(RenameOptions { prepare_provider: Some(true), work_done_progress_options, })), text_document_sync: Some(lsp_types::TextDocumentSyncCapability::Kind( TextDocumentSyncKind::INCREMENTAL, )), workspace: Some(WorkspaceServerCapabilities { workspace_folders: Some(WorkspaceFoldersServerCapabilities { supported: Some(true), change_notifications: Some(OneOf::Left(true)), }), ..Default::default() }), workspace_symbol_provider: Some(OneOf::Left(true)), semantic_tokens_provider: Some( SemanticTokensServerCapabilities::SemanticTokensOptions(SemanticTokensOptions { // NOTE: only internal command names with space supported for now legend: SemanticTokensLegend { token_types: vec![SemanticTokenType::FUNCTION], token_modifiers: vec![], }, full: Some(lsp_types::SemanticTokensFullOptions::Bool(true)), ..Default::default() }), ), signature_help_provider: Some(SignatureHelpOptions::default()), ..Default::default() }) .expect("Must be serializable"); let init_params = self .connection .initialize_while(server_capabilities, || { !self.initial_engine_state.signals().interrupted() }) .into_diagnostic()?; self.initialize_workspace_folders(init_params); while !self.initial_engine_state.signals().interrupted() { // first check new messages from child thread self.handle_internal_messages()?; let msg = match self .connection .receiver .recv_timeout(Duration::from_secs(1)) { Ok(msg) => { // cancel execution if other messages received before job done self.cancel_background_thread(); msg } Err(crossbeam_channel::RecvTimeoutError::Timeout) => { continue; } Err(_) => break, }; match msg { Message::Request(request) => { if self .connection .handle_shutdown(&request) .into_diagnostic()? { return Ok(()); } let resp = match request.method.as_str() { request::Completion::METHOD => { Self::handle_lsp_request(request, |params| self.complete(params)) } request::DocumentHighlightRequest::METHOD => { Self::handle_lsp_request(request, |params| { self.document_highlight(params) }) } request::DocumentSymbolRequest::METHOD => { Self::handle_lsp_request(request, |params| self.document_symbol(params)) } request::GotoDefinition::METHOD => { Self::handle_lsp_request(request, |params| self.goto_definition(params)) } request::HoverRequest::METHOD => { Self::handle_lsp_request(request, |params| self.hover(params)) } request::InlayHintRequest::METHOD => { Self::handle_lsp_request(request, |params| self.get_inlay_hints(params)) } request::PrepareRenameRequest::METHOD => { let id = request.id.clone(); if let Err(e) = self.prepare_rename(request) { self.send_error_message(id, 2, e.to_string())? } continue; } request::References::METHOD => { Self::handle_lsp_request(request, |params| { self.references(params, 5000) }) } request::Rename::METHOD => { if self.channels.is_some() { self.send_error_message( request.id.clone(), 3, "Please wait for renaming preparation to complete.".into(), )?; continue; } Self::handle_lsp_request(request, |params| self.rename(params)) } request::SemanticTokensFullRequest::METHOD => { Self::handle_lsp_request(request, |params| { self.get_semantic_tokens(params) }) } request::SignatureHelpRequest::METHOD => { Self::handle_lsp_request(request, |params| { self.get_signature_help(params) }) } request::WorkspaceSymbolRequest::METHOD => { Self::handle_lsp_request(request, |params| { self.workspace_symbol(params) }) } _ => { continue; } }; self.connection .sender .send(Message::Response(resp)) .into_diagnostic()?; } Message::Response(_) => {} Message::Notification(notification) => { if let Some(updated_file) = self.handle_lsp_notification(notification) { self.need_parse = true; self.symbol_cache.mark_dirty(updated_file.clone(), true); self.publish_diagnostics_for_file(updated_file)?; } } } } if let Some(io_threads) = self.io_threads { io_threads.join().into_diagnostic()?; } Ok(()) } /// Send a cancel message to a running bg thread pub(crate) fn cancel_background_thread(&mut self) { if let Some((sender, _)) = &self.channels { sender.send(true).ok(); let _ = self.send_log_message( MessageType::WARNING, "Workspace-wide search took too long!".into(), ); } } /// Check results from background thread pub(crate) fn handle_internal_messages(&mut self) -> Result<bool> { let mut reset = false; if let Some((_, receiver)) = &self.channels { for im in receiver.try_iter() { match im { InternalMessage::RangeMessage(RangePerDoc { uri, ranges }) => { self.occurrences.insert(uri, ranges); } InternalMessage::OnGoing(token, progress) => { self.send_progress_report(token, progress, None)?; } InternalMessage::Finished(token) => { reset = true; self.send_progress_end(token, Some("Finished.".to_string()))?; } InternalMessage::Cancelled(token) => { reset = true; self.send_progress_end(token, Some("interrupted.".to_string()))?; } } } } if reset { self.channels = None; } Ok(reset) } /// Create a clone of the initial_engine_state with: /// /// * PWD set to the parent directory of given uri. Fallback to `$env.PWD` if None. /// * `StateDelta` cache merged pub(crate) fn new_engine_state(&self, uri: Option<&Uri>) -> EngineState { let mut engine_state = self.initial_engine_state.clone(); match uri { Some(uri) => { let path = uri_to_path(uri); if let Some(path) = path.parent() { engine_state .add_env_var("PWD".into(), Value::test_string(path.to_string_lossy())) }; } None => { let cwd = std::env::current_dir().expect("Could not get current working directory."); engine_state.add_env_var("PWD".into(), Value::test_string(cwd.to_string_lossy())); } } // merge the cached `StateDelta` if text not changed if !self.need_parse { engine_state .merge_delta( self.cached_state_delta .to_owned() .expect("Tried to merge a non-existing state delta"), ) .expect("Failed to merge state delta"); } engine_state } fn cache_parsed_block(&mut self, working_set: &mut StateWorkingSet, block: Arc<Block>) { if self.need_parse { // TODO: incremental parsing // add block to working_set for later references working_set.add_block(block); self.cached_state_delta = Some(working_set.delta.clone()); self.need_parse = false; } } pub(crate) fn parse_and_find<'a>( &mut self, engine_state: &'a mut EngineState, uri: &Uri, pos: Position, ) -> Result<(StateWorkingSet<'a>, Id, Span, Span)> { let (block, file_span, working_set) = self .parse_file(engine_state, uri, false) .ok_or_else(|| miette!("\nFailed to parse current file"))?; let docs = match self.docs.lock() { Ok(it) => it, Err(err) => return Err(miette!(err.to_string())), }; let file = docs .get_document(uri) .ok_or_else(|| miette!("\nFailed to get document"))?; let location = file.offset_at(pos) as usize + file_span.start; let (id, span) = ast::find_id(&block, &working_set, &location) .ok_or_else(|| miette!("\nFailed to find current name"))?; Ok((working_set, id, span, file_span)) } pub(crate) fn parse_file<'a>( &mut self, engine_state: &'a mut EngineState, uri: &Uri, need_extra_info: bool, ) -> Option<(Arc<Block>, Span, StateWorkingSet<'a>)> { let mut working_set = StateWorkingSet::new(engine_state); let docs = self.docs.lock().ok()?; let file = docs.get_document(uri)?; let file_path = uri_to_path(uri); let file_path_str = file_path.to_str()?; let contents = file.get_content(None).as_bytes(); // For `const foo = path self .` let _ = working_set.files.push(file_path.clone(), Span::unknown()); let block = nu_parser::parse(&mut working_set, Some(file_path_str), contents, false); let span = working_set.get_span_for_filename(file_path_str)?; if need_extra_info { let file_inlay_hints = Self::extract_inlay_hints(&working_set, &block, span.start, file); self.inlay_hints.insert(uri.clone(), file_inlay_hints); let file_semantic_tokens = Self::extract_semantic_tokens(&working_set, &block, span.start, file); self.semantic_tokens .insert(uri.clone(), file_semantic_tokens); } drop(docs); self.cache_parsed_block(&mut working_set, block.clone()); Some((block, span, working_set)) } fn handle_lsp_request<P, H, R>(req: lsp_server::Request, mut param_handler: H) -> Response where P: serde::de::DeserializeOwned, H: FnMut(&P) -> Option<R>, R: serde::ser::Serialize, { match serde_json::from_value::<P>(req.params) { Ok(params) => Response { id: req.id, result: Some( param_handler(&params) .and_then(|response| serde_json::to_value(response).ok()) .unwrap_or(serde_json::Value::Null), ), error: None, }, Err(err) => Response { id: req.id, result: None, error: Some(ResponseError { code: 1, message: err.to_string(), data: None, }), }, } } } #[cfg(test)] mod tests { use super::*; use lsp_types::{ DidChangeTextDocumentParams, DidOpenTextDocumentParams, HoverParams, InitializedParams, TextDocumentContentChangeEvent, TextDocumentIdentifier, TextDocumentItem, TextDocumentPositionParams, WorkDoneProgressParams, notification::{ DidChangeTextDocument, DidOpenTextDocument, Exit, Initialized, Notification, }, request::{HoverRequest, Initialize, Request, Shutdown}, }; use nu_protocol::{PipelineData, ShellError, Value, debugger::WithoutDebug, engine::Stack}; use nu_std::load_standard_library; use std::sync::mpsc::{self, Receiver}; use std::time::Duration; /// Initialize the language server for test purposes /// /// # Arguments /// - `nu_config_code`: Optional user defined `config.nu` that is loaded on start /// - `params`: Optional client side capability parameters pub(crate) fn initialize_language_server( nu_config_code: Option<&str>, params: Option<serde_json::Value>, ) -> (Connection, Receiver<Result<()>>) { let engine_state = nu_cmd_lang::create_default_context(); let mut engine_state = nu_command::add_shell_command_context(engine_state); engine_state.generate_nu_constant(); assert!(load_standard_library(&mut engine_state).is_ok()); let cwd = std::env::current_dir().expect("Could not get current working directory."); engine_state.add_env_var("PWD".into(), Value::test_string(cwd.to_string_lossy())); if let Some(code) = nu_config_code { assert!(merge_input(code.as_bytes(), &mut engine_state, &mut Stack::new()).is_ok()); } let (client_connection, server_connection) = Connection::memory(); let lsp_server = LanguageServer::initialize_connection(server_connection, None, engine_state).unwrap(); let (send, recv) = mpsc::channel(); std::thread::spawn(move || send.send(lsp_server.serve_requests())); client_connection .sender .send(Message::Request(lsp_server::Request { id: 1.into(), method: Initialize::METHOD.to_string(), params: params.unwrap_or(serde_json::Value::Null), })) .unwrap(); client_connection .sender .send(Message::Notification(lsp_server::Notification { method: Initialized::METHOD.to_string(), params: serde_json::to_value(InitializedParams {}).unwrap(), })) .unwrap(); let _initialize_response = client_connection .receiver .recv_timeout(Duration::from_secs(5)) .unwrap(); (client_connection, recv) } /// merge_input executes the given input into the engine /// and merges the state fn merge_input( input: &[u8], engine_state: &mut EngineState, stack: &mut Stack, ) -> Result<(), ShellError> { let (block, delta) = { let mut working_set = StateWorkingSet::new(engine_state); let block = nu_parser::parse(&mut working_set, None, input, false); assert!(working_set.parse_errors.is_empty()); (block, working_set.render()) }; engine_state.merge_delta(delta)?; assert!( nu_engine::eval_block::<WithoutDebug>( engine_state, stack, &block, PipelineData::value(Value::nothing(Span::unknown()), None), ) .is_ok() ); // Merge environment into the permanent state engine_state.merge_env(stack) } #[test] fn shutdown_on_request() { let (client_connection, recv) = initialize_language_server(None, None); client_connection .sender .send(Message::Request(lsp_server::Request { id: 2.into(), method: Shutdown::METHOD.to_string(), params: serde_json::Value::Null, })) .unwrap(); client_connection .sender .send(Message::Notification(lsp_server::Notification { method: Exit::METHOD.to_string(), params: serde_json::Value::Null, })) .unwrap(); assert!(recv.recv_timeout(Duration::from_secs(2)).unwrap().is_ok()); } pub(crate) fn open_unchecked( client_connection: &Connection, uri: Uri, ) -> lsp_server::Notification { open(client_connection, uri, None).unwrap() } pub(crate) fn open( client_connection: &Connection, uri: Uri, new_text: Option<String>, ) -> Result<lsp_server::Notification, String> { let text = new_text .or_else(|| std::fs::read_to_string(uri_to_path(&uri)).ok()) .ok_or("Failed to read file.")?; client_connection .sender .send(Message::Notification(lsp_server::Notification { method: DidOpenTextDocument::METHOD.to_string(), params: serde_json::to_value(DidOpenTextDocumentParams { text_document: TextDocumentItem { uri, language_id: String::from("nu"), version: 1, text, }, }) .unwrap(), })) .map_err(|e| e.to_string())?; let notification = client_connection .receiver .recv_timeout(Duration::from_secs(2)) .map_err(|e| e.to_string())?; if let Message::Notification(n) = notification { Ok(n) } else { Err(String::from("Did not receive a notification from server")) } } pub(crate) fn update( client_connection: &Connection, uri: Uri, text: String, range: Option<Range>, ) -> lsp_server::Notification { client_connection .sender .send(lsp_server::Message::Notification( lsp_server::Notification { method: DidChangeTextDocument::METHOD.to_string(), params: serde_json::to_value(DidChangeTextDocumentParams { text_document: lsp_types::VersionedTextDocumentIdentifier { uri, version: 2, }, content_changes: vec![TextDocumentContentChangeEvent { range, range_length: None, text, }], }) .unwrap(), }, )) .unwrap(); let notification = client_connection .receiver .recv_timeout(Duration::from_secs(2)) .unwrap(); if let Message::Notification(n) = notification { n } else { panic!(); } } pub(crate) fn result_from_message(message: lsp_server::Message) -> serde_json::Value { match message { Message::Response(Response { result, .. }) => result.expect("Empty result!"), _ => panic!("Unexpected message type!"), } } pub(crate) fn send_hover_request( client_connection: &Connection, uri: Uri, line: u32, character: u32, ) -> Message { client_connection .sender .send(Message::Request(lsp_server::Request { id: 2.into(), method: HoverRequest::METHOD.to_string(), params: serde_json::to_value(HoverParams { text_document_position_params: TextDocumentPositionParams { text_document: TextDocumentIdentifier { uri }, position: Position { line, character }, }, work_done_progress_params: WorkDoneProgressParams::default(), }) .unwrap(), })) .unwrap(); client_connection .receiver .recv_timeout(Duration::from_secs(3)) .unwrap() } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-lsp/src/signature.rs
crates/nu-lsp/src/signature.rs
use lsp_types::{ Documentation, MarkupContent, MarkupKind, ParameterInformation, SignatureHelp, SignatureHelpParams, SignatureInformation, }; use nu_protocol::{ Flag, PositionalArg, Signature, SyntaxShape, Value, ast::{Argument, Call, Expr, Expression, FindMapResult, Traverse}, engine::StateWorkingSet, }; use crate::{LanguageServer, uri_to_path}; fn find_active_internal_call<'a>( expr: &'a Expression, working_set: &'a StateWorkingSet, pos: usize, ) -> FindMapResult<&'a Call> { if !expr.span.contains(pos) { return FindMapResult::Stop; } let closure = |e| find_active_internal_call(e, working_set, pos); match &expr.expr { Expr::Call(call) => { if call.head.contains(pos) { return FindMapResult::Stop; } call.arguments .iter() .find_map(|arg| arg.expr().and_then(|e| e.find_map(working_set, &closure))) .or(Some(call.as_ref())) .map(FindMapResult::Found) .unwrap_or_default() } _ => FindMapResult::Continue, } } pub(crate) fn display_flag(flag: &Flag, verbitam: bool) -> String { let md_backtick = if verbitam { "`" } else { "" }; let mut text = String::new(); if let Some(short_flag) = flag.short { text.push_str(&format!("{md_backtick}-{short_flag}{md_backtick}")); } if !flag.long.is_empty() { if flag.short.is_some() { text.push_str(", "); } text.push_str(&format!("{md_backtick}--{}{md_backtick}", flag.long)); } text } pub(crate) fn doc_for_arg( syntax_shape: Option<SyntaxShape>, desc: String, default_value: Option<Value>, optional: bool, ) -> String { let mut text = String::new(); if let Some(mut shape) = syntax_shape { if let SyntaxShape::Keyword(_, inner_shape) = shape { shape = *inner_shape; } text.push_str(&format!(": `<{shape}>`")); } if !(desc.is_empty() && default_value.is_none()) || optional { text.push_str(" -") }; if !desc.is_empty() { text.push_str(&format!(" {desc}")); }; if let Some(value) = default_value.as_ref().and_then(|v| v.coerce_str().ok()) { text.push_str(&format!( " ({}default: `{value}`)", if optional { "optional, " } else { "" } )); } else if optional { text.push_str(" (optional)"); } text } pub(crate) fn get_signature_label(signature: &Signature, indent: bool) -> String { let expand_keyword = |arg: &PositionalArg, optional: bool| match &arg.shape { SyntaxShape::Keyword(kwd, _) => { format!("{} <{}>", String::from_utf8_lossy(kwd), arg.name) } _ => { if optional { arg.name.clone() } else { format!("<{}>", arg.name) } } }; let mut label = String::new(); if indent { label.push_str(" "); } label.push_str(&signature.name); if !signature.named.is_empty() { label.push_str(" {flags}"); } for required_arg in &signature.required_positional { label.push_str(&format!(" {}", expand_keyword(required_arg, false))); } for optional_arg in &signature.optional_positional { label.push_str(&format!(" ({})", expand_keyword(optional_arg, true))); } if let Some(arg) = &signature.rest_positional { label.push_str(&format!(" ...({})", arg.name)); } label } impl LanguageServer { pub(crate) fn get_signature_help( &mut self, params: &SignatureHelpParams, ) -> Option<SignatureHelp> { let path_uri = &params.text_document_position_params.text_document.uri; let docs = self.docs.lock().ok()?; let file = docs.get_document(path_uri)?; let location = file.offset_at(params.text_document_position_params.position) as usize; let file_text = file.get_content(None).to_owned(); drop(docs); let engine_state = self.new_engine_state(Some(path_uri)); let mut working_set = StateWorkingSet::new(&engine_state); // NOTE: in case the cursor is at the end of the call expression let need_placeholder = location == 0 || file_text .get(location - 1..location) .is_some_and(|s| s.chars().all(|c| c.is_whitespace())); let file_path = uri_to_path(path_uri); let filename = if need_placeholder { "lsp_signature_helper_temp_file" } else { file_path.to_str()? }; let block = if need_placeholder { nu_parser::parse( &mut working_set, Some(filename), format!( "{}a{}", file_text.get(..location).unwrap_or_default(), file_text.get(location..).unwrap_or_default() ) .as_bytes(), false, ) } else { nu_parser::parse( &mut working_set, Some(filename), file_text.as_bytes(), false, ) }; let span = working_set.get_span_for_filename(filename)?; let pos_to_search = location.saturating_add(span.start).saturating_sub(1); let active_call = block.find_map(&working_set, &|expr: &Expression| { find_active_internal_call(expr, &working_set, pos_to_search) })?; let active_signature = working_set.get_decl(active_call.decl_id).signature(); let label = get_signature_label(&active_signature, false); let param_num_before_pos = active_call .arguments .iter() .filter(|&arg| !matches!(arg, Argument::Named(..))) .take_while(|&arg| arg.span().end <= pos_to_search) .count() as u32; let str_to_doc = |s: String| { Some(Documentation::MarkupContent(MarkupContent { kind: MarkupKind::Markdown, value: s, })) }; let arg_to_param_info = |arg: PositionalArg, optional: bool| ParameterInformation { label: lsp_types::ParameterLabel::Simple(arg.name), documentation: str_to_doc(doc_for_arg( Some(arg.shape), arg.desc, arg.default_value, optional, )), }; let flag_to_param_info = |flag: Flag| ParameterInformation { label: lsp_types::ParameterLabel::Simple(display_flag(&flag, false)), documentation: str_to_doc(doc_for_arg(flag.arg, flag.desc, flag.default_value, false)), }; // positional args let mut parameters: Vec<ParameterInformation> = active_signature .required_positional .into_iter() .map(|arg| arg_to_param_info(arg, false)) .chain( active_signature .optional_positional .into_iter() .map(|arg| arg_to_param_info(arg, true)), ) .collect(); if let Some(rest_arg) = active_signature.rest_positional { parameters.push(arg_to_param_info(rest_arg, false)); } let max_idx = parameters.len().saturating_sub(1) as u32; let active_parameter = Some(param_num_before_pos.min(max_idx)); // also include flags in the end, just for documentation parameters.extend(active_signature.named.into_iter().map(flag_to_param_info)); Some(SignatureHelp { signatures: vec![SignatureInformation { label, documentation: str_to_doc(active_signature.description), parameters: Some(parameters), active_parameter, }], active_signature: Some(0), active_parameter, }) } } #[cfg(test)] mod tests { use crate::path_to_uri; use crate::tests::{initialize_language_server, open_unchecked, result_from_message}; use assert_json_diff::assert_json_include; use lsp_server::{Connection, Message}; use lsp_types::{Position, SignatureHelpParams, TextDocumentPositionParams}; use lsp_types::{ TextDocumentIdentifier, Uri, WorkDoneProgressParams, request::{Request, SignatureHelpRequest}, }; use nu_test_support::fs::fixtures; use rstest::rstest; fn send_signature_help_request( client_connection: &Connection, uri: Uri, line: u32, character: u32, ) -> Message { client_connection .sender .send(Message::Request(lsp_server::Request { id: 1.into(), method: SignatureHelpRequest::METHOD.to_string(), params: serde_json::to_value(SignatureHelpParams { text_document_position_params: TextDocumentPositionParams { text_document: TextDocumentIdentifier { uri }, position: Position { line, character }, }, work_done_progress_params: WorkDoneProgressParams::default(), context: None, }) .unwrap(), })) .unwrap(); client_connection .receiver .recv_timeout(std::time::Duration::from_secs(2)) .unwrap() } #[rstest] #[case::str_substring_pos_15( None, (0, 15), serde_json::json!({ "signatures": [{ "label": "str substring {flags} <range> ...(rest)", "parameters": [ ], "activeParameter": 0 }], "activeSignature": 0 }) )] #[case::str_substring_pos_17( None, (0, 17), serde_json::json!({ "signatures": [{ "activeParameter": 0 }], "activeSignature": 0 }) )] #[case::str_substring_pos_18( None, (0, 18), serde_json::json!({ "signatures": [{ "activeParameter": 1 }], "activeSignature": 0 }) )] #[case::str_substring_pos_22( None, (0, 22), serde_json::json!({ "signatures": [{ "activeParameter": 1 }], "activeSignature": 0 }) )] #[case::str_substring_line_7( None, (7, 0), serde_json::json!({ "signatures": [{ "label": "str substring {flags} <range> ...(rest)", "activeParameter": 1 }]}) )] #[case::str_substring_line_4( None, (4, 0), serde_json::json!({ "signatures": [{ "label": "str substring {flags} <range> ...(rest)", "activeParameter": 0 }]}) )] #[case::echo_command( None, (16, 6), serde_json::json!({ "signatures": [{ "label": "echo {flags} ...(rest)", "activeParameter": 0 }]}) )] #[case::custom_command_foo_bar( Some(r#"export def "foo bar" [ p1: int p2: string, # doc p3?: int = 1 ] {}"#), (9, 11), serde_json::json!({ "signatures": [{ "label": "foo bar {flags} <p1> <p2> (p3)", "parameters": [ {"label": "p1", "documentation": {"value": ": `<int>`"}}, {"label": "p2", "documentation": {"value": ": `<string>` - doc"}}, {"label": "p3", "documentation": {"value": ": `<int>` - (optional, default: `1`)"}}, ], "activeParameter": 1 }], "activeSignature": 0, "activeParameter": 1 }) )] #[case::custom_command_foo_baz( Some(r#"export def "foo bar" [ p1: int p2: string, # doc p3?: int = 1 ] {}"#), (10, 15), serde_json::json!({ "signatures": [{ "label": "foo baz {flags} <p1> <p2> (p3)", "parameters": [ {"label": "p1", "documentation": {"value": ": `<int>`"}}, {"label": "p2", "documentation": {"value": ": `<string>` - doc"}}, {"label": "p3", "documentation": {"value": ": `<int>` - (optional, default: `1`)"}}, {"label": "-h, --help", "documentation": {"value": " - Display the help message for this command"}}, ], "activeParameter": 2 }], "activeSignature": 0, "activeParameter": 2 }) )] fn signature_help_request( #[case] config: Option<&str>, #[case] cursor_position: (u32, u32), #[case] expected: serde_json::Value, ) { let (client_connection, _recv) = initialize_language_server(config, None); let mut script = fixtures(); script.push("lsp/hints/signature.nu"); let script = path_to_uri(&script); open_unchecked(&client_connection, script.clone()); let (line, character) = cursor_position; let resp = send_signature_help_request(&client_connection, script, line, character); assert_json_include!( actual: result_from_message(resp), expected: expected ); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-lsp/src/completion.rs
crates/nu-lsp/src/completion.rs
use std::sync::Arc; use crate::{LanguageServer, span_to_range, uri_to_path}; use lsp_types::{ CompletionItem, CompletionItemKind, CompletionItemLabelDetails, CompletionParams, CompletionResponse, CompletionTextEdit, Documentation, InsertTextFormat, MarkupContent, MarkupKind, Range, TextEdit, }; use nu_cli::{NuCompleter, SemanticSuggestion, SuggestionKind}; use nu_protocol::{ PositionalArg, Span, SyntaxShape, engine::{CommandType, EngineState, Stack}, }; impl LanguageServer { pub(crate) fn complete(&mut self, params: &CompletionParams) -> Option<CompletionResponse> { let path_uri = &params.text_document_position.text_document.uri; let docs = self.docs.lock().ok()?; let file = docs.get_document(path_uri)?; let location = file.offset_at(params.text_document_position.position) as usize; let file_text = file.get_content(None).to_owned(); drop(docs); // fallback to default completer where // the text is truncated to `location` and // an extra placeholder token is inserted for correct parsing let is_variable = file_text .get(..location) .and_then(|s| s.rsplit(' ').next()) .is_some_and(|last_word| last_word.starts_with('$')); let need_fallback = location == 0 || is_variable || file_text .get(location - 1..location) .and_then(|s| s.chars().next()) .is_some_and(|c| c.is_whitespace() || "|(){}[]<>,:;".contains(c)); self.need_parse |= need_fallback; let engine_state = Arc::new(self.new_engine_state(Some(path_uri))); let completer = NuCompleter::new(engine_state.clone(), Arc::new(Stack::new())); let results = if need_fallback { completer.fetch_completions_at(&file_text[..location], location) } else { let file_path = uri_to_path(path_uri); let filename = file_path.to_str()?; completer.fetch_completions_within_file(filename, location, &file_text) }; let docs = self.docs.lock().ok()?; let file = docs.get_document(path_uri)?; (!results.is_empty()).then_some(CompletionResponse::Array( results .into_iter() .map(|r| { let reedline_span = r.suggestion.span; Self::completion_item_from_suggestion( &engine_state, r, span_to_range(&Span::new(reedline_span.start, reedline_span.end), file, 0), ) }) .collect(), )) } fn completion_item_from_suggestion( engine_state: &EngineState, suggestion: SemanticSuggestion, range: Range, ) -> CompletionItem { let mut snippet_text = suggestion.suggestion.value.clone(); let mut doc_string = suggestion.suggestion.extra.map(|ex| ex.join("\n")); let mut insert_text_format = None; let mut idx = 0; // use snippet as `insert_text_format` for command argument completion if let Some(SuggestionKind::Command(_, Some(decl_id))) = suggestion.kind { // NOTE: for new commands defined in current context, // which are not present in the engine state, skip the documentation and snippet. if engine_state.num_decls() > decl_id.get() { let cmd = engine_state.get_decl(decl_id); doc_string = Some(Self::get_decl_description(cmd, true)); insert_text_format = Some(InsertTextFormat::SNIPPET); let signature = cmd.signature(); // add curly brackets around block arguments // and keywords, e.g. `=` in `alias foo = bar` let mut arg_wrapper = |arg: &PositionalArg, text: String, optional: bool| -> String { idx += 1; match &arg.shape { SyntaxShape::Block | SyntaxShape::MatchBlock => { format!("{{ ${{{idx}:{text}}} }}") } SyntaxShape::Keyword(kwd, _) => { // NOTE: If optional, the keyword should also be in a placeholder so that it can be removed easily. // Here we choose to use nested placeholders. Note that some editors don't fully support this format, // but usually they will simply ignore the inner ones, so it should be fine. if optional { idx += 1; format!( "${{{}:{} ${{{}:{}}}}}", idx - 1, String::from_utf8_lossy(kwd), idx, text ) } else { format!("{} ${{{}:{}}}", String::from_utf8_lossy(kwd), idx, text) } } _ => format!("${{{idx}:{text}}}"), } }; for required in signature.required_positional { snippet_text.push(' '); snippet_text .push_str(arg_wrapper(&required, required.name.clone(), false).as_str()); } for optional in signature.optional_positional { snippet_text.push(' '); snippet_text.push_str( arg_wrapper(&optional, format!("{}?", optional.name), true).as_str(), ); } if let Some(rest) = signature.rest_positional { idx += 1; snippet_text.push_str(format!(" ${{{}:...{}}}", idx, rest.name).as_str()); } } } // no extra space for a command with args expanded in the snippet if idx == 0 && suggestion.suggestion.append_whitespace { snippet_text.push(' '); } let text_edit = Some(CompletionTextEdit::Edit(TextEdit { range, new_text: snippet_text, })); CompletionItem { label: suggestion.suggestion.value, label_details: suggestion .kind .as_ref() .map(|kind| match kind { SuggestionKind::Value(t) => t.to_string(), SuggestionKind::Command(cmd, _) => cmd.to_string(), SuggestionKind::Module => "module".to_string(), SuggestionKind::Operator => "operator".to_string(), SuggestionKind::Variable => "variable".to_string(), SuggestionKind::Flag => "flag".to_string(), _ => String::new(), }) .map(|s| CompletionItemLabelDetails { detail: None, description: Some(s), }), detail: suggestion.suggestion.description, documentation: doc_string.map(|value| { Documentation::MarkupContent(MarkupContent { kind: MarkupKind::Markdown, value, }) }), kind: Self::lsp_completion_item_kind(suggestion.kind), text_edit, insert_text_format, ..Default::default() } } fn lsp_completion_item_kind( suggestion_kind: Option<SuggestionKind>, ) -> Option<CompletionItemKind> { suggestion_kind.and_then(|suggestion_kind| match suggestion_kind { SuggestionKind::Value(t) => match t { nu_protocol::Type::String => Some(CompletionItemKind::VALUE), _ => None, }, SuggestionKind::CellPath => Some(CompletionItemKind::PROPERTY), SuggestionKind::Command(c, _) => match c { CommandType::Keyword => Some(CompletionItemKind::KEYWORD), CommandType::Builtin => Some(CompletionItemKind::FUNCTION), CommandType::Alias => Some(CompletionItemKind::REFERENCE), CommandType::External => Some(CompletionItemKind::INTERFACE), CommandType::Custom | CommandType::Plugin => Some(CompletionItemKind::METHOD), }, SuggestionKind::Directory => Some(CompletionItemKind::FOLDER), SuggestionKind::File => Some(CompletionItemKind::FILE), SuggestionKind::Flag => Some(CompletionItemKind::FIELD), SuggestionKind::Module => Some(CompletionItemKind::MODULE), SuggestionKind::Operator => Some(CompletionItemKind::OPERATOR), SuggestionKind::Variable => Some(CompletionItemKind::VARIABLE), }) } } #[cfg(test)] mod tests { use crate::path_to_uri; use crate::tests::{initialize_language_server, open_unchecked, result_from_message}; use assert_json_diff::assert_json_include; use lsp_server::{Connection, Message}; use lsp_types::{ CompletionParams, PartialResultParams, Position, TextDocumentIdentifier, TextDocumentPositionParams, Uri, WorkDoneProgressParams, request::{Completion, Request}, }; use nu_test_support::fs::fixtures; use rstest::rstest; fn send_complete_request( client_connection: &Connection, uri: Uri, line: u32, character: u32, ) -> Message { client_connection .sender .send(Message::Request(lsp_server::Request { id: 2.into(), method: Completion::METHOD.to_string(), params: serde_json::to_value(CompletionParams { text_document_position: TextDocumentPositionParams { text_document: TextDocumentIdentifier { uri }, position: Position { line, character }, }, work_done_progress_params: WorkDoneProgressParams::default(), partial_result_params: PartialResultParams::default(), context: None, }) .unwrap(), })) .unwrap(); client_connection .receiver .recv_timeout(std::time::Duration::from_secs(2)) .unwrap() } #[cfg(not(windows))] const DETAIL_STR: &str = "detail"; #[cfg(windows)] const DETAIL_STR: &str = "detail\r"; #[rstest] #[case::variable("var.nu", (2, 9), None, serde_json::json!([ { "label": "$greeting", "labelDetails": { "description": "variable" }, "textEdit": { "newText": "$greeting", "range": { "start": { "character": 5, "line": 2 }, "end": { "character": 9, "line": 2 } } }, "kind": 6 } ]))] #[case::local_variable("var.nu", (5, 10), None, serde_json::json!([ { "label": "$bar", "labelDetails": { "description": "variable" }, "textEdit": { "newText": "$bar", "range": { "start": { "character": 7, "line": 5 }, "end": { "character": 10, "line": 5 } } }, "kind": 6 } ]))] #[case::keyword("keyword.nu", (0, 2), None, serde_json::json!([ { "label": "overlay", "labelDetails": { "description": "keyword" }, "textEdit": { "newText": "overlay ", "range": { "start": { "character": 0, "line": 0 }, "end": { "character": 2, "line": 0 } } }, "kind": 14 } ]))] #[case::cell_path_first("cell_path.nu", (1, 5), None, serde_json::json!([ { "label": "\"1\"", "detail": "string", "textEdit": { "newText": "\"1\"", "range": { "start": { "line": 1, "character": 5 }, "end": { "line": 1, "character": 5 } } }, "kind": 10 } ]))] #[case::cell_path_second("cell_path.nu", (1, 10), None, serde_json::json!([ { "label": "baz", "detail": "int", "textEdit": { "newText": "baz", "range": { "start": { "line": 1, "character": 10 }, "end": { "line": 1, "character": 10 } } }, "kind": 10 } ]))] #[case::command_with_line("utf_pipeline.nu", (0, 13), None, serde_json::json!([ { "label": "str trim", "labelDetails": { "description": "built-in" }, "detail": "Trim whitespace or specific character.", "textEdit": { "range": { "start": { "line": 0, "character": 8 }, "end": { "line": 0, "character": 13 }, }, "newText": "str trim ${1:...rest}" }, "insertTextFormat": 2, "kind": 3 } ]))] #[case::external_completer( "external.nu", (0, 11), Some("$env.config.completions.external.completer = {|spans| ['--background']}"), serde_json::json!([{ "label": "--background", "labelDetails": { "description": "string" }, "textEdit": { "newText": "--background", "range": { "start": { "line": 0, "character": 5 }, "end": { "line": 0, "character": 11 } } }, }]) )] #[case::fallback_beginning("fallback.nu", (0, 0), None, serde_json::json!([ { "label": "alias", "labelDetails": { "description": "keyword" }, "detail": "Alias a command (with optional flags) to a new name.", "textEdit": { "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 0 }, }, "newText": "alias ${1:name} = ${2:initial_value}" }, "insertTextFormat": 2, "kind": 14 } ]))] #[case::fallback_whitespace("fallback.nu", (3, 2), None, serde_json::json!([ { "label": "alias", "labelDetails": { "description": "keyword" }, "detail": "Alias a command (with optional flags) to a new name.", "textEdit": { "range": { "start": { "line": 3, "character": 2 }, "end": { "line": 3, "character": 2 }, }, "newText": "alias ${1:name} = ${2:initial_value}" }, "insertTextFormat": 2, "kind": 14 } ]))] #[case::operator_not_equal("fallback.nu", (7, 10), None, serde_json::json!([ { "label": "!=", "labelDetails": { "description": "operator" }, "textEdit": { "newText": "!= ", "range": { "start": { "character": 10, "line": 7 }, "end": { "character": 10, "line": 7 } } }, "kind": 24 } ]))] #[case::operator_not_has("fallback.nu", (7, 15), None, serde_json::json!([ { "label": "not-has", "labelDetails": { "description": "operator" }, "textEdit": { "newText": "not-has ", "range": { "start": { "character": 10, "line": 7 }, "end": { "character": 15, "line": 7 } } }, "kind": 24 } ]))] #[case::use_module("use.nu", (4, 17), None, serde_json::json!([ { "label": "std-rfc", "labelDetails": { "description": "module" }, "textEdit": { "newText": "std-rfc", "range": { "start": { "character": 11, "line": 4 }, "end": { "character": 17, "line": 4 } } }, "kind": 9 } ]))] #[case::use_clip("use.nu", (5, 22), None, serde_json::json!([ { "label": "std-rfc/clip", "labelDetails": { "description": "module" }, "textEdit": { "newText": "std-rfc/clip", "range": { "start": { "character": 11, "line": 5 }, "end": { "character": 23, "line": 5 } } }, "kind": 9 } ]))] #[case::use_paste("use.nu", (5, 35), None, serde_json::json!([ { "label": "paste", "labelDetails": { "description": "custom" }, "textEdit": { "newText": "paste", "range": { "start": { "character": 32, "line": 5 }, "end": { "character": 37, "line": 5 } } }, "kind": 2 } ]))] #[case::use_null_device("use.nu", (6, 14), None, serde_json::json!([ { "label": "null_device", "labelDetails": { "description": "variable" }, "textEdit": { "newText": "null_device", "range": { "start": { "character": 8, "line": 6 }, "end": { "character": 14, "line": 6 } } }, "kind": 6 } ]))] #[case::use_foo("use.nu", (7, 13), None, serde_json::json!([ { "label": "foo", "labelDetails": { "description": "variable" }, "textEdit": { "newText": "foo", "range": { "start": { "character": 11, "line": 7 }, "end": { "character": 14, "line": 7 } } }, "kind": 6 } ]))] #[case::command_basic("command.nu", (0, 6), None, serde_json::json!([ { "label": "config n foo bar", "detail": DETAIL_STR, "kind": 2 }, { "label": "config nu", "detail": "Edit nu configurations.", "textEdit": { "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 8 } }, "newText": "config nu " } } ]))] #[case::command_fallback("command.nu", (13, 9), None, serde_json::json!([ { "label": "config n foo bar", "detail": DETAIL_STR, "kind": 2 } ]))] #[case::short_flag_name("command.nu", (15, 17), None, serde_json::json!([ { "label": "-e", "detail": "byte encode endian, available options: native(default), little, big", "textEdit": { "newText": "-e ", "range": { "start": { "character": 15, "line": 15 }, "end": { "character": 17, "line": 15 } } }, "kind": 5 } ]))] #[case::short_flag_value("command.nu", (15, 20), None, serde_json::json!([ { "label": "big", "kind": 12 } ]))] #[case::long_flag_name("command.nu", (15, 30), None, serde_json::json!([ { "label": "--endian", "detail": "byte encode endian, available options: native(default), little, big", "textEdit": { "newText": "--endian ", "range": { "start": { "character": 22, "line": 15 }, "end": { "character": 30, "line": 15 } } }, "kind": 5 } ]))] #[case::fallback_file_path("fallback.nu", (5, 4), None, serde_json::json!([ { "label": "cell_path.nu", "labelDetails": { "description": "" }, "textEdit": { "range": { "start": { "line": 5, "character": 3 }, "end": { "line": 5, "character": 4 } }, "newText": "cell_path.nu" }, "kind": 17 } ]))] #[case::external_fallback( "external.nu", (0, 5), Some("$env.config.completions.external.completer = {|spans| ['--background']}"), serde_json::json!([{ "label": "alias", "labelDetails": { "description": "keyword" }, "detail": "Alias a command (with optional flags) to a new name.", "textEdit": { "range": { "start": { "line": 0, "character": 5 }, "end": { "line": 0, "character": 5 } }, "newText": "alias ${1:name} = ${2:initial_value}" }, "kind": 14 }]) )] #[case::command_wide_custom( "command.nu", (23, 5), None, serde_json::json!([{ "label": "baz", "labelDetails": { "description": "string" }, "textEdit": { "range": { "start": { "line": 23, "character": 4 }, "end": { "line": 23, "character": 7 } }, "newText": "baz" }, "kind": 12 }]) )] #[case::command_wide_external( "command.nu", (28, 8), Some("$env.config.completions.external.completer = {|spans| ['text']}"), serde_json::json!([{ "label": "text", "labelDetails": { "description": "string" }, "textEdit": { "range": { "start": { "line": 28, "character": 8 }, "end": { "line": 28, "character": 8 } }, "newText": "text" }, "kind": 12 }]) )] #[case::attributable_command_with_snippet( "command.nu", (21, 0), None, serde_json::json!([{ "label": "def", "labelDetails": { "description": "keyword" }, "textEdit": { "range": { "start": { "line": 21, "character": 0 }, "end": { "line": 21, "character": 0 } }, "newText": "def ${1:def_name} ${2:params} ${3:block}" }, "kind": 14 }]) )] #[case::custom_completion_with_position_and_span( "custom.nu", (13, 15), None, serde_json::json!([{ "label": "foo", "labelDetails": { "description": "string" }, "textEdit": { "range": { "start": { "line": 13, "character": 14 }, "end": { "line": 13, "character": 15 } }, "newText": "foo" }, "kind": 12 }]) )] #[case::custom_completion_with_position_and_span_on_fallback( "custom.nu", (13, 17), None, serde_json::json!([{ "label": "foo", "labelDetails": { "description": "string" }, "textEdit": { "range": { "start": { "line": 13, "character": 16 }, "end": { "line": 13, "character": 17 } }, "newText": "foo" }, "kind": 12 }]) )] #[case::custom_completion_with_position_and_span_on_flag_value( "custom.nu", (13, 30), None, serde_json::json!([{ "label": "foo", "labelDetails": { "description": "string" }, "textEdit": { "range": { "start": { "line": 13, "character": 29 }, "end": { "line": 13, "character": 30 } }, "newText": "foo" }, "kind": 12 }]) )] fn completion_single_request( #[case] filename: &str, #[case] cursor_position: (u32, u32), #[case] config: Option<&str>, #[case] expected: serde_json::Value, ) { let (client_connection, _recv) = initialize_language_server(config, None); let mut script = fixtures(); script.push("lsp/completion"); script.push(filename); let script = path_to_uri(&script); open_unchecked(&client_connection, script.clone()); let (line, character) = cursor_position; let resp = send_complete_request(&client_connection, script, line, character); assert_json_include!( actual: result_from_message(resp), expected: expected ); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-lsp/src/semantic_tokens.rs
crates/nu-lsp/src/semantic_tokens.rs
use std::sync::Arc; use lsp_textdocument::FullTextDocument; use lsp_types::{SemanticToken, SemanticTokens, SemanticTokensParams}; use nu_protocol::{ Span, ast::{Block, Expr, Expression, Traverse}, engine::StateWorkingSet, }; use crate::{LanguageServer, span_to_range}; /// Important to keep spans in increasing order, /// since `SemanticToken`s are created by relative positions /// to one's previous token /// /// Currently supported types: /// 1. internal command names with space fn extract_semantic_tokens_from_expression( expr: &Expression, working_set: &StateWorkingSet, ) -> Vec<Span> { match &expr.expr { Expr::Call(call) => { let command_name = working_set.get_span_contents(call.head); // Exclude some keywords that are supposed to be already highlighted properly, // e.g. by tree-sitter-nu if command_name.contains(&b' ') && !command_name.starts_with(b"export") && !command_name.starts_with(b"overlay") { vec![call.head] } else { vec![] } } _ => vec![], } } impl LanguageServer { pub(crate) fn get_semantic_tokens( &mut self, params: &SemanticTokensParams, ) -> Option<SemanticTokens> { self.semantic_tokens .get(&params.text_document.uri) .map(|vec| SemanticTokens { result_id: None, data: vec.clone(), }) } pub(crate) fn extract_semantic_tokens( working_set: &StateWorkingSet, block: &Arc<Block>, offset: usize, file: &FullTextDocument, ) -> Vec<SemanticToken> { let mut results = Vec::new(); let closure = |e| extract_semantic_tokens_from_expression(e, working_set); block.flat_map(working_set, &closure, &mut results); let mut last_token_line = 0; let mut last_token_char = 0; let mut last_span = Span::unknown(); let mut tokens = vec![]; for sp in results { let range = span_to_range(&sp, file, offset); // shouldn't happen if sp < last_span { continue; } let mut delta_start = range.start.character; if range.end.line == last_token_line { delta_start -= last_token_char; } tokens.push(SemanticToken { delta_start, delta_line: range.end.line.saturating_sub(last_token_line), length: range.end.character.saturating_sub(range.start.character), // 0 means function in semantic_token_legend token_type: 0, token_modifiers_bitset: 0, }); last_span = sp; last_token_line = range.end.line; last_token_char = range.start.character; } tokens } } #[cfg(test)] mod tests { use crate::path_to_uri; use crate::tests::{initialize_language_server, open_unchecked, result_from_message}; use assert_json_diff::assert_json_eq; use lsp_server::{Connection, Message}; use lsp_types::{PartialResultParams, SemanticTokensParams}; use lsp_types::{ TextDocumentIdentifier, Uri, WorkDoneProgressParams, request::{Request, SemanticTokensFullRequest}, }; use nu_test_support::fs::fixtures; fn send_semantic_token_request(client_connection: &Connection, uri: Uri) -> Message { client_connection .sender .send(Message::Request(lsp_server::Request { id: 1.into(), method: SemanticTokensFullRequest::METHOD.to_string(), params: serde_json::to_value(SemanticTokensParams { text_document: TextDocumentIdentifier { uri }, work_done_progress_params: WorkDoneProgressParams::default(), partial_result_params: PartialResultParams::default(), }) .unwrap(), })) .unwrap(); client_connection .receiver .recv_timeout(std::time::Duration::from_secs(2)) .unwrap() } #[test] fn semantic_token_internals() { let (client_connection, _recv) = initialize_language_server(None, None); let mut script = fixtures(); script.push("lsp/semantic_tokens/internals.nu"); let script = path_to_uri(&script); open_unchecked(&client_connection, script.clone()); let resp = send_semantic_token_request(&client_connection, script); assert_json_eq!( result_from_message(resp), serde_json::json!( { "data": [ // delta_line, delta_start, length, token_type, token_modifiers_bitset 0, 0, 13, 0, 0, 1, 2, 10, 0, 0, 7, 15, 13, 0, 0, 0, 20, 10, 0, 0, 4, 0, 7, 0, 0, 5, 0, 12, 0, 0 ]}) ); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-lsp/src/notification.rs
crates/nu-lsp/src/notification.rs
use crate::LanguageServer; use lsp_types::{ DidChangeTextDocumentParams, DidChangeWorkspaceFoldersParams, DidCloseTextDocumentParams, DidOpenTextDocumentParams, LogMessageParams, MessageType, ProgressParams, ProgressParamsValue, ProgressToken, Uri, WorkDoneProgress, WorkDoneProgressBegin, WorkDoneProgressEnd, WorkDoneProgressReport, notification::{ DidChangeTextDocument, DidChangeWorkspaceFolders, DidCloseTextDocument, DidOpenTextDocument, Notification, Progress, }, }; use miette::{IntoDiagnostic, Result}; impl LanguageServer { pub(crate) fn handle_lsp_notification( &mut self, notification: lsp_server::Notification, ) -> Option<Uri> { let mut docs = self.docs.lock().ok()?; docs.listen(notification.method.as_str(), &notification.params); match notification.method.as_str() { DidOpenTextDocument::METHOD => { let params: DidOpenTextDocumentParams = serde_json::from_value(notification.params) .expect("Expect receive DidOpenTextDocumentParams"); Some(params.text_document.uri) } DidChangeTextDocument::METHOD => { let params: DidChangeTextDocumentParams = serde_json::from_value(notification.params) .expect("Expect receive DidChangeTextDocumentParams"); Some(params.text_document.uri) } DidCloseTextDocument::METHOD => { let params: DidCloseTextDocumentParams = serde_json::from_value(notification.params) .expect("Expect receive DidCloseTextDocumentParams"); let uri = params.text_document.uri; self.symbol_cache.drop(&uri); self.inlay_hints.remove(&uri); None } DidChangeWorkspaceFolders::METHOD => { let params: DidChangeWorkspaceFoldersParams = serde_json::from_value(notification.params) .expect("Expect receive DidChangeWorkspaceFoldersParams"); for added in params.event.added { self.workspace_folders.insert(added.name.clone(), added); } for removed in params.event.removed { self.workspace_folders.remove(&removed.name); } None } _ => None, } } pub(crate) fn send_progress_notification( &self, token: ProgressToken, value: WorkDoneProgress, ) -> Result<()> { let progress_params = ProgressParams { token, value: ProgressParamsValue::WorkDone(value), }; let notification = lsp_server::Notification::new(Progress::METHOD.to_string(), progress_params); self.connection .sender .send(lsp_server::Message::Notification(notification)) .into_diagnostic() } pub(crate) fn send_log_message(&self, typ: MessageType, message: String) -> Result<()> { let log_params = LogMessageParams { typ, message }; let notification = lsp_server::Notification::new( lsp_types::notification::LogMessage::METHOD.to_string(), log_params, ); self.connection .sender .send(lsp_server::Message::Notification(notification)) .into_diagnostic() } pub(crate) fn send_progress_begin(&self, token: ProgressToken, title: String) -> Result<()> { self.send_progress_notification( token, WorkDoneProgress::Begin(WorkDoneProgressBegin { title, percentage: Some(0), cancellable: Some(true), ..Default::default() }), ) } pub(crate) fn send_progress_report( &self, token: ProgressToken, percentage: u32, message: Option<String>, ) -> Result<()> { self.send_progress_notification( token, WorkDoneProgress::Report(WorkDoneProgressReport { message, cancellable: Some(true), percentage: Some(percentage), }), ) } pub(crate) fn send_progress_end( &self, token: ProgressToken, message: Option<String>, ) -> Result<()> { self.send_progress_notification( token, WorkDoneProgress::End(WorkDoneProgressEnd { message }), ) } pub(crate) fn send_error_message( &self, id: lsp_server::RequestId, code: i32, message: String, ) -> Result<()> { self.connection .sender .send(lsp_server::Message::Response(lsp_server::Response { id, result: None, error: Some(lsp_server::ResponseError { code, message, data: None, }), })) .into_diagnostic()?; Ok(()) } } #[cfg(test)] mod tests { use crate::path_to_uri; use crate::tests::{ initialize_language_server, open_unchecked, result_from_message, send_hover_request, update, }; use assert_json_diff::assert_json_eq; use lsp_types::Range; use nu_test_support::fs::fixtures; use rstest::rstest; #[rstest] #[case::full( r#"# Renders some updated greeting message def hello [] {} hello"#, None )] #[case::partial( "# Renders some updated greeting message", Some(Range { start: lsp_types::Position { line: 0, character: 0, }, end: lsp_types::Position { line: 0, character: 31, }, }) )] fn hover_on_command_after_content_change(#[case] text: String, #[case] range: Option<Range>) { let (client_connection, _recv) = initialize_language_server(None, None); let mut script = fixtures(); script.push("lsp/hover/command.nu"); let script = path_to_uri(&script); open_unchecked(&client_connection, script.clone()); update(&client_connection, script.clone(), text, range); let resp = send_hover_request(&client_connection, script, 3, 0); assert_json_eq!( result_from_message(resp), serde_json::json!({ "contents": { "kind": "markdown", "value": "Renders some updated greeting message\n---\n### Usage \n```nu\n hello {flags}\n```\n\n### Flags\n\n `-h`, `--help` - Display the help message for this command\n\n" } }) ); } #[test] fn open_document_with_utf_char() { let (client_connection, _recv) = initialize_language_server(None, None); let mut script = fixtures(); script.push("lsp/notifications/issue_11522.nu"); let script = path_to_uri(&script); open_unchecked(&client_connection, script); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-lsp/src/hover.rs
crates/nu-lsp/src/hover.rs
use lsp_types::{Hover, HoverContents, HoverParams, MarkupContent, MarkupKind}; use nu_protocol::{PositionalArg, engine::Command}; use std::borrow::Cow; use crate::{ Id, LanguageServer, signature::{display_flag, doc_for_arg, get_signature_label}, }; impl LanguageServer { pub(crate) fn get_decl_description(decl: &dyn Command, skip_description: bool) -> String { let mut description = String::new(); if !skip_description { // First description description.push_str(&format!("{}\n", decl.description().replace('\r', ""))); // Additional description if !decl.extra_description().is_empty() { description.push_str(&format!("\n{}\n", decl.extra_description())); } } // Usage description.push_str("---\n### Usage \n```nu\n"); let signature = decl.signature(); description.push_str(&get_signature_label(&signature, true)); description.push_str("\n```\n"); // Flags if !signature.named.is_empty() { description.push_str("\n### Flags\n\n"); let mut first = true; for named in signature.named { if first { first = false; } else { description.push('\n'); } description.push_str(" "); description.push_str(&display_flag(&named, true)); description.push_str(&doc_for_arg( named.arg, named.desc, named.default_value, false, )); description.push('\n'); } description.push('\n'); } // Parameters if !signature.required_positional.is_empty() || !signature.optional_positional.is_empty() || signature.rest_positional.is_some() { description.push_str("\n### Parameters\n\n"); let mut first = true; let mut write_arg = |arg: PositionalArg, optional: bool| { if first { first = false; } else { description.push('\n'); } description.push_str(&format!(" `{}`", arg.name)); description.push_str(&doc_for_arg( Some(arg.shape), arg.desc, arg.default_value, optional, )); description.push('\n'); }; for required_arg in signature.required_positional { write_arg(required_arg, false); } for optional_arg in signature.optional_positional { write_arg(optional_arg, true); } if let Some(arg) = signature.rest_positional { if !first { description.push('\n'); } description.push_str(&format!(" `...{}`", arg.name)); description.push_str(&doc_for_arg( Some(arg.shape), arg.desc, arg.default_value, false, )); description.push('\n'); } description.push('\n'); } // Input/output types if !signature.input_output_types.is_empty() { description.push_str("\n### Input/output types\n"); description.push_str("\n```nu\n"); for input_output in &signature.input_output_types { description.push_str(&format!(" {} | {}\n", input_output.0, input_output.1)); } description.push_str("\n```\n"); } // Examples if !decl.examples().is_empty() { description.push_str("### Example(s)\n"); for example in decl.examples() { description.push_str(&format!( " {}\n```nu\n {}\n```\n", example.description, example.example )); } } description } pub(crate) fn hover(&mut self, params: &HoverParams) -> Option<Hover> { let path_uri = &params.text_document_position_params.text_document.uri; let mut engine_state = self.new_engine_state(Some(path_uri)); let (working_set, id, _, _) = self .parse_and_find( &mut engine_state, path_uri, params.text_document_position_params.position, ) .ok()?; let markdown_hover = |content: String| { Some(Hover { contents: HoverContents::Markup(MarkupContent { kind: MarkupKind::Markdown, value: content, }), // TODO range: None, }) }; match id { Id::Variable(var_id, _) => { let var = working_set.get_variable(var_id); let value = var .const_val .clone() .and_then(|v| v.coerce_into_string().ok()) .unwrap_or(String::from(if var.mutable { "mutable" } else { "immutable" })); let contents = format!("```\n{}\n``` \n---\n{}", var.ty, value); markdown_hover(contents) } Id::CellPath(var_id, cell_path) => { let var = working_set.get_variable(var_id); markdown_hover( var.const_val .as_ref() .and_then(|val| val.follow_cell_path(&cell_path).ok()) .map(|val| { let ty = val.get_type(); if let Ok(s) = val.coerce_str() { format!("```\n{ty}\n```\n---\n{s}") } else { format!("```\n{ty}\n```") } }) .unwrap_or("`unknown`".into()), ) } Id::Declaration(decl_id) => markdown_hover(Self::get_decl_description( working_set.get_decl(decl_id), false, )), Id::Module(module_id, _) => { let description = working_set .get_module_comments(module_id)? .iter() .map(|sp| String::from_utf8_lossy(working_set.get_span_contents(*sp)).into()) .collect::<Vec<String>>() .join("\n"); markdown_hover(description) } Id::Value(t) => markdown_hover(format!("`{t}`")), Id::External(cmd) => { fn fix_manpage_ascii_shenanigans(text: &str) -> Cow<'_, str> { if cfg!(windows) { Cow::Borrowed(text) } else { let re = fancy_regex::Regex::new(r".\x08").expect("regular expression error"); re.replace_all(text, "") } } let command_output = if cfg!(windows) { std::process::Command::new("powershell.exe") .args(["-NoProfile", "-Command", "help", &cmd]) .output() } else { std::process::Command::new("man").arg(&cmd).output() }; let manpage_str = match command_output { Ok(output) => nu_utils::strip_ansi_likely( fix_manpage_ascii_shenanigans( String::from_utf8_lossy(&output.stdout).as_ref(), ) .as_ref(), ) .to_string(), Err(_) => format!("No command help found for {}", &cmd), }; markdown_hover(manpage_str) } } } } #[cfg(test)] mod hover_tests { use crate::{ path_to_uri, tests::{ initialize_language_server, open_unchecked, result_from_message, send_hover_request, }, }; use assert_json_diff::assert_json_eq; use nu_test_support::fs::fixtures; use rstest::rstest; #[rstest] #[case::variable("var.nu", (2, 0), "```\ntable\n``` \n---\nimmutable")] #[case::custom_command( "command.nu", (3, 0), "Renders some greeting message\n---\n### Usage \n```nu\n hello {flags}\n```\n\n### Flags\n\n `-h`, `--help` - Display the help message for this command\n\n" )] #[case::custom_in_custom( "command.nu", (9, 7), "\n---\n### Usage \n```nu\n bar {flags}\n```\n\n### Flags\n\n `-h`, `--help` - Display the help message for this command\n\n" )] #[case::str_join( "command.nu", (5, 8), "Concatenate multiple strings into a single string, with an optional separator between each.\n---\n### Usage \n```nu\n str join {flags} (separator)\n```\n\n### Flags\n\n `-h`, `--help` - Display the help message for this command\n\n\n### Parameters\n\n `separator`: `<string>` - Optional separator to use when creating string. (optional)\n\n\n### Input/output types\n\n```nu\n list<any> | string\n string | string\n\n```\n### Example(s)\n Create a string from input\n```nu\n ['nu', 'shell'] | str join\n```\n Create a string from input with a separator\n```nu\n ['nu', 'shell'] | str join '-'\n```\n" )] #[case::cell_path1("use.nu", (2, 3), "```\nlist<oneof<int, record<bar: int>>>\n```")] #[case::cell_path2("use.nu", (2, 7), "```\nrecord<bar: int>\n```")] #[case::cell_path3("use.nu", (2, 11), "```\nint\n```\n---\n2")] fn hover_single_request( #[case] filename: &str, #[case] cursor: (u32, u32), #[case] expected: &str, ) { let (client_connection, _recv) = initialize_language_server(None, None); let mut script = fixtures(); script.push("lsp/hover"); script.push(filename); let script = path_to_uri(&script); open_unchecked(&client_connection, script.clone()); let (line, character) = cursor; let resp = send_hover_request(&client_connection, script, line, character); assert_json_eq!( result_from_message(resp)["contents"]["value"], serde_json::json!(expected) ); } #[ignore = "long-tail disk IO fails the CI workflow"] #[test] fn hover_on_external_command() { let (client_connection, _recv) = initialize_language_server(None, None); let mut script = fixtures(); script.push("lsp/hover/command.nu"); let script = path_to_uri(&script); open_unchecked(&client_connection, script.clone()); let resp = send_hover_request(&client_connection, script, 6, 2); let hover_text = result_from_message(resp)["contents"]["value"].to_string(); #[cfg(not(windows))] assert!(hover_text.contains("SLEEP")); #[cfg(windows)] assert!(hover_text.contains("Start-Sleep")); } #[rstest] #[case::use_record("hover/use.nu", (0, 19), "```\nrecord<foo: list<oneof<int, record<bar: int>>>>\n``` \n---\nimmutable", true)] #[case::use_function("hover/use.nu", (0, 22), "\n---\n### Usage \n```nu\n foo {flags}\n```\n\n### Flags", true)] #[case::cell_path("workspace/baz.nu", (8, 42), "```\nstring\n```\n---\nconst value", false)] #[case::module_first("workspace/foo.nu", (15, 15), "# cmt", false)] #[case::module_second("workspace/foo.nu", (17, 27), "# sub cmt", false)] #[case::module_third("workspace/foo.nu", (19, 33), "# sub sub cmt", false)] fn hover_on_exportable( #[case] filename: &str, #[case] cursor: (u32, u32), #[case] expected_prefix: &str, #[case] use_config: bool, ) { let mut script = fixtures(); script.push("lsp"); script.push(filename); let script_uri = path_to_uri(&script); let config = format!("use {}", script.to_str().unwrap()); let (client_connection, _recv) = initialize_language_server(use_config.then_some(&config), None); open_unchecked(&client_connection, script_uri.clone()); let (line, character) = cursor; let resp = send_hover_request(&client_connection, script_uri, line, character); let result = result_from_message(resp); let actual = result["contents"]["value"] .as_str() .unwrap() .replace("\r", ""); assert!(actual.starts_with(expected_prefix)); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-lsp/src/symbols.rs
crates/nu-lsp/src/symbols.rs
use crate::{Id, LanguageServer, path_to_uri, span_to_range, uri_to_path}; use lsp_textdocument::{FullTextDocument, TextDocuments}; use lsp_types::{ DocumentSymbolParams, DocumentSymbolResponse, Location, Range, SymbolInformation, SymbolKind, Uri, WorkspaceSymbolParams, WorkspaceSymbolResponse, }; use nu_protocol::{ DeclId, ModuleId, Span, VarId, engine::{CachedFile, EngineState, StateWorkingSet}, }; use nucleo_matcher::pattern::{AtomKind, CaseMatching, Normalization, Pattern}; use nucleo_matcher::{Config, Matcher, Utf32Str}; use std::{ cmp::Ordering, collections::{BTreeMap, HashSet}, hash::{Hash, Hasher}, }; /// Struct stored in cache, uri not included #[derive(Clone, Debug, Eq, PartialEq)] struct Symbol { name: String, kind: SymbolKind, range: Range, } impl Hash for Symbol { fn hash<H: Hasher>(&self, state: &mut H) { self.range.start.hash(state); self.range.end.hash(state); } } impl PartialOrd for Symbol { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl Ord for Symbol { fn cmp(&self, other: &Self) -> Ordering { if self.kind == other.kind { return self.range.start.cmp(&other.range.start); } match (self.kind, other.kind) { (SymbolKind::FUNCTION, _) => Ordering::Less, (_, SymbolKind::FUNCTION) => Ordering::Greater, _ => self.range.start.cmp(&other.range.start), } } } impl Symbol { fn to_symbol_information(&self, uri: &Uri) -> SymbolInformation { #[allow(deprecated)] SymbolInformation { location: Location { uri: uri.clone(), range: self.range, }, name: self.name.to_owned(), kind: self.kind, container_name: None, deprecated: None, tags: None, } } } /// Cache symbols for each opened file to avoid repeated parsing pub(crate) struct SymbolCache { /// Fuzzy matcher for symbol names matcher: Matcher, /// File Uri --> Symbols cache: BTreeMap<Uri, Vec<Symbol>>, /// If marked as dirty, parse on next request dirty_flags: BTreeMap<Uri, bool>, } impl SymbolCache { pub fn new() -> Self { SymbolCache { matcher: Matcher::new({ let mut cfg = Config::DEFAULT; cfg.prefer_prefix = true; cfg }), cache: BTreeMap::new(), dirty_flags: BTreeMap::new(), } } pub fn mark_dirty(&mut self, uri: Uri, flag: bool) { self.dirty_flags.insert(uri, flag); } fn get_symbol_by_id( working_set: &StateWorkingSet, id: Id, doc: &FullTextDocument, doc_span: &Span, ) -> Option<Symbol> { match id { Id::Declaration(decl_id) => { let decl = working_set.get_decl(decl_id); let span = working_set.get_block(decl.block_id()?).span?; // multi-doc working_set, returns None if the Id is in other files if !doc_span.contains(span.start) { return None; } Some(Symbol { name: decl.name().to_string(), kind: SymbolKind::FUNCTION, range: span_to_range(&span, doc, doc_span.start), }) } Id::Variable(var_id, _) => { let var = working_set.get_variable(var_id); let span = var.declaration_span; if !doc_span.contains(span.start) || span.end == span.start { return None; } let range = span_to_range(&span, doc, doc_span.start); let name = doc.get_content(Some(range)); Some(Symbol { name: name.to_string(), kind: SymbolKind::VARIABLE, range, }) } Id::Module(module_id, _) => { let module = working_set.get_module(module_id); let span = module.span?; if !doc_span.contains(span.start) { return None; } Some(Symbol { name: String::from_utf8(module.name()).ok()?, kind: SymbolKind::MODULE, range: span_to_range(&span, doc, doc_span.start), }) } _ => None, } } fn extract_all_symbols( working_set: &StateWorkingSet, doc: &FullTextDocument, cached_file: &CachedFile, ) -> Vec<Symbol> { let mut all_symbols: Vec<Symbol> = (0..working_set.num_decls()) .filter_map(|id| { Self::get_symbol_by_id( working_set, Id::Declaration(DeclId::new(id)), doc, &cached_file.covered_span, ) }) .chain((0..working_set.num_vars()).filter_map(|id| { Self::get_symbol_by_id( working_set, Id::Variable(VarId::new(id), [].into()), doc, &cached_file.covered_span, ) })) .chain((0..working_set.num_modules()).filter_map(|id| { Self::get_symbol_by_id( working_set, Id::Module(ModuleId::new(id), [].into()), doc, &cached_file.covered_span, ) })) // TODO: same variable symbol can be duplicated with different VarId .collect::<HashSet<Symbol>>() .into_iter() .collect(); all_symbols.sort(); all_symbols } /// Update the symbols of given uri if marked as dirty pub fn update(&mut self, uri: &Uri, engine_state: &EngineState, docs: &TextDocuments) { if *self.dirty_flags.get(uri).unwrap_or(&true) { let mut working_set = StateWorkingSet::new(engine_state); let content = docs .get_document_content(uri, None) .expect("Failed to get_document_content!") .as_bytes(); nu_parser::parse( &mut working_set, Some( uri_to_path(uri) .to_str() .expect("Failed to convert pathbuf to string"), ), content, false, ); for cached_file in working_set.files() { let path = std::path::Path::new(&*cached_file.name); if !path.is_file() { continue; } let target_uri = path_to_uri(path); let new_symbols = Self::extract_all_symbols( &working_set, docs.get_document(&target_uri) .unwrap_or(&FullTextDocument::new( "nu".to_string(), 0, String::from_utf8((*cached_file.content).to_vec()) .expect("Invalid UTF-8"), )), cached_file, ); self.cache.insert(target_uri.clone(), new_symbols); self.mark_dirty(target_uri, false); } self.mark_dirty(uri.clone(), false); }; } pub fn drop(&mut self, uri: &Uri) { self.cache.remove(uri); self.dirty_flags.remove(uri); } pub fn update_all(&mut self, engine_state: &EngineState, docs: &TextDocuments) { for uri in docs.documents().keys() { self.update(uri, engine_state, docs); } } pub fn get_symbols_by_uri(&self, uri: &Uri) -> Option<Vec<SymbolInformation>> { Some( self.cache .get(uri)? .iter() .map(|s| s.to_symbol_information(uri)) .collect(), ) } pub fn get_fuzzy_matched_symbols(&mut self, query: &str) -> Vec<SymbolInformation> { let pat = Pattern::new( query, CaseMatching::Smart, Normalization::Smart, AtomKind::Fuzzy, ); self.cache .iter() .flat_map(|(uri, symbols)| symbols.iter().map(|s| s.to_symbol_information(uri))) .filter_map(|s| { let mut buf = Vec::new(); let name = Utf32Str::new(&s.name, &mut buf); pat.score(name, &mut self.matcher)?; Some(s) }) .collect() } pub fn any_dirty(&self) -> bool { self.dirty_flags.values().any(|f| *f) } } impl LanguageServer { pub(crate) fn document_symbol( &mut self, params: &DocumentSymbolParams, ) -> Option<DocumentSymbolResponse> { let uri = &params.text_document.uri; let engine_state = self.new_engine_state(Some(uri)); let docs = self.docs.lock().ok()?; self.symbol_cache.update(uri, &engine_state, &docs); self.symbol_cache .get_symbols_by_uri(uri) .map(DocumentSymbolResponse::Flat) } pub(crate) fn workspace_symbol( &mut self, params: &WorkspaceSymbolParams, ) -> Option<WorkspaceSymbolResponse> { if self.symbol_cache.any_dirty() { let engine_state = self.new_engine_state(None); let docs = self.docs.lock().ok()?; self.symbol_cache.update_all(&engine_state, &docs); } Some(WorkspaceSymbolResponse::Flat( self.symbol_cache .get_fuzzy_matched_symbols(params.query.as_str()), )) } } #[cfg(test)] mod tests { use crate::path_to_uri; use crate::tests::{initialize_language_server, open_unchecked, result_from_message, update}; use assert_json_diff::assert_json_eq; use lsp_server::{Connection, Message}; use lsp_types::{ DocumentSymbolParams, PartialResultParams, Position, Range, TextDocumentIdentifier, Uri, WorkDoneProgressParams, WorkspaceSymbolParams, request::{DocumentSymbolRequest, Request, WorkspaceSymbolRequest}, }; use nu_test_support::fs::fixtures; use rstest::rstest; fn create_position(line: u32, character: u32) -> serde_json::Value { serde_json::json!({ "line": line, "character": character }) } fn create_range( start_line: u32, start_char: u32, end_line: u32, end_char: u32, ) -> serde_json::Value { serde_json::json!({ "start": create_position(start_line, start_char), "end": create_position(end_line, end_char) }) } fn create_symbol( name: &str, kind: u8, start_line: u32, start_char: u32, end_line: u32, end_char: u32, ) -> serde_json::Value { serde_json::json!({ "name": name, "kind": kind, "location": { "range": create_range(start_line, start_char, end_line, end_char) } }) } fn update_symbol_uri(symbols: &mut serde_json::Value, uri: &Uri) { if let Some(symbols_array) = symbols.as_array_mut() { for symbol in symbols_array { if let Some(location) = symbol.get_mut("location") { location["uri"] = serde_json::json!(uri.to_string()); } } } } fn send_document_symbol_request(client_connection: &Connection, uri: Uri) -> Message { client_connection .sender .send(Message::Request(lsp_server::Request { id: 1.into(), method: DocumentSymbolRequest::METHOD.to_string(), params: serde_json::to_value(DocumentSymbolParams { text_document: TextDocumentIdentifier { uri }, partial_result_params: PartialResultParams::default(), work_done_progress_params: WorkDoneProgressParams::default(), }) .unwrap(), })) .unwrap(); client_connection .receiver .recv_timeout(std::time::Duration::from_secs(2)) .unwrap() } fn send_workspace_symbol_request(client_connection: &Connection, query: String) -> Message { client_connection .sender .send(Message::Request(lsp_server::Request { id: 2.into(), method: WorkspaceSymbolRequest::METHOD.to_string(), params: serde_json::to_value(WorkspaceSymbolParams { query, partial_result_params: PartialResultParams::default(), work_done_progress_params: WorkDoneProgressParams::default(), }) .unwrap(), })) .unwrap(); client_connection .receiver .recv_timeout(std::time::Duration::from_secs(2)) .unwrap() } #[rstest] #[case::special_variables( "span.nu", None, serde_json::json!([]) )] #[case::basic_symbols( "foo.nu", None, serde_json::json!([ create_symbol("def_foo", 12, 5, 15, 5, 20), create_symbol("var_foo", 13, 2, 4, 2, 11) ]) )] #[case::after_update( "bar.nu", Some((String::default(), Range { start: Position { line: 2, character: 0 }, end: Position { line: 4, character: 29 } })), serde_json::json!([ create_symbol("var_bar", 13, 0, 13, 0, 20) ]) )] fn document_symbol_request( #[case] filename: &str, #[case] update_op: Option<(String, Range)>, #[case] mut expected: serde_json::Value, ) { let (client_connection, _recv) = initialize_language_server(None, None); let mut script = fixtures(); script.push("lsp/symbols"); script.push(filename); let script = path_to_uri(&script); open_unchecked(&client_connection, script.clone()); if let Some((content, range)) = update_op { update(&client_connection, script.clone(), content, Some(range)); } let resp = send_document_symbol_request(&client_connection, script.clone()); // Update expected JSON to include the actual URI update_symbol_uri(&mut expected, &script); assert_json_eq!(result_from_message(resp), expected); } #[rstest] #[case::search_br( "br", serde_json::json!([ create_symbol("def_bar", 12, 2, 22, 2, 27), create_symbol("var_bar", 13, 0, 13, 0, 20), create_symbol("module_bar", 2, 4, 26, 4, 27) ]) )] #[case::search_foo( "foo", serde_json::json!([ create_symbol("def_foo", 12, 5, 15, 5, 20), create_symbol("var_foo", 13, 2, 4, 2, 11) ]) )] fn workspace_symbol_request(#[case] query: &str, #[case] mut expected: serde_json::Value) { let (client_connection, _recv) = initialize_language_server(None, None); let mut script_foo = fixtures(); script_foo.push("lsp/symbols/foo.nu"); let script_foo = path_to_uri(&script_foo); let mut script_bar = fixtures(); script_bar.push("lsp/symbols/bar.nu"); let script_bar = path_to_uri(&script_bar); open_unchecked(&client_connection, script_foo.clone()); open_unchecked(&client_connection, script_bar.clone()); let resp = send_workspace_symbol_request(&client_connection, query.to_string()); // Determine which URI to use based on expected_file let target_uri = if query.contains("foo") { script_foo } else { script_bar }; // Update expected JSON to include the actual URI update_symbol_uri(&mut expected, &target_uri); assert_json_eq!(result_from_message(resp), expected); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-lsp/src/hints.rs
crates/nu-lsp/src/hints.rs
use crate::{LanguageServer, span_to_range}; use lsp_textdocument::FullTextDocument; use lsp_types::{ InlayHint, InlayHintKind, InlayHintLabel, InlayHintParams, InlayHintTooltip, MarkupContent, MarkupKind, Position, Range, }; use nu_protocol::{ Type, ast::{Argument, Block, Expr, Expression, Operator, Traverse}, engine::StateWorkingSet, }; use std::sync::Arc; fn type_short_name(t: &Type) -> String { match t { Type::Custom(_) => String::from("custom"), Type::Record(_) => String::from("record"), Type::Table(_) => String::from("table"), Type::List(_) => String::from("list"), _ => t.to_string(), } } fn extract_inlay_hints_from_expression( expr: &Expression, working_set: &StateWorkingSet, offset: &usize, file: &FullTextDocument, ) -> Vec<InlayHint> { match &expr.expr { Expr::BinaryOp(lhs, op, rhs) => { if let Expr::Operator(Operator::Assignment(_)) = op.expr { let position = span_to_range(&lhs.span, file, *offset).end; let type_rhs = type_short_name(&rhs.ty); let type_lhs = type_short_name(&lhs.ty); let type_string = match (type_lhs.as_str(), type_rhs.as_str()) { ("any", _) => type_rhs, (_, "any") => type_lhs, _ => type_lhs, }; vec![InlayHint { kind: Some(InlayHintKind::TYPE), label: InlayHintLabel::String(format!(": {type_string}")), position, text_edits: None, tooltip: None, data: None, padding_left: None, padding_right: None, }] } else { vec![] } } Expr::VarDecl(var_id) => { let position = span_to_range(&expr.span, file, *offset).end; // skip if the type is already specified in code if file .get_content(Some(Range { start: position, end: Position { line: position.line, character: position.character + 1, }, })) .contains(':') { return vec![]; } let var = working_set.get_variable(*var_id); let type_string = type_short_name(&var.ty); vec![InlayHint { kind: Some(InlayHintKind::TYPE), label: InlayHintLabel::String(format!(": {type_string}")), position, text_edits: None, tooltip: None, data: None, padding_left: None, padding_right: None, }] } Expr::Call(call) => { let decl = working_set.get_decl(call.decl_id); // skip those defined outside of the project let Some(block_id) = decl.block_id() else { return vec![]; }; if working_set.get_block(block_id).span.is_none() { return vec![]; }; let signatures = decl.signature(); let signatures = [ signatures.required_positional, signatures.optional_positional, ] .concat(); let arguments = &call.arguments; let mut sig_idx = 0; let mut hints = Vec::new(); for arg in arguments { match arg { // skip the rest when spread/unknown arguments encountered Argument::Spread(_) | Argument::Unknown(_) => { sig_idx = signatures.len(); continue; } Argument::Positional(_) => { if let Some(sig) = signatures.get(sig_idx) { sig_idx += 1; let position = span_to_range(&arg.span(), file, *offset).start; hints.push(InlayHint { kind: Some(InlayHintKind::PARAMETER), label: InlayHintLabel::String(format!("{}:", sig.name)), position, text_edits: None, tooltip: Some(InlayHintTooltip::MarkupContent(MarkupContent { kind: MarkupKind::Markdown, value: format!("`{}: {}`", sig.shape, sig.desc), })), data: None, padding_left: None, padding_right: None, }); } } // skip current for flags _ => { continue; } } } hints } _ => vec![], } } impl LanguageServer { pub(crate) fn get_inlay_hints(&mut self, params: &InlayHintParams) -> Option<Vec<InlayHint>> { self.inlay_hints.get(&params.text_document.uri).cloned() } pub(crate) fn extract_inlay_hints( working_set: &StateWorkingSet, block: &Arc<Block>, offset: usize, file: &FullTextDocument, ) -> Vec<InlayHint> { let closure = |e| extract_inlay_hints_from_expression(e, working_set, &offset, file); let mut results = Vec::new(); block.flat_map(working_set, &closure, &mut results); results } } #[cfg(test)] mod tests { use crate::path_to_uri; use crate::tests::{initialize_language_server, open_unchecked, result_from_message}; use assert_json_diff::assert_json_eq; use lsp_server::{Connection, Message}; use lsp_types::{ InlayHintParams, Position, Range, TextDocumentIdentifier, Uri, WorkDoneProgressParams, request::{InlayHintRequest, Request}, }; use nu_test_support::fs::fixtures; use rstest::rstest; fn send_inlay_hint_request(client_connection: &Connection, uri: Uri) -> Message { client_connection .sender .send(Message::Request(lsp_server::Request { id: 1.into(), method: InlayHintRequest::METHOD.to_string(), params: serde_json::to_value(InlayHintParams { text_document: TextDocumentIdentifier { uri }, work_done_progress_params: WorkDoneProgressParams::default(), // all inlay hints in the file are returned anyway range: Range { start: Position { line: 0, character: 0, }, end: Position { line: 0, character: 0, }, }, }) .unwrap(), })) .unwrap(); client_connection .receiver .recv_timeout(std::time::Duration::from_secs(2)) .unwrap() } #[rstest] #[case::variable_type( "type.nu", false, serde_json::json!([ { "position": { "line": 0, "character": 9 }, "label": ": int", "kind": 1 }, { "position": { "line": 1, "character": 7 }, "label": ": string", "kind": 1 }, { "position": { "line": 2, "character": 8 }, "label": ": bool", "kind": 1 }, { "position": { "line": 3, "character": 9 }, "label": ": float", "kind": 1 }, { "position": { "line": 4, "character": 8 }, "label": ": list", "kind": 1 }, { "position": { "line": 5, "character": 10 }, "label": ": record", "kind": 1 }, { "position": { "line": 6, "character": 11 }, "label": ": closure", "kind": 1 } ]) )] #[case::assignment_type( "assignment.nu", false, serde_json::json!([ { "position": { "line": 0, "character": 8 }, "label": ": int", "kind": 1 }, { "position": { "line": 1, "character": 10 }, "label": ": float", "kind": 1 }, { "position": { "line": 2, "character": 10 }, "label": ": table", "kind": 1 }, { "position": { "line": 3, "character": 9 }, "label": ": list", "kind": 1 }, { "position": { "line": 4, "character": 11 }, "label": ": record", "kind": 1 }, { "position": { "line": 6, "character": 7 }, "label": ": filesize", "kind": 1 }, { "position": { "line": 7, "character": 7 }, "label": ": filesize", "kind": 1 }, { "position": { "line": 8, "character": 4 }, "label": ": filesize", "kind": 1 } ]) )] #[case::parameter_names( "param.nu", false, serde_json::json!([ { "position": { "line": 9, "character": 9 }, "label": "a1:", "kind": 2, "tooltip": { "kind": "markdown", "value": "`any: `" } }, { "position": { "line": 9, "character": 11 }, "label": "a2:", "kind": 2, "tooltip": { "kind": "markdown", "value": "`any: `" } }, { "position": { "line": 9, "character": 18 }, "label": "a3:", "kind": 2, "tooltip": { "kind": "markdown", "value": "`any: arg3`" } }, { "position": { "line": 10, "character": 6 }, "label": "a1:", "kind": 2, "tooltip": { "kind": "markdown", "value": "`any: `" } }, { "position": { "line": 11, "character": 2 }, "label": "a2:", "kind": 2, "tooltip": { "kind": "markdown", "value": "`any: `" } }, { "position": { "line": 12, "character": 11 }, "label": "a1:", "kind": 2, "tooltip": { "kind": "markdown", "value": "`any: `" } }, { "position": { "line": 12, "character": 13 }, "label": "a2:", "kind": 2, "tooltip": { "kind": "markdown", "value": "`any: `" } } ]) )] #[case::script_loaded_on_init( "type.nu", true, serde_json::json!([ { "position": { "line": 0, "character": 9 }, "label": ": int", "kind": 1 }, { "position": { "line": 1, "character": 7 }, "label": ": string", "kind": 1 }, { "position": { "line": 2, "character": 8 }, "label": ": bool", "kind": 1 }, { "position": { "line": 3, "character": 9 }, "label": ": float", "kind": 1 }, { "position": { "line": 4, "character": 8 }, "label": ": list", "kind": 1 }, { "position": { "line": 5, "character": 10 }, "label": ": record", "kind": 1 }, { "position": { "line": 6, "character": 11 }, "label": ": closure", "kind": 1 } ]) )] fn inlay_hint_request( #[case] filename: &str, #[case] source_self: bool, #[case] expected: serde_json::Value, ) { let mut script = fixtures(); script.push("lsp/hints"); script.push(filename); let config = format!("source {}", script.to_str().unwrap()); let script = path_to_uri(&script); let (client_connection, _recv) = initialize_language_server(source_self.then_some(&config), None); open_unchecked(&client_connection, script.clone()); let resp = send_inlay_hint_request(&client_connection, script); assert_json_eq!(result_from_message(resp), expected); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-mcp/src/lib.rs
crates/nu-mcp/src/lib.rs
use nu_protocol::{ShellError, engine::EngineState, engine::StateWorkingSet, format_cli_error}; use rmcp::{ServiceExt, transport::stdio}; use server::NushellMcpServer; use tokio::runtime::Runtime; use tracing_subscriber::EnvFilter; use rmcp::ErrorData as McpError; mod evaluation; mod history; mod server; pub fn initialize_mcp_server(engine_state: EngineState) -> Result<(), ShellError> { tracing_subscriber::fmt() .with_env_filter(EnvFilter::from_default_env().add_directive(tracing::Level::DEBUG.into())) .with_writer(std::io::stderr) .with_ansi(false) .init(); tracing::info!("Starting MCP server"); let runtime = Runtime::new().map_err(|e| ShellError::GenericError { error: format!("Could not instantiate tokio: {e}"), msg: "".into(), span: None, help: None, inner: vec![], })?; runtime.block_on(async { if let Err(e) = run_server(engine_state).await { tracing::error!("Error running MCP server: {:?}", e); } }); Ok(()) } async fn run_server(engine_state: EngineState) -> Result<(), Box<dyn std::error::Error>> { NushellMcpServer::new(engine_state) .serve(stdio()) .await .inspect_err(|e| { tracing::error!("serving error: {:?}", e); })? .waiting() .await?; Ok(()) } pub(crate) fn shell_error_to_mcp_error( error: nu_protocol::ShellError, engine_state: &EngineState, ) -> McpError { // Use Nushell's rich error formatting to provide detailed, helpful error messages for LLMs let working_set = StateWorkingSet::new(engine_state); let formatted_error = format_cli_error(None, &working_set, &error, Some("nu::shell::error")); McpError::internal_error(formatted_error, None) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-mcp/src/history.rs
crates/nu-mcp/src/history.rs
use nu_protocol::{ Span, Type, Value, VarId, engine::{EngineState, Stack, StateWorkingSet}, }; use std::collections::VecDeque; const HISTORY_LIMIT_ENV_VAR: &str = "NU_MCP_HISTORY_LIMIT"; const DEFAULT_HISTORY_LIMIT: usize = 100; /// Ring buffer for storing command output history. /// /// Maintains a fixed-size buffer of values that can be accessed via the `$history` variable. /// When the buffer is full, oldest entries are evicted to make room for new ones. pub struct History { buffer: VecDeque<Value>, var_id: VarId, } impl History { /// Creates a new history buffer and registers the `$history` variable. pub fn new(engine_state: &mut EngineState) -> Self { let var_id = register_history_variable(engine_state); Self { buffer: VecDeque::new(), var_id, } } /// Returns the variable ID for `$history`. pub fn var_id(&self) -> VarId { self.var_id } /// Pushes a value to the history, evicting the oldest entry if at capacity. /// /// Returns the index at which the value was stored. pub fn push(&mut self, value: Value, engine_state: &EngineState, stack: &Stack) -> usize { let limit = history_limit(engine_state, stack); if self.buffer.len() >= limit { self.buffer.pop_front(); } let index = self.buffer.len(); self.buffer.push_back(value); index } /// Creates a `Value::list` containing all history entries for use in evaluation. pub fn as_value(&self) -> Value { let list: Vec<Value> = self.buffer.iter().cloned().collect(); Value::list(list, Span::unknown()) } } fn register_history_variable(engine_state: &mut EngineState) -> VarId { let mut working_set = StateWorkingSet::new(engine_state); let var_id = working_set.add_variable( b"history".to_vec(), Span::unknown(), Type::List(Box::new(Type::Any)), false, ); let delta = working_set.render(); engine_state .merge_delta(delta) .expect("failed to register $history variable"); var_id } /// Returns the history limit (max number of entries in the ring buffer). /// /// Defaults to 100 entries. Can be overridden via `NU_MCP_HISTORY_LIMIT` env var. fn history_limit(engine_state: &EngineState, stack: &Stack) -> usize { stack .get_env_var(engine_state, HISTORY_LIMIT_ENV_VAR) .and_then(|v| v.as_int().ok()) .and_then(|i| usize::try_from(i).ok()) .unwrap_or(DEFAULT_HISTORY_LIMIT) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-mcp/src/server.rs
crates/nu-mcp/src/server.rs
use std::sync::Arc; use nu_protocol::{UseAnsiColoring, engine::EngineState}; use rmcp::{ ErrorData as McpError, ServerHandler, handler::server::{tool::ToolRouter, wrapper::Parameters}, model::{ServerCapabilities, ServerInfo}, tool, tool_handler, tool_router, }; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use crate::evaluation::Evaluator; pub struct NushellMcpServer { tool_router: ToolRouter<Self>, evaluator: Evaluator, } #[tool_router] impl NushellMcpServer { pub fn new(mut engine_state: EngineState) -> Self { // Configure the engine state for MCP if let Some(config) = Arc::get_mut(&mut engine_state.config) { config.use_ansi_coloring = UseAnsiColoring::False; config.color_config.clear(); } NushellMcpServer { tool_router: Self::tool_router(), evaluator: Evaluator::new(engine_state), } } #[tool(description = r#"List available Nushell native commands. By default all available commands will be returned. To find a specific command by searching command names, descriptions and search terms, use the find parameter."#)] async fn list_commands( &self, Parameters(ListCommandsRequest { find }): Parameters<ListCommandsRequest>, ) -> Result<String, McpError> { let cmd = if let Some(f) = find { format!("help commands --find {f}") } else { "help commands".to_string() }; self.evaluator.eval(&cmd) } #[tool( description = "Get help for a specific Nushell command. This will only work on commands that are native to nushell. To find out if a command is native to nushell you can use the find_command tool." )] async fn command_help( &self, Parameters(CommandNameRequest { name }): Parameters<CommandNameRequest>, ) -> Result<String, McpError> { let cmd = format!("help {name}"); self.evaluator.eval(&cmd) } #[doc = include_str!("evaluate_tool.md")] #[tool] async fn evaluate( &self, Parameters(NuSourceRequest { input }): Parameters<NuSourceRequest>, ) -> Result<String, McpError> { self.evaluator.eval(&input) } } #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)] struct ListCommandsRequest { #[schemars(description = "string to find in command names, descriptions, and search term")] find: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)] struct CommandNameRequest { #[schemars(description = "The name of the command")] name: String, } #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)] struct NuSourceRequest { #[schemars(description = "The Nushell source code to evaluate")] input: String, } #[tool_handler] impl ServerHandler for NushellMcpServer { fn get_info(&self) -> ServerInfo { ServerInfo { instructions: Some(include_str!("instructions.md").to_string()), capabilities: ServerCapabilities::builder().enable_tools().build(), ..Default::default() } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-mcp/src/evaluation.rs
crates/nu-mcp/src/evaluation.rs
use crate::{history::History, shell_error_to_mcp_error}; use nu_protocol::{ PipelineData, PipelineExecutionData, Span, Value, debugger::WithoutDebug, engine::{EngineState, Stack, StateWorkingSet}, }; use std::{ sync::Mutex, time::{SystemTime, UNIX_EPOCH}, }; const OUTPUT_LIMIT_ENV_VAR: &str = "NU_MCP_OUTPUT_LIMIT"; const DEFAULT_OUTPUT_LIMIT: usize = 10 * 1024; // 10kb /// Evaluates Nushell code in a persistent REPL-style context for MCP. /// /// # Architecture /// /// The evaluator maintains a persistent `EngineState` and `Stack` that carry /// state across evaluations—just like an interactive REPL session. Each evaluation: /// 1. Parses code into a `Block` and gets a `StateDelta` via `working_set.render()` /// 2. **Merges the delta** into the persistent engine state /// 3. Evaluates the block with the persistent state and stack /// /// Step 2 ensures parsed blocks (including closures) are registered and available. /// /// # State Persistence /// /// Variables, definitions, and environment changes persist across calls, /// enabling workflows like: /// ```nu /// $env.MY_VAR = "hello" # First call /// $env.MY_VAR # Second call returns "hello" /// ``` /// /// # History /// /// The evaluator maintains a `$history` list that stores all command outputs. /// Each evaluation can access previous outputs via `$history.0`, `$history.1`, etc. /// History is stored as a ring buffer with a configurable limit (default: 100 entries) via /// `NU_MCP_HISTORY_LIMIT` env var. When the limit is reached, oldest entries are evicted. /// Large outputs are truncated in the response but stored in full in history. pub struct Evaluator { state: Mutex<EvalState>, } struct EvalState { engine_state: EngineState, stack: Stack, history: History, } impl Evaluator { pub fn new(mut engine_state: EngineState) -> Self { // Disable ANSI coloring for MCP - it's a computer-to-computer protocol let mut config = nu_protocol::Config::clone(engine_state.get_config()); config.use_ansi_coloring = nu_protocol::UseAnsiColoring::False; engine_state.set_config(config); let history = History::new(&mut engine_state); Self { state: Mutex::new(EvalState { engine_state, stack: Stack::new(), history, }), } } pub fn eval(&self, nu_source: &str) -> Result<String, rmcp::ErrorData> { let mut state = self.state.lock().expect("evaluator lock poisoned"); let EvalState { engine_state, stack, history, } = &mut *state; let (block, delta) = { let mut working_set = StateWorkingSet::new(engine_state); let block = nu_parser::parse(&mut working_set, None, nu_source.as_bytes(), false); if let Some(err) = working_set.parse_errors.first() { return Err(rmcp::ErrorData::internal_error( nu_protocol::format_cli_error(None, &working_set, err, None), None, )); } if let Some(err) = working_set.compile_errors.first() { return Err(rmcp::ErrorData::internal_error( nu_protocol::format_cli_error(None, &working_set, err, None), None, )); } (block, working_set.render()) }; engine_state .merge_delta(delta) .map_err(|e| shell_error_to_mcp_error(e, engine_state))?; // Set up $history variable on the stack before evaluation stack.add_var(history.var_id(), history.as_value()); let output = nu_engine::eval_block::<WithoutDebug>( engine_state, stack, &block, PipelineData::empty(), ) .map_err(|e| shell_error_to_mcp_error(e, engine_state))?; let cwd = engine_state .cwd(Some(stack)) .map(|p| p.to_string_lossy().into_owned()) .unwrap_or_else(|_| String::from("unknown")); let (output_value, output_nuon) = process_pipeline(output, engine_state)?; // Create timestamp for response let timestamp = SystemTime::now() .duration_since(UNIX_EPOCH) .map(|d| d.as_nanos() as i64) .unwrap_or(0); let timestamp_value = chrono::DateTime::from_timestamp_nanos(timestamp).fixed_offset(); // Store in history let history_index = history.push(output_value, engine_state, stack); let truncated = output_limit(engine_state, stack).is_some_and(|limit| output_nuon.len() > limit); let mut record = nu_protocol::record! { "cwd" => Value::string(cwd, Span::unknown()), "history_index" => Value::int(history_index as i64, Span::unknown()), "timestamp" => Value::date(timestamp_value, Span::unknown()), }; if truncated { record.push( "note", Value::string( format!("output truncated, full result in $history.{history_index}"), Span::unknown(), ), ); } else { record.push("output", Value::string(output_nuon, Span::unknown())); } let response = Value::record(record, Span::unknown()); nuon::to_nuon( engine_state, &response, nuon::ToStyle::Raw, Some(Span::unknown()), false, ) .map_err(|e| shell_error_to_mcp_error(e, engine_state)) } } /// Returns the output limit in bytes. /// /// Defaults to 10kb. Can be overridden via `NU_MCP_OUTPUT_LIMIT` env var. /// Set to `0` to disable truncation entirely. fn output_limit(engine_state: &EngineState, stack: &Stack) -> Option<usize> { let limit = stack .get_env_var(engine_state, OUTPUT_LIMIT_ENV_VAR) .and_then(|v| v.as_filesize().ok()) .and_then(|fs| usize::try_from(fs.get()).ok()) .unwrap_or(DEFAULT_OUTPUT_LIMIT); if limit == 0 { None } else { Some(limit) } } fn process_pipeline( pipeline_execution_data: PipelineExecutionData, engine_state: &EngineState, ) -> Result<(Value, String), rmcp::ErrorData> { let span = pipeline_execution_data.span(); if let PipelineData::ByteStream(stream, ..) = pipeline_execution_data.body { let mut buffer = Vec::new(); stream .write_to(&mut buffer) .map_err(|e| shell_error_to_mcp_error(e, engine_state))?; let string_output = String::from_utf8_lossy(&buffer).into_owned(); let value = Value::string(&string_output, Span::unknown()); return Ok((value, string_output)); } let mut values = Vec::new(); for item in pipeline_execution_data.body { if let Value::Error { error, .. } = &item { return Err(shell_error_to_mcp_error(*error.clone(), engine_state)); } values.push(item); } let value_to_store = match values.len() { 1 => values .pop() .expect("values has exactly one element; this cannot fail"), _ => Value::list(values, span.unwrap_or(Span::unknown())), }; let nuon_string = nuon::to_nuon( engine_state, &value_to_store, nuon::ToStyle::Raw, Some(Span::unknown()), false, ) .map_err(|e| shell_error_to_mcp_error(e, engine_state))?; Ok((value_to_store, nuon_string)) } #[cfg(test)] mod tests { use super::*; #[test] fn test_evaluator_response_format() -> Result<(), Box<dyn std::error::Error>> { let engine_state = nu_cmd_lang::create_default_context(); let evaluator = Evaluator::new(engine_state); let result = evaluator.eval("42")?; assert!( result.contains("history_index"), "Response should contain history_index, got: {result}" ); assert!( result.contains("cwd"), "Response should contain cwd, got: {result}" ); assert!( result.contains("timestamp"), "Response should contain timestamp, got: {result}" ); assert!( result.contains("output"), "Response should contain output, got: {result}" ); assert!( result.contains("42"), "Output should contain the evaluated value, got: {result}" ); Ok(()) } #[test] fn test_history_index_increments() -> Result<(), Box<dyn std::error::Error>> { let engine_state = nu_cmd_lang::create_default_context(); let evaluator = Evaluator::new(engine_state); let result1 = evaluator.eval("1")?; let result2 = evaluator.eval("2")?; let result3 = evaluator.eval("3")?; assert!( result1.contains("history_index:0") || result1.contains("history_index: 0"), "First result should have history_index: 0, got: {result1}" ); assert!( result2.contains("history_index:1") || result2.contains("history_index: 1"), "Second result should have history_index: 1, got: {result2}" ); assert!( result3.contains("history_index:2") || result3.contains("history_index: 2"), "Third result should have history_index: 2, got: {result3}" ); Ok(()) } #[test] fn test_history_variable_exists() -> Result<(), Box<dyn std::error::Error>> { let engine_state = nu_cmd_lang::create_default_context(); let evaluator = Evaluator::new(engine_state); evaluator.eval("42")?; let result = evaluator.eval("$history")?; assert!( result.contains("output"), "Should be able to access $history, got: {result}" ); assert!( result.contains("42"), "History should contain previous output 42, got: {result}" ); Ok(()) } #[test] fn test_history_access_by_index() -> Result<(), Box<dyn std::error::Error>> { let engine_state = nu_cmd_lang::create_default_context(); let evaluator = Evaluator::new(engine_state); evaluator.eval("100")?; evaluator.eval("200")?; let result = evaluator.eval("$history.0")?; assert!( result.contains("100"), "history.0 should be 100, got: {result}" ); let result = evaluator.eval("$history.1")?; assert!( result.contains("200"), "history.1 should be 200, got: {result}" ); Ok(()) } #[test] fn test_output_truncation() -> Result<(), Box<dyn std::error::Error>> { let engine_state = nu_cmd_lang::create_default_context(); let evaluator = Evaluator::new(engine_state); evaluator.eval("$env.NU_MCP_OUTPUT_LIMIT = 20b")?; let result = evaluator.eval("\"this is a very long string that exceeds the output limit\"")?; // Should have 'note' field instead of 'output' when truncated assert!( result.contains("note") && result.contains("truncated") && result.contains("$history"), "Large output should have note about truncation, got: {result}" ); assert!( !result.contains("output:"), "Truncated response should not have output field, got: {result}" ); Ok(()) } #[test] fn test_evaluator_parse_error_message() { let engine_state = nu_cmd_lang::create_default_context(); let evaluator = Evaluator::new(engine_state); let result = evaluator.eval("let x = [1, 2, 3"); assert!(result.is_err()); let err = result.unwrap_err(); let err_msg = err.message.to_string(); assert!( err_msg.contains("Error: nu::parser::") && err_msg.contains("unexpected_eof"), "Error message should contain error code 'nu::parser::unexpected_eof', but got: {err_msg}" ); assert!( err_msg.contains("let x = [1, 2, 3"), "Error message should contain source code context, but got: {err_msg}" ); assert!( !err_msg.contains('\x1b'), "Error message should not contain ANSI escape codes, but got: {err_msg:?}" ); assert!( !err_msg.contains("Span {"), "Error message should not contain raw Debug formatting, but got: {err_msg}" ); } #[test] fn test_evaluator_compile_error_message() { let engine_state = nu_cmd_lang::create_default_context(); let evaluator = Evaluator::new(engine_state); let result = evaluator.eval("[{a: 1}] | get a"); assert!(result.is_err()); let err = result.unwrap_err(); let err_msg = err.message.to_string(); assert!( err_msg.contains("Error: nu::compile::"), "Error message should contain error code 'nu::compile::', but got: {err_msg}" ); assert!( !err_msg.contains("Span {"), "Error message should not contain raw Debug formatting, but got: {err_msg}" ); } #[test] fn test_evaluator_runtime_error_message() { let engine_state = nu_cmd_lang::create_default_context(); let evaluator = Evaluator::new(engine_state); let result = evaluator.eval( r#"error make {msg: "custom runtime error" label: {text: "problem here" span: {start: 0 end: 5}}}"#, ); assert!(result.is_err()); let err = result.unwrap_err(); let err_msg = err.message.to_string(); assert!( err_msg.contains("Error:") && err_msg.contains("custom runtime error"), "Error message should contain rich formatting and custom error message, but got: {err_msg}" ); } #[test] fn test_closure_in_pipeline() { let engine_state = { let engine_state = nu_protocol::engine::EngineState::new(); nu_cmd_lang::add_default_context(engine_state) }; let evaluator = Evaluator::new(engine_state); let result = evaluator.eval(r#"do { |x| $x + 1 } 41"#); assert!( result.is_ok(), "Pipeline with closure should succeed: {:?}", result.err() ); let output = result.unwrap(); assert!( output.contains("42"), "Output should contain 42, got: {output}" ); } #[test] fn test_repl_variable_persistence() { let engine_state = nu_cmd_lang::create_default_context(); let evaluator = Evaluator::new(engine_state); let result = evaluator.eval("let x = 42"); assert!(result.is_ok(), "Setting variable should succeed"); let result = evaluator.eval("$x"); assert!( result.is_ok(), "Variable should be accessible: {:?}", result.err() ); let output = result.unwrap(); assert!( output.contains("42"), "Variable $x should be 42, got: {output}" ); } #[test] fn test_repl_env_persistence() { let engine_state = nu_cmd_lang::create_default_context(); let evaluator = Evaluator::new(engine_state); let result = evaluator.eval("$env.TEST_VAR = 'hello_repl'"); assert!(result.is_ok(), "Setting env var should succeed"); let result = evaluator.eval("$env.TEST_VAR"); assert!( result.is_ok(), "Env var should be accessible: {:?}", result.err() ); let output = result.unwrap(); assert!( output.contains("hello_repl"), "Env var should be 'hello_repl', got: {output}" ); } #[test] fn test_history_ring_buffer() -> Result<(), Box<dyn std::error::Error>> { let engine_state = nu_cmd_lang::create_default_context(); let evaluator = Evaluator::new(engine_state); // Set a small history limit evaluator.eval("$env.NU_MCP_HISTORY_LIMIT = 3")?; // Add items to history (the env var set above counts as first) // After limit=3 is set: history=[{set_result}] evaluator.eval("'second'")?; // history=[{set}, {second}] evaluator.eval("'third'")?; // history=[{set}, {second}, {third}] - at limit evaluator.eval("'fourth'")?; // evict oldest -> history=[{second}, {third}, {fourth}] evaluator.eval("'fifth'")?; // evict oldest -> history=[{third}, {fourth}, {fifth}] // At this point, before checking $history: // history = [{third}, {fourth}, {fifth}] // $history.0 should be "third" let result = evaluator.eval("$history.0")?; assert!( result.contains("third"), "Oldest entry should be 'third' after eviction, got: {result}" ); // After the above query, history was: // evict oldest -> [{fourth}, {fifth}] // append result -> [{fourth}, {fifth}, {result_of_query}] // So now $history.1 = "fifth" let result = evaluator.eval("$history.1")?; assert!( result.contains("fifth"), "Entry at index 1 should be 'fifth', got: {result}" ); Ok(()) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin/src/lib.rs
crates/nu-plugin/src/lib.rs
#![allow(clippy::needless_doctest_main)] //! # Nu Plugin: Plugin library for Nushell //! //! This crate contains the interface necessary to build Nushell plugins in Rust. //! Additionally, it contains public, but undocumented, items used by Nushell itself //! to interface with Nushell plugins. This documentation focuses on the interface //! needed to write an independent plugin. //! //! Nushell plugins are stand-alone applications that communicate with Nushell //! over stdin and stdout using a standardizes serialization framework to exchange //! the typed data that Nushell commands utilize natively. //! //! A typical plugin application will define a struct that implements the [`Plugin`] //! trait and then, in its main method, pass that [`Plugin`] to the [`serve_plugin()`] //! function, which will handle all of the input and output serialization when //! invoked by Nushell. //! //! ```rust,no_run //! use nu_plugin::{EvaluatedCall, MsgPackSerializer, serve_plugin}; //! use nu_plugin::{EngineInterface, Plugin, PluginCommand, SimplePluginCommand}; //! use nu_protocol::{LabeledError, Signature, Value}; //! //! struct MyPlugin; //! struct MyCommand; //! //! impl Plugin for MyPlugin { //! fn version(&self) -> String { //! env!("CARGO_PKG_VERSION").into() //! } //! //! fn commands(&self) -> Vec<Box<dyn PluginCommand<Plugin = Self>>> { //! vec![Box::new(MyCommand)] //! } //! } //! //! impl SimplePluginCommand for MyCommand { //! type Plugin = MyPlugin; //! //! fn name(&self) -> &str { //! "my-command" //! } //! //! fn description(&self) -> &str { //! todo!(); //! } //! //! fn signature(&self) -> Signature { //! todo!(); //! } //! //! fn run( //! &self, //! plugin: &MyPlugin, //! engine: &EngineInterface, //! call: &EvaluatedCall, //! input: &Value //! ) -> Result<Value, LabeledError> { //! todo!(); //! } //! } //! //! fn main() { //! serve_plugin(&MyPlugin{}, MsgPackSerializer) //! } //! ``` //! //! Nushell's source tree contains a //! [Plugin Example](https://github.com/nushell/nushell/tree/main/crates/nu_plugin_example) //! that demonstrates the full range of plugin capabilities. mod plugin; #[cfg(test)] mod test_util; pub use plugin::{EngineInterface, Plugin, PluginCommand, SimplePluginCommand, serve_plugin}; // Re-exports. Consider semver implications carefully. pub use nu_plugin_core::{JsonSerializer, MsgPackSerializer, PluginEncoder}; pub use nu_plugin_protocol::{DynamicCompletionCall, EvaluatedCall}; // Required by other internal crates. #[doc(hidden)] pub use plugin::{create_plugin_signature, serve_plugin_io};
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin/src/test_util.rs
crates/nu-plugin/src/test_util.rs
use nu_plugin_core::interface_test_util::TestCase; use nu_plugin_protocol::{PluginInput, PluginOutput}; use crate::plugin::EngineInterfaceManager; pub trait TestCaseExt { /// Create a new [`EngineInterfaceManager`] that writes to this test case. fn engine(&self) -> EngineInterfaceManager; } impl TestCaseExt for TestCase<PluginInput, PluginOutput> { fn engine(&self) -> EngineInterfaceManager { EngineInterfaceManager::new(self.clone()) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin/src/plugin/command.rs
crates/nu-plugin/src/plugin/command.rs
use nu_protocol::{ DynamicSuggestion, Example, IntoSpanned, LabeledError, PipelineData, PluginExample, PluginSignature, ShellError, Signature, Value, engine::ArgType, }; use crate::{DynamicCompletionCall, EngineInterface, EvaluatedCall, Plugin}; /// The API for a Nushell plugin command /// /// This is the trait that Nushell plugin commands must implement. The methods defined on /// `PluginCommand` are invoked by [`serve_plugin`](crate::serve_plugin) during plugin registration /// and execution. /// /// The plugin command must be able to be safely shared between threads, so that multiple /// invocations can be run in parallel. If interior mutability is desired, consider synchronization /// primitives such as [mutexes](std::sync::Mutex) and [channels](std::sync::mpsc). /// /// This version of the trait expects stream input and output. If you have a simple plugin that just /// operates on plain values, consider using [`SimplePluginCommand`] instead. /// /// # Examples /// Basic usage: /// ``` /// # use nu_plugin::*; /// # use nu_protocol::{LabeledError, PipelineData, Signals, Signature, Type, Value}; /// struct LowercasePlugin; /// struct Lowercase; /// /// impl PluginCommand for Lowercase { /// type Plugin = LowercasePlugin; /// /// fn name(&self) -> &str { /// "lowercase" /// } /// /// fn description(&self) -> &str { /// "Convert each string in a stream to lowercase" /// } /// /// fn signature(&self) -> Signature { /// Signature::build(PluginCommand::name(self)) /// .input_output_type(Type::List(Type::String.into()), Type::List(Type::String.into())) /// } /// /// fn run( /// &self, /// plugin: &LowercasePlugin, /// engine: &EngineInterface, /// call: &EvaluatedCall, /// input: PipelineData, /// ) -> Result<PipelineData, LabeledError> { /// let span = call.head; /// Ok(input.map(move |value| { /// value.as_str() /// .map(|string| Value::string(string.to_lowercase(), span)) /// // Errors in a stream should be returned as values. /// .unwrap_or_else(|err| Value::error(err, span)) /// }, &Signals::empty())?) /// } /// } /// /// # impl Plugin for LowercasePlugin { /// # fn version(&self) -> String { /// # "0.0.0".into() /// # } /// # fn commands(&self) -> Vec<Box<dyn PluginCommand<Plugin=Self>>> { /// # vec![Box::new(Lowercase)] /// # } /// # } /// # /// # fn main() { /// # serve_plugin(&LowercasePlugin{}, MsgPackSerializer) /// # } /// ``` pub trait PluginCommand: Sync { /// The type of plugin this command runs on. /// /// Since [`.run()`](Self::run) takes a reference to the plugin, it is necessary to define the /// type of plugin that the command expects here. type Plugin: Plugin; /// The name of the command from within Nu. /// /// In case this contains spaces, it will be treated as a subcommand. fn name(&self) -> &str; /// The signature of the command. /// /// This defines the arguments and input/output types of the command. fn signature(&self) -> Signature; /// A brief description of usage for the command. /// /// This should be short enough to fit in completion menus. fn description(&self) -> &str; /// Additional documentation for usage of the command. /// /// This is optional - any arguments documented by [`.signature()`](Self::signature) will be /// shown in the help page automatically. However, this can be useful for explaining things that /// would be too brief to include in [`.description()`](Self::description) and may span multiple lines. fn extra_description(&self) -> &str { "" } /// Search terms to help users find the command. /// /// A search query matching any of these search keywords, e.g. on `help --find`, will also /// show this command as a result. This may be used to suggest this command as a replacement /// for common system commands, or based alternate names for the functionality this command /// provides. /// /// For example, a `fold` command might mention `reduce` in its search terms. fn search_terms(&self) -> Vec<&str> { vec![] } /// Examples, in Nu, of how the command might be used. /// /// The examples are not restricted to only including this command, and may demonstrate /// pipelines using the command. A `result` may optionally be provided to show users what the /// command would return. /// /// `PluginTest::test_command_examples()` from the /// [`nu-plugin-test-support`](https://docs.rs/nu-plugin-test-support) crate can be used in /// plugin tests to automatically test that examples produce the `result`s as specified. fn examples(&self) -> Vec<Example<'_>> { vec![] } /// Perform the actual behavior of the plugin command. /// /// The behavior of the plugin is defined by the implementation of this method. When Nushell /// invoked the plugin [`serve_plugin`](crate::serve_plugin) will call this method and print the /// serialized returned value or error to stdout, which Nushell will interpret. /// /// `engine` provides an interface back to the Nushell engine. See [`EngineInterface`] docs for /// details on what methods are available. /// /// The `call` contains metadata describing how the plugin command was invoked, including /// arguments, and `input` contains the structured data piped into the command. /// /// This variant expects to receive and produce [`PipelineData`], which allows for stream-based /// handling of I/O. This is recommended if the plugin is expected to transform large /// lists or potentially large quantities of bytes. The API is more complex however, and /// [`SimplePluginCommand`] is recommended instead if this is not a concern. fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError>; #[allow(unused_variables)] /// Get completion items for `arg_type`. /// /// It's useful when you want to get auto completion items of a flag or positional argument /// dynamically. /// /// The implementation can returns 3 types of return values: /// - None: I couldn't find any suggestions, please fall back to default completions /// - Some(vec![]): there are no suggestions /// - Some(vec![item1, item2]): item1 and item2 are available #[expect(deprecated, reason = "forwarding experimental status")] fn get_dynamic_completion( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: DynamicCompletionCall, arg_type: ArgType, _experimental: nu_protocol::engine::ExperimentalMarker, ) -> Option<Vec<DynamicSuggestion>> { None } } /// The API for a simple Nushell plugin command /// /// This trait is an alternative to [`PluginCommand`], and operates on values instead of streams. /// Note that this may make handling large lists more difficult. /// /// The plugin command must be able to be safely shared between threads, so that multiple /// invocations can be run in parallel. If interior mutability is desired, consider synchronization /// primitives such as [mutexes](std::sync::Mutex) and [channels](std::sync::mpsc). /// /// # Examples /// Basic usage: /// ``` /// # use nu_plugin::*; /// # use nu_protocol::{LabeledError, Signature, Type, Value}; /// struct HelloPlugin; /// struct Hello; /// /// impl SimplePluginCommand for Hello { /// type Plugin = HelloPlugin; /// /// fn name(&self) -> &str { /// "hello" /// } /// /// fn description(&self) -> &str { /// "Every programmer's favorite greeting" /// } /// /// fn signature(&self) -> Signature { /// Signature::build(PluginCommand::name(self)) /// .input_output_type(Type::Nothing, Type::String) /// } /// /// fn run( /// &self, /// plugin: &HelloPlugin, /// engine: &EngineInterface, /// call: &EvaluatedCall, /// input: &Value, /// ) -> Result<Value, LabeledError> { /// Ok(Value::string("Hello, World!".to_owned(), call.head)) /// } /// } /// /// # impl Plugin for HelloPlugin { /// # fn version(&self) -> String { /// # "0.0.0".into() /// # } /// # fn commands(&self) -> Vec<Box<dyn PluginCommand<Plugin=Self>>> { /// # vec![Box::new(Hello)] /// # } /// # } /// # /// # fn main() { /// # serve_plugin(&HelloPlugin{}, MsgPackSerializer) /// # } /// ``` pub trait SimplePluginCommand: Sync { /// The type of plugin this command runs on. /// /// Since [`.run()`] takes a reference to the plugin, it is necessary to define the type of /// plugin that the command expects here. type Plugin: Plugin; /// The name of the command from within Nu. /// /// In case this contains spaces, it will be treated as a subcommand. fn name(&self) -> &str; /// The signature of the command. /// /// This defines the arguments and input/output types of the command. fn signature(&self) -> Signature; /// A brief description of usage for the command. /// /// This should be short enough to fit in completion menus. fn description(&self) -> &str; /// Additional documentation for usage of the command. /// /// This is optional - any arguments documented by [`.signature()`] will be shown in the help /// page automatically. However, this can be useful for explaining things that would be too /// brief to include in [`.description()`](Self::description) and may span multiple lines. fn extra_description(&self) -> &str { "" } /// Search terms to help users find the command. /// /// A search query matching any of these search keywords, e.g. on `help --find`, will also /// show this command as a result. This may be used to suggest this command as a replacement /// for common system commands, or based alternate names for the functionality this command /// provides. /// /// For example, a `fold` command might mention `reduce` in its search terms. fn search_terms(&self) -> Vec<&str> { vec![] } /// Examples, in Nu, of how the command might be used. /// /// The examples are not restricted to only including this command, and may demonstrate /// pipelines using the command. A `result` may optionally be provided to show users what the /// command would return. /// /// `PluginTest::test_command_examples()` from the /// [`nu-plugin-test-support`](https://docs.rs/nu-plugin-test-support) crate can be used in /// plugin tests to automatically test that examples produce the `result`s as specified. fn examples(&self) -> Vec<Example<'_>> { vec![] } /// Perform the actual behavior of the plugin command. /// /// The behavior of the plugin is defined by the implementation of this method. When Nushell /// invoked the plugin [`serve_plugin`](crate::serve_plugin) will call this method and print the /// serialized returned value or error to stdout, which Nushell will interpret. /// /// `engine` provides an interface back to the Nushell engine. See [`EngineInterface`] docs for /// details on what methods are available. /// /// The `call` contains metadata describing how the plugin command was invoked, including /// arguments, and `input` contains the structured data piped into the command. /// /// This variant does not support streaming. Consider implementing [`PluginCommand`] directly /// if streaming is desired. fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: &Value, ) -> Result<Value, LabeledError>; /// Get completion items for `arg_type`. /// /// It's useful when you want to get auto completion items of a flag or positional argument /// dynamically. /// /// The implementation can returns 3 types of return values: /// - None: I couldn't find any suggestions, please fall back to default completions /// - Some(vec![]): there are no suggestions /// - Some(vec![item1, item2]): item1 and item2 are available #[allow(unused_variables)] #[expect(deprecated, reason = "forwarding experimental status")] fn get_dynamic_completion( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: DynamicCompletionCall, arg_type: ArgType, _experimental: nu_protocol::engine::ExperimentalMarker, ) -> Option<Vec<DynamicSuggestion>> { None } } /// All [`SimplePluginCommand`]s can be used as [`PluginCommand`]s, but input streams will be fully /// consumed before the plugin command runs. impl<T> PluginCommand for T where T: SimplePluginCommand, { type Plugin = <Self as SimplePluginCommand>::Plugin; fn examples(&self) -> Vec<Example<'_>> { <Self as SimplePluginCommand>::examples(self) } fn extra_description(&self) -> &str { <Self as SimplePluginCommand>::extra_description(self) } fn name(&self) -> &str { <Self as SimplePluginCommand>::name(self) } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { // Unwrap the PipelineData from input, consuming the potential stream, and pass it to the // simpler signature in Plugin let span = input.span().unwrap_or(call.head); let input_value = input.into_value(span)?; // Wrap the output in PipelineData::value <Self as SimplePluginCommand>::run(self, plugin, engine, call, &input_value) .map(|value| PipelineData::value(value, None)) } fn search_terms(&self) -> Vec<&str> { <Self as SimplePluginCommand>::search_terms(self) } fn signature(&self) -> Signature { <Self as SimplePluginCommand>::signature(self) } fn description(&self) -> &str { <Self as SimplePluginCommand>::description(self) } #[allow(unused_variables)] #[allow(deprecated, reason = "internal usage")] fn get_dynamic_completion( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: DynamicCompletionCall, arg_type: ArgType, experimental: nu_protocol::engine::ExperimentalMarker, ) -> Option<Vec<DynamicSuggestion>> { <Self as SimplePluginCommand>::get_dynamic_completion( self, plugin, engine, call, arg_type, experimental, ) } } /// Build a [`PluginSignature`] from the signature-related methods on [`PluginCommand`]. /// /// This is sent to the engine on `plugin add`. /// /// This is not a public API. #[doc(hidden)] pub fn create_plugin_signature(command: &(impl PluginCommand + ?Sized)) -> PluginSignature { PluginSignature::new( // Add results of trait methods to signature command .signature() .description(command.description()) .extra_description(command.extra_description()) .search_terms( command .search_terms() .into_iter() .map(String::from) .collect(), ), // Convert `Example`s to `PluginExample`s command .examples() .into_iter() .map(PluginExample::from) .collect(), ) } /// Render examples to their base value so they can be sent in the response to `Signature`. pub(crate) fn render_examples( plugin: &impl Plugin, engine: &EngineInterface, examples: &mut [PluginExample], ) -> Result<(), ShellError> { for example in examples { if let Some(ref mut value) = example.result { value.recurse_mut(&mut |value| { let span = value.span(); match value { Value::Custom { .. } => { let value_taken = std::mem::replace(value, Value::nothing(span)); let Value::Custom { val, .. } = value_taken else { unreachable!() }; *value = plugin.custom_value_to_base_value(engine, val.into_spanned(span))?; Ok::<_, ShellError>(()) } _ => Ok(()), } })?; } } Ok(()) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin/src/plugin/mod.rs
crates/nu-plugin/src/plugin/mod.rs
use std::{ cmp::Ordering, collections::HashMap, env, ffi::OsString, ops::Deref, panic::AssertUnwindSafe, path::Path, sync::mpsc::{self, TrySendError}, thread, }; use nu_engine::documentation::{FormatterValue, HelpStyle, get_flags_section}; use nu_plugin_core::{ ClientCommunicationIo, CommunicationMode, InterfaceManager, PluginEncoder, PluginRead, PluginWrite, }; use nu_plugin_protocol::{ CallInfo, CustomValueOp, GetCompletionInfo, PluginCustomValue, PluginInput, PluginOutput, }; use nu_protocol::{ CustomValue, IntoSpanned, LabeledError, PipelineData, PluginMetadata, ShellError, Span, Spanned, Value, ast::Operator, casing::Casing, }; use thiserror::Error; use self::{command::render_examples, interface::ReceivedPluginCall}; mod command; mod interface; pub use command::{PluginCommand, SimplePluginCommand, create_plugin_signature}; pub use interface::{EngineInterface, EngineInterfaceManager}; /// This should be larger than the largest commonly sent message to avoid excessive fragmentation. /// /// The buffers coming from byte streams are typically each 8192 bytes, so double that. #[allow(dead_code)] pub(crate) const OUTPUT_BUFFER_SIZE: usize = 16384; /// The API for a Nushell plugin /// /// A plugin defines multiple commands, which are added to the engine when the user calls /// `plugin add`. /// /// The plugin must be able to be safely shared between threads, so that multiple invocations can /// be run in parallel. If interior mutability is desired, consider synchronization primitives such /// as [mutexes](std::sync::Mutex) and [channels](std::sync::mpsc). /// /// # Examples /// Basic usage: /// ``` /// # use nu_plugin::*; /// # use nu_protocol::{LabeledError, Signature, Type, Value}; /// struct HelloPlugin; /// struct Hello; /// /// impl Plugin for HelloPlugin { /// fn version(&self) -> String { /// env!("CARGO_PKG_VERSION").into() /// } /// /// fn commands(&self) -> Vec<Box<dyn PluginCommand<Plugin=Self>>> { /// vec![Box::new(Hello)] /// } /// } /// /// impl SimplePluginCommand for Hello { /// type Plugin = HelloPlugin; /// /// fn name(&self) -> &str { /// "hello" /// } /// /// fn description(&self) -> &str { /// "Every programmer's favorite greeting" /// } /// /// fn signature(&self) -> Signature { /// Signature::build(PluginCommand::name(self)) /// .input_output_type(Type::Nothing, Type::String) /// } /// /// fn run( /// &self, /// plugin: &HelloPlugin, /// engine: &EngineInterface, /// call: &EvaluatedCall, /// input: &Value, /// ) -> Result<Value, LabeledError> { /// Ok(Value::string("Hello, World!".to_owned(), call.head)) /// } /// } /// /// # fn main() { /// # serve_plugin(&HelloPlugin{}, MsgPackSerializer) /// # } /// ``` pub trait Plugin: Sync { /// The version of the plugin. /// /// The recommended implementation, which will use the version from your crate's `Cargo.toml` /// file: /// /// ```no_run /// # use nu_plugin::{Plugin, PluginCommand}; /// # struct MyPlugin; /// # impl Plugin for MyPlugin { /// fn version(&self) -> String { /// env!("CARGO_PKG_VERSION").into() /// } /// # fn commands(&self) -> Vec<Box<dyn PluginCommand<Plugin = Self>>> { vec![] } /// # } /// ``` fn version(&self) -> String; /// The commands supported by the plugin /// /// Each [`PluginCommand`] contains both the signature of the command and the functionality it /// implements. /// /// This is only called once by [`serve_plugin`] at the beginning of your plugin's execution. It /// is not possible to change the defined commands during runtime. fn commands(&self) -> Vec<Box<dyn PluginCommand<Plugin = Self>>>; /// Collapse a custom value to plain old data. /// /// The default implementation of this method just calls [`CustomValue::to_base_value`], but /// the method can be implemented differently if accessing plugin state is desirable. fn custom_value_to_base_value( &self, engine: &EngineInterface, custom_value: Spanned<Box<dyn CustomValue>>, ) -> Result<Value, LabeledError> { let _ = engine; custom_value .item .to_base_value(custom_value.span) .map_err(LabeledError::from) } /// Follow a numbered cell path on a custom value - e.g. `value.0`. /// /// The default implementation of this method just calls [`CustomValue::follow_path_int`], but /// the method can be implemented differently if accessing plugin state is desirable. fn custom_value_follow_path_int( &self, engine: &EngineInterface, custom_value: Spanned<Box<dyn CustomValue>>, index: Spanned<usize>, optional: bool, ) -> Result<Value, LabeledError> { let _ = engine; custom_value .item .follow_path_int(custom_value.span, index.item, index.span, optional) .map_err(LabeledError::from) } /// Follow a named cell path on a custom value - e.g. `value.column`. /// /// The default implementation of this method just calls [`CustomValue::follow_path_string`], /// but the method can be implemented differently if accessing plugin state is desirable. fn custom_value_follow_path_string( &self, engine: &EngineInterface, custom_value: Spanned<Box<dyn CustomValue>>, column_name: Spanned<String>, optional: bool, casing: Casing, ) -> Result<Value, LabeledError> { let _ = engine; custom_value .item .follow_path_string( custom_value.span, column_name.item, column_name.span, optional, casing, ) .map_err(LabeledError::from) } /// Implement comparison logic for custom values. /// /// The default implementation of this method just calls [`CustomValue::partial_cmp`], but /// the method can be implemented differently if accessing plugin state is desirable. /// /// Note that returning an error here is unlikely to produce desired behavior, as `partial_cmp` /// lacks a way to produce an error. At the moment the engine just logs the error, and the /// comparison returns `None`. fn custom_value_partial_cmp( &self, engine: &EngineInterface, custom_value: Box<dyn CustomValue>, other_value: Value, ) -> Result<Option<Ordering>, LabeledError> { let _ = engine; Ok(custom_value.partial_cmp(&other_value)) } /// Implement functionality for an operator on a custom value. /// /// The default implementation of this method just calls [`CustomValue::operation`], but /// the method can be implemented differently if accessing plugin state is desirable. fn custom_value_operation( &self, engine: &EngineInterface, left: Spanned<Box<dyn CustomValue>>, operator: Spanned<Operator>, right: Value, ) -> Result<Value, LabeledError> { let _ = engine; left.item .operation(left.span, operator.item, operator.span, &right) .map_err(LabeledError::from) } /// Implement saving logic for a custom value. /// /// The default implementation of this method just calls [`CustomValue::save`], but /// the method can be implemented differently if accessing plugin state is desirable. fn custom_value_save( &self, engine: &EngineInterface, value: Spanned<Box<dyn CustomValue>>, path: Spanned<&Path>, save_call_span: Span, ) -> Result<(), LabeledError> { let _ = engine; value .item .save(path, value.span, save_call_span) .map_err(LabeledError::from) } /// Handle a notification that all copies of a custom value within the engine have been dropped. /// /// This notification is only sent if [`CustomValue::notify_plugin_on_drop`] was true. Unlike /// the other custom value handlers, a span is not provided. /// /// Note that a new custom value is created each time it is sent to the engine - if you intend /// to accept a custom value and send it back, you may need to implement some kind of unique /// reference counting in your plugin, as you will receive multiple drop notifications even if /// the data within is identical. /// /// The default implementation does nothing. Any error generated here is unlikely to be visible /// to the user, and will only show up in the engine's log output. fn custom_value_dropped( &self, engine: &EngineInterface, custom_value: Box<dyn CustomValue>, ) -> Result<(), LabeledError> { let _ = (engine, custom_value); Ok(()) } } /// Function used to implement the communication protocol between nushell and an external plugin. /// /// When creating a new plugin this function is typically used as the main entry /// point for the plugin, e.g. /// /// ```rust,no_run /// # use nu_plugin::*; /// # use nu_protocol::{PluginSignature, Value}; /// # struct MyPlugin; /// # impl MyPlugin { fn new() -> Self { Self }} /// # impl Plugin for MyPlugin { /// # fn version(&self) -> String { "0.0.0".into() } /// # fn commands(&self) -> Vec<Box<dyn PluginCommand<Plugin=Self>>> {todo!();} /// # } /// fn main() { /// serve_plugin(&MyPlugin::new(), MsgPackSerializer) /// } /// ``` pub fn serve_plugin(plugin: &impl Plugin, encoder: impl PluginEncoder + 'static) { let args: Vec<OsString> = env::args_os().skip(1).collect(); // Determine the plugin name, for errors let exe = std::env::current_exe().ok(); let plugin_name: String = exe .as_ref() .and_then(|path| path.file_stem()) .map(|stem| stem.to_string_lossy().into_owned()) .map(|stem| { stem.strip_prefix("nu_plugin_") .map(|s| s.to_owned()) .unwrap_or(stem) }) .unwrap_or_else(|| "(unknown)".into()); if args.is_empty() || args[0] == "-h" || args[0] == "--help" { print_help(plugin, encoder); std::process::exit(0) } // Implement different communication modes: let mode = if args[0] == "--stdio" && args.len() == 1 { // --stdio always supported. CommunicationMode::Stdio } else if args[0] == "--local-socket" && args.len() == 2 { #[cfg(feature = "local-socket")] { CommunicationMode::LocalSocket((&args[1]).into()) } #[cfg(not(feature = "local-socket"))] { eprintln!("{plugin_name}: local socket mode is not supported"); std::process::exit(1); } } else { eprintln!( "{}: This plugin must be run from within Nushell. See `plugin add --help` for details \ on how to use plugins.", env::current_exe() .map(|path| path.display().to_string()) .unwrap_or_else(|_| "plugin".into()) ); eprintln!( "If you are running from Nushell, this plugin may be incompatible with the \ version of nushell you are using." ); std::process::exit(1) }; let encoder_clone = encoder.clone(); let result = match mode.connect_as_client() { Ok(ClientCommunicationIo::Stdio(stdin, mut stdout)) => { tell_nushell_encoding(&mut stdout, &encoder).expect("failed to tell nushell encoding"); serve_plugin_io( plugin, &plugin_name, move || (stdin.lock(), encoder_clone), move || (stdout, encoder), ) } #[cfg(feature = "local-socket")] Ok(ClientCommunicationIo::LocalSocket { read_in, mut write_out, }) => { use std::io::{BufReader, BufWriter}; use std::sync::Mutex; tell_nushell_encoding(&mut write_out, &encoder) .expect("failed to tell nushell encoding"); let read = BufReader::with_capacity(OUTPUT_BUFFER_SIZE, read_in); let write = Mutex::new(BufWriter::with_capacity(OUTPUT_BUFFER_SIZE, write_out)); serve_plugin_io( plugin, &plugin_name, move || (read, encoder_clone), move || (write, encoder), ) } Err(err) => { eprintln!("{plugin_name}: failed to connect: {err:?}"); std::process::exit(1); } }; match result { Ok(()) => (), // Write unreported errors to the console Err(ServePluginError::UnreportedError(err)) => { eprintln!("Plugin `{plugin_name}` error: {err}"); std::process::exit(1); } Err(_) => std::process::exit(1), } } fn tell_nushell_encoding( writer: &mut impl std::io::Write, encoder: &impl PluginEncoder, ) -> Result<(), std::io::Error> { // tell nushell encoding. // // 1 byte // encoding format: | content-length | content | let encoding = encoder.name(); let length = encoding.len() as u8; let mut encoding_content: Vec<u8> = encoding.as_bytes().to_vec(); encoding_content.insert(0, length); writer.write_all(&encoding_content)?; writer.flush() } /// An error from [`serve_plugin_io()`] #[derive(Debug, Error)] pub enum ServePluginError { /// An error occurred that could not be reported to the engine. #[error("{0}")] UnreportedError(#[source] ShellError), /// An error occurred that could be reported to the engine. #[error("{0}")] ReportedError(#[source] ShellError), /// A version mismatch occurred. #[error("{0}")] Incompatible(#[source] ShellError), /// An I/O error occurred. #[error("{0}")] IOError(#[source] ShellError), /// A thread spawning error occurred. #[error("{0}")] ThreadSpawnError(#[source] std::io::Error), /// A panic occurred. #[error("a panic occurred in a plugin thread")] Panicked, } impl From<ShellError> for ServePluginError { fn from(error: ShellError) -> Self { match error { ShellError::Io(_) => ServePluginError::IOError(error), ShellError::PluginFailedToLoad { .. } => ServePluginError::Incompatible(error), _ => ServePluginError::UnreportedError(error), } } } /// Convert result error to ReportedError if it can be reported to the engine. trait TryToReport { type T; fn try_to_report(self, engine: &EngineInterface) -> Result<Self::T, ServePluginError>; } impl<T, E> TryToReport for Result<T, E> where E: Into<ServePluginError>, { type T = T; fn try_to_report(self, engine: &EngineInterface) -> Result<T, ServePluginError> { self.map_err(|e| match e.into() { ServePluginError::UnreportedError(err) => { if engine.write_response(Err(err.clone())).is_ok() { ServePluginError::ReportedError(err) } else { ServePluginError::UnreportedError(err) } } other => other, }) } } /// Serve a plugin on the given input & output. /// /// Unlike [`serve_plugin`], this doesn't assume total control over the process lifecycle / stdin / /// stdout, and can be used for more advanced use cases. /// /// This is not a public API. #[doc(hidden)] pub fn serve_plugin_io<I, O>( plugin: &impl Plugin, plugin_name: &str, input: impl FnOnce() -> I + Send + 'static, output: impl FnOnce() -> O + Send + 'static, ) -> Result<(), ServePluginError> where I: PluginRead<PluginInput> + 'static, O: PluginWrite<PluginOutput> + 'static, { let (error_tx, error_rx) = mpsc::channel(); // Build commands map, to make running a command easier let mut commands: HashMap<String, _> = HashMap::new(); for command in plugin.commands() { if let Some(previous) = commands.insert(command.name().into(), command) { eprintln!( "Plugin `{plugin_name}` warning: command `{}` shadowed by another command with the \ same name. Check your commands' `name()` methods", previous.name() ); } } let mut manager = EngineInterfaceManager::new(output()); let call_receiver = manager .take_plugin_call_receiver() // This expect should be totally safe, as we just created the manager .expect("take_plugin_call_receiver returned None"); // We need to hold on to the interface to keep the manager alive. We can drop it at the end let interface = manager.get_interface(); // Send Hello message interface.hello()?; { // Spawn the reader thread let error_tx = error_tx.clone(); std::thread::Builder::new() .name("engine interface reader".into()) .spawn(move || { // Report the error on the channel if we get an error if let Err(err) = manager.consume_all(input()) { let _ = error_tx.send(ServePluginError::from(err)); } }) .map_err(ServePluginError::ThreadSpawnError)?; } // Handle each Run plugin call on a thread thread::scope(|scope| { let run = |engine, call_info| { // SAFETY: It should be okay to use `AssertUnwindSafe` here, because we don't use any // of the references after we catch the unwind, and immediately exit. let unwind_result = std::panic::catch_unwind(AssertUnwindSafe(|| { let CallInfo { name, call, input } = call_info; let result = if let Some(command) = commands.get(&name) { command.run(plugin, &engine, &call, input) } else { Err( LabeledError::new(format!("Plugin command not found: `{name}`")) .with_label( format!("plugin `{plugin_name}` doesn't have this command"), call.head, ), ) }; let write_result = engine .write_response(result) .and_then(|writer| writer.write()) .try_to_report(&engine); if let Err(err) = write_result { let _ = error_tx.send(err); } })); if unwind_result.is_err() { // Exit after unwind if a panic occurred std::process::exit(1); } }; let get_dynamic_completion = |engine, get_dynamic_completion_info| { // SAFETY: It should be okay to use `AssertUnwindSafe` here, because we don't use any // of the references after we catch the unwind, and immediately exit. let unwind_result = std::panic::catch_unwind(AssertUnwindSafe(|| { let GetCompletionInfo { name, arg_type, call, } = get_dynamic_completion_info; let items = if let Some(command) = commands.get(&name) { let arg_type = arg_type.into(); command.get_dynamic_completion( plugin, &engine, call, arg_type, #[expect(deprecated, reason = "internal usage")] nu_protocol::engine::ExperimentalMarker, ) } else { None }; let write_result = engine.write_completion_items(items).try_to_report(&engine); if let Err(err) = write_result { let _ = error_tx.send(err); } })); if unwind_result.is_err() { // Exit after unwind if a panic occurred std::process::exit(1); } }; // As an optimization: create one thread that can be reused for Run calls in sequence let (run_tx, run_rx) = mpsc::sync_channel(0); thread::Builder::new() .name("plugin runner (primary)".into()) .spawn_scoped(scope, move || { for (engine, call) in run_rx { run(engine, call); } }) .map_err(ServePluginError::ThreadSpawnError)?; for plugin_call in call_receiver { // Check for pending errors if let Ok(error) = error_rx.try_recv() { return Err(error); } match plugin_call { // Send metadata back to nushell so it can be stored with the plugin signatures ReceivedPluginCall::Metadata { engine } => { engine .write_metadata(PluginMetadata::new().with_version(plugin.version())) .try_to_report(&engine)?; } // Sending the signature back to nushell to create the declaration definition ReceivedPluginCall::Signature { engine } => { let sigs = commands .values() .map(|command| create_plugin_signature(command.deref())) .map(|mut sig| { render_examples(plugin, &engine, &mut sig.examples)?; Ok(sig) }) .collect::<Result<Vec<_>, ShellError>>() .try_to_report(&engine)?; engine.write_signature(sigs).try_to_report(&engine)?; } // Run the plugin on a background thread, handling any input or output streams ReceivedPluginCall::Run { engine, call } => { // Try to run it on the primary thread match run_tx.try_send((engine, call)) { Ok(()) => (), // If the primary thread isn't ready, spawn a secondary thread to do it Err(TrySendError::Full((engine, call))) | Err(TrySendError::Disconnected((engine, call))) => { thread::Builder::new() .name("plugin runner (secondary)".into()) .spawn_scoped(scope, move || run(engine, call)) .map_err(ServePluginError::ThreadSpawnError)?; } } } // Do an operation on a custom value ReceivedPluginCall::CustomValueOp { engine, custom_value, op, } => { custom_value_op(plugin, &engine, custom_value, op).try_to_report(&engine)?; } ReceivedPluginCall::GetCompletion { engine, info } => { get_dynamic_completion(engine, info) } } } Ok::<_, ServePluginError>(()) })?; // This will stop the manager drop(interface); // Receive any error left on the channel if let Ok(err) = error_rx.try_recv() { Err(err) } else { Ok(()) } } fn custom_value_op( plugin: &impl Plugin, engine: &EngineInterface, custom_value: Spanned<PluginCustomValue>, op: CustomValueOp, ) -> Result<(), ShellError> { let local_value = custom_value .item .deserialize_to_custom_value(custom_value.span)? .into_spanned(custom_value.span); match op { CustomValueOp::ToBaseValue => { let result = plugin .custom_value_to_base_value(engine, local_value) .map(|value| PipelineData::value(value, None)); engine .write_response(result) .and_then(|writer| writer.write()) } CustomValueOp::FollowPathInt { index, optional } => { let result = plugin .custom_value_follow_path_int(engine, local_value, index, optional) .map(|value| PipelineData::value(value, None)); engine .write_response(result) .and_then(|writer| writer.write()) } CustomValueOp::FollowPathString { column_name, optional, casing, } => { let result = plugin .custom_value_follow_path_string(engine, local_value, column_name, optional, casing) .map(|value| PipelineData::value(value, None)); engine .write_response(result) .and_then(|writer| writer.write()) } CustomValueOp::PartialCmp(mut other_value) => { PluginCustomValue::deserialize_custom_values_in(&mut other_value)?; match plugin.custom_value_partial_cmp(engine, local_value.item, other_value) { Ok(ordering) => engine.write_ordering(ordering), Err(err) => engine .write_response(Err(err)) .and_then(|writer| writer.write()), } } CustomValueOp::Operation(operator, mut right) => { PluginCustomValue::deserialize_custom_values_in(&mut right)?; let result = plugin .custom_value_operation(engine, local_value, operator, right) .map(|value| PipelineData::value(value, None)); engine .write_response(result) .and_then(|writer| writer.write()) } CustomValueOp::Save { path, save_call_span, } => { let path = Spanned { item: path.item.as_path(), span: path.span, }; let result = plugin.custom_value_save(engine, local_value, path, save_call_span); engine.write_ok(result) } CustomValueOp::Dropped => { let result = plugin .custom_value_dropped(engine, local_value.item) .map(|_| PipelineData::empty()); engine .write_response(result) .and_then(|writer| writer.write()) } } } fn print_help(plugin: &impl Plugin, encoder: impl PluginEncoder) { use std::fmt::Write; println!("Nushell Plugin"); println!("Encoder: {}", encoder.name()); println!("Version: {}", plugin.version()); // Determine the plugin name let exe = std::env::current_exe().ok(); let plugin_name: String = exe .as_ref() .map(|stem| stem.to_string_lossy().into_owned()) .unwrap_or_else(|| "(unknown)".into()); println!("Plugin file path: {plugin_name}"); let mut help = String::new(); let help_style = HelpStyle::default(); plugin.commands().into_iter().for_each(|command| { let signature = command.signature(); let res = write!(help, "\nCommand: {}", command.name()) .and_then(|_| writeln!(help, "\nDescription:\n > {}", command.description())) .and_then(|_| { if !command.extra_description().is_empty() { writeln!( help, "\nExtra description:\n > {}", command.extra_description() ) } else { Ok(()) } }) .and_then(|_| { let flags = get_flags_section(&signature, &help_style, |v| match v { FormatterValue::DefaultValue(value) => format!("{value:#?}"), FormatterValue::CodeString(text) => text.to_string(), }); write!(help, "{flags}") }) .and_then(|_| writeln!(help, "\nParameters:")) .and_then(|_| { signature .required_positional .iter() .try_for_each(|positional| { writeln!( help, " {} <{}>: {}", positional.name, positional.shape, positional.desc ) }) }) .and_then(|_| { signature .optional_positional .iter() .try_for_each(|positional| { writeln!( help, " (optional) {} <{}>: {}", positional.name, positional.shape, positional.desc ) }) }) .and_then(|_| { if let Some(rest_positional) = &signature.rest_positional { writeln!( help, " ...{} <{}>: {}", rest_positional.name, rest_positional.shape, rest_positional.desc ) } else { Ok(()) } }) .and_then(|_| writeln!(help, "======================")); if res.is_err() { println!("{res:?}") } }); println!("{help}") }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin/src/plugin/interface/tests.rs
crates/nu-plugin/src/plugin/interface/tests.rs
use crate::test_util::TestCaseExt; use super::{EngineInterfaceManager, ReceivedPluginCall}; use nu_engine::command_prelude::IoError; use nu_plugin_core::{Interface, InterfaceManager, interface_test_util::TestCase}; use nu_plugin_protocol::{ ByteStreamInfo, CallInfo, CustomValueOp, EngineCall, EngineCallId, EngineCallResponse, EvaluatedCall, ListStreamInfo, PipelineDataHeader, PluginCall, PluginCallResponse, PluginCustomValue, PluginInput, PluginOutput, Protocol, ProtocolInfo, StreamData, test_util::{TestCustomValue, expected_test_custom_value, test_plugin_custom_value}, }; use nu_protocol::{ BlockId, ByteStreamType, Config, CustomValue, IntoInterruptiblePipelineData, LabeledError, PipelineData, PluginSignature, ShellError, Signals, Span, Spanned, Value, VarId, engine::Closure, shell_error, }; use std::{ collections::HashMap, sync::{ Arc, mpsc::{self, TryRecvError}, }, }; #[test] fn is_using_stdio_is_false_for_test() { let test = TestCase::new(); let manager = test.engine(); let interface = manager.get_interface(); assert!(!interface.is_using_stdio()); } #[test] fn manager_consume_all_consumes_messages() -> Result<(), ShellError> { let mut test = TestCase::new(); let mut manager = test.engine(); // This message should be non-problematic test.add(PluginInput::Hello(ProtocolInfo::default())); manager.consume_all(&mut test)?; assert!(!test.has_unconsumed_read()); Ok(()) } #[test] fn manager_consume_all_exits_after_streams_and_interfaces_are_dropped() -> Result<(), ShellError> { let mut test = TestCase::new(); let mut manager = test.engine(); // Add messages that won't cause errors for _ in 0..5 { test.add(PluginInput::Hello(ProtocolInfo::default())); } // Create a stream... let stream = manager.read_pipeline_data( PipelineDataHeader::list_stream(ListStreamInfo::new(0, Span::test_data())), &Signals::empty(), )?; // and an interface... let interface = manager.get_interface(); // Expect that is_finished is false assert!( !manager.is_finished(), "is_finished is true even though active stream/interface exists" ); // After dropping, it should be true drop(stream); drop(interface); assert!( manager.is_finished(), "is_finished is false even though manager has no stream or interface" ); // When it's true, consume_all shouldn't consume everything manager.consume_all(&mut test)?; assert!( test.has_unconsumed_read(), "consume_all consumed the messages" ); Ok(()) } fn test_io_error() -> ShellError { ShellError::Io(IoError::new_with_additional_context( shell_error::io::ErrorKind::from_std(std::io::ErrorKind::Other), Span::test_data(), None, "test io error", )) } fn check_test_io_error(error: &ShellError) { assert!( format!("{error:?}").contains("test io error"), "error: {error}" ); } #[test] fn manager_consume_all_propagates_io_error_to_readers() -> Result<(), ShellError> { let mut test = TestCase::new(); let mut manager = test.engine(); test.set_read_error(test_io_error()); let stream = manager.read_pipeline_data( PipelineDataHeader::list_stream(ListStreamInfo::new(0, Span::test_data())), &Signals::empty(), )?; manager .consume_all(&mut test) .expect_err("consume_all did not error"); // Ensure end of stream drop(manager); let value = stream.into_iter().next().expect("stream is empty"); if let Value::Error { error, .. } = value { check_test_io_error(&error); Ok(()) } else { panic!("did not get an error"); } } fn invalid_input() -> PluginInput { // This should definitely cause an error, as 0.0.0 is not compatible with any version other than // itself PluginInput::Hello(ProtocolInfo { protocol: Protocol::NuPlugin, version: "0.0.0".into(), features: vec![], }) } fn check_invalid_input_error(error: &ShellError) { // the error message should include something about the version... assert!(format!("{error:?}").contains("0.0.0"), "error: {error}"); } #[test] fn manager_consume_all_propagates_message_error_to_readers() -> Result<(), ShellError> { let mut test = TestCase::new(); let mut manager = test.engine(); test.add(invalid_input()); let stream = manager.read_pipeline_data( PipelineDataHeader::byte_stream(ByteStreamInfo::new( 0, Span::test_data(), ByteStreamType::Unknown, )), &Signals::empty(), )?; manager .consume_all(&mut test) .expect_err("consume_all did not error"); // Ensure end of stream drop(manager); let value = stream.into_iter().next().expect("stream is empty"); if let Value::Error { error, .. } = value { check_invalid_input_error(&error); Ok(()) } else { panic!("did not get an error"); } } fn fake_engine_call( manager: &mut EngineInterfaceManager, id: EngineCallId, ) -> mpsc::Receiver<EngineCallResponse<PipelineData>> { // Set up a fake engine call subscription let (tx, rx) = mpsc::channel(); manager.engine_call_subscriptions.insert(id, tx); rx } #[test] fn manager_consume_all_propagates_io_error_to_engine_calls() -> Result<(), ShellError> { let mut test = TestCase::new(); let mut manager = test.engine(); let interface = manager.get_interface(); test.set_read_error(test_io_error()); // Set up a fake engine call subscription let rx = fake_engine_call(&mut manager, 0); manager .consume_all(&mut test) .expect_err("consume_all did not error"); // We have to hold interface until now otherwise consume_all won't try to process the message drop(interface); let message = rx.try_recv().expect("failed to get engine call message"); match message { EngineCallResponse::Error(error) => { check_test_io_error(&error); Ok(()) } _ => panic!("received something other than an error: {message:?}"), } } #[test] fn manager_consume_all_propagates_message_error_to_engine_calls() -> Result<(), ShellError> { let mut test = TestCase::new(); let mut manager = test.engine(); let interface = manager.get_interface(); test.add(invalid_input()); // Set up a fake engine call subscription let rx = fake_engine_call(&mut manager, 0); manager .consume_all(&mut test) .expect_err("consume_all did not error"); // We have to hold interface until now otherwise consume_all won't try to process the message drop(interface); let message = rx.try_recv().expect("failed to get engine call message"); match message { EngineCallResponse::Error(error) => { check_invalid_input_error(&error); Ok(()) } _ => panic!("received something other than an error: {message:?}"), } } #[test] fn manager_consume_sets_protocol_info_on_hello() -> Result<(), ShellError> { let mut manager = TestCase::new().engine(); let info = ProtocolInfo::default(); manager.consume(PluginInput::Hello(info.clone()))?; let set_info = manager .state .protocol_info .try_get()? .expect("protocol info not set"); assert_eq!(info.version, set_info.version); Ok(()) } #[test] fn manager_consume_errors_on_wrong_nushell_version() -> Result<(), ShellError> { let mut manager = TestCase::new().engine(); let info = ProtocolInfo { protocol: Protocol::NuPlugin, version: "0.0.0".into(), features: vec![], }; manager .consume(PluginInput::Hello(info)) .expect_err("version 0.0.0 should cause an error"); Ok(()) } #[test] fn manager_consume_errors_on_sending_other_messages_before_hello() -> Result<(), ShellError> { let mut manager = TestCase::new().engine(); // hello not set assert!(!manager.state.protocol_info.is_set()); let error = manager .consume(PluginInput::Drop(0)) .expect_err("consume before Hello should cause an error"); assert!(format!("{error:?}").contains("Hello")); Ok(()) } fn set_default_protocol_info(manager: &mut EngineInterfaceManager) -> Result<(), ShellError> { manager .protocol_info_mut .set(Arc::new(ProtocolInfo::default())) } #[test] fn manager_consume_goodbye_closes_plugin_call_channel() -> Result<(), ShellError> { let mut manager = TestCase::new().engine(); set_default_protocol_info(&mut manager)?; let rx = manager .take_plugin_call_receiver() .expect("plugin call receiver missing"); manager.consume(PluginInput::Goodbye)?; match rx.try_recv() { Err(TryRecvError::Disconnected) => (), _ => panic!("receiver was not disconnected"), } Ok(()) } #[test] fn manager_consume_call_metadata_forwards_to_receiver_with_context() -> Result<(), ShellError> { let mut manager = TestCase::new().engine(); set_default_protocol_info(&mut manager)?; let rx = manager .take_plugin_call_receiver() .expect("couldn't take receiver"); manager.consume(PluginInput::Call(0, PluginCall::Metadata))?; match rx.try_recv().expect("call was not forwarded to receiver") { ReceivedPluginCall::Metadata { engine } => { assert_eq!(Some(0), engine.context); Ok(()) } call => panic!("wrong call type: {call:?}"), } } #[test] fn manager_consume_call_signature_forwards_to_receiver_with_context() -> Result<(), ShellError> { let mut manager = TestCase::new().engine(); set_default_protocol_info(&mut manager)?; let rx = manager .take_plugin_call_receiver() .expect("couldn't take receiver"); manager.consume(PluginInput::Call(0, PluginCall::Signature))?; match rx.try_recv().expect("call was not forwarded to receiver") { ReceivedPluginCall::Signature { engine } => { assert_eq!(Some(0), engine.context); Ok(()) } call => panic!("wrong call type: {call:?}"), } } #[test] fn manager_consume_call_run_forwards_to_receiver_with_context() -> Result<(), ShellError> { let mut manager = TestCase::new().engine(); set_default_protocol_info(&mut manager)?; let rx = manager .take_plugin_call_receiver() .expect("couldn't take receiver"); manager.consume(PluginInput::Call( 17, PluginCall::Run(CallInfo { name: "bar".into(), call: EvaluatedCall { head: Span::test_data(), positional: vec![], named: vec![], }, input: PipelineDataHeader::Empty, }), ))?; // Make sure the streams end and we don't deadlock drop(manager); match rx.try_recv().expect("call was not forwarded to receiver") { ReceivedPluginCall::Run { engine, call: _ } => { assert_eq!(Some(17), engine.context, "context"); Ok(()) } call => panic!("wrong call type: {call:?}"), } } #[test] fn manager_consume_call_run_forwards_to_receiver_with_pipeline_data() -> Result<(), ShellError> { let mut manager = TestCase::new().engine(); set_default_protocol_info(&mut manager)?; let rx = manager .take_plugin_call_receiver() .expect("couldn't take receiver"); manager.consume(PluginInput::Call( 0, PluginCall::Run(CallInfo { name: "bar".into(), call: EvaluatedCall { head: Span::test_data(), positional: vec![], named: vec![], }, input: PipelineDataHeader::list_stream(ListStreamInfo::new(6, Span::test_data())), }), ))?; for i in 0..10 { manager.consume(PluginInput::Data(6, Value::test_int(i).into()))?; } manager.consume(PluginInput::End(6))?; // Make sure the streams end and we don't deadlock drop(manager); match rx.try_recv().expect("call was not forwarded to receiver") { ReceivedPluginCall::Run { engine: _, call } => { assert_eq!("bar", call.name); // Ensure we manage to receive the stream messages assert_eq!(10, call.input.into_iter().count()); Ok(()) } call => panic!("wrong call type: {call:?}"), } } #[test] fn manager_consume_call_run_deserializes_custom_values_in_args() -> Result<(), ShellError> { let mut manager = TestCase::new().engine(); set_default_protocol_info(&mut manager)?; let rx = manager .take_plugin_call_receiver() .expect("couldn't take receiver"); let value = Value::test_custom_value(Box::new(test_plugin_custom_value())); manager.consume(PluginInput::Call( 0, PluginCall::Run(CallInfo { name: "bar".into(), call: EvaluatedCall { head: Span::test_data(), positional: vec![value.clone()], named: vec![( Spanned { item: "flag".into(), span: Span::test_data(), }, Some(value), )], }, input: PipelineDataHeader::Empty, }), ))?; // Make sure the streams end and we don't deadlock drop(manager); match rx.try_recv().expect("call was not forwarded to receiver") { ReceivedPluginCall::Run { engine: _, call } => { assert_eq!(1, call.call.positional.len()); assert_eq!(1, call.call.named.len()); for arg in call.call.positional { let custom_value: &TestCustomValue = arg .as_custom_value()? .as_any() .downcast_ref() .expect("positional arg is not TestCustomValue"); assert_eq!(expected_test_custom_value(), *custom_value, "positional"); } for (key, val) in call.call.named { let key = &key.item; let custom_value: &TestCustomValue = val .as_ref() .unwrap_or_else(|| panic!("found empty named argument: {key}")) .as_custom_value()? .as_any() .downcast_ref() .unwrap_or_else(|| panic!("named arg {key} is not TestCustomValue")); assert_eq!(expected_test_custom_value(), *custom_value, "named: {key}"); } Ok(()) } call => panic!("wrong call type: {call:?}"), } } #[test] fn manager_consume_call_custom_value_op_forwards_to_receiver_with_context() -> Result<(), ShellError> { let mut manager = TestCase::new().engine(); set_default_protocol_info(&mut manager)?; let rx = manager .take_plugin_call_receiver() .expect("couldn't take receiver"); manager.consume(PluginInput::Call( 32, PluginCall::CustomValueOp( Spanned { item: test_plugin_custom_value(), span: Span::test_data(), }, CustomValueOp::ToBaseValue, ), ))?; match rx.try_recv().expect("call was not forwarded to receiver") { ReceivedPluginCall::CustomValueOp { engine, custom_value, op, } => { assert_eq!(Some(32), engine.context); assert_eq!("TestCustomValue", custom_value.item.name()); assert!( matches!(op, CustomValueOp::ToBaseValue), "incorrect op: {op:?}" ); } call => panic!("wrong call type: {call:?}"), } Ok(()) } #[test] fn manager_consume_engine_call_response_forwards_to_subscriber_with_pipeline_data() -> Result<(), ShellError> { let mut manager = TestCase::new().engine(); set_default_protocol_info(&mut manager)?; let rx = fake_engine_call(&mut manager, 0); manager.consume(PluginInput::EngineCallResponse( 0, EngineCallResponse::PipelineData(PipelineDataHeader::list_stream(ListStreamInfo::new( 0, Span::test_data(), ))), ))?; for i in 0..2 { manager.consume(PluginInput::Data(0, Value::test_int(i).into()))?; } manager.consume(PluginInput::End(0))?; // Make sure the streams end and we don't deadlock drop(manager); let response = rx.try_recv().expect("failed to get engine call response"); match response { EngineCallResponse::PipelineData(data) => { // Ensure we manage to receive the stream messages assert_eq!(2, data.into_iter().count()); Ok(()) } _ => panic!("unexpected response: {response:?}"), } } #[test] fn manager_prepare_pipeline_data_deserializes_custom_values() -> Result<(), ShellError> { let manager = TestCase::new().engine(); let data = manager.prepare_pipeline_data(PipelineData::value( Value::test_custom_value(Box::new(test_plugin_custom_value())), None, ))?; let value = data .into_iter() .next() .expect("prepared pipeline data is empty"); let custom_value: &TestCustomValue = value .as_custom_value()? .as_any() .downcast_ref() .expect("custom value is not a TestCustomValue, probably not deserialized"); assert_eq!(expected_test_custom_value(), *custom_value); Ok(()) } #[test] fn manager_prepare_pipeline_data_deserializes_custom_values_in_streams() -> Result<(), ShellError> { let manager = TestCase::new().engine(); let data = manager.prepare_pipeline_data( [Value::test_custom_value(Box::new( test_plugin_custom_value(), ))] .into_pipeline_data(Span::test_data(), Signals::empty()), )?; let value = data .into_iter() .next() .expect("prepared pipeline data is empty"); let custom_value: &TestCustomValue = value .as_custom_value()? .as_any() .downcast_ref() .expect("custom value is not a TestCustomValue, probably not deserialized"); assert_eq!(expected_test_custom_value(), *custom_value); Ok(()) } #[test] fn manager_prepare_pipeline_data_embeds_deserialization_errors_in_streams() -> Result<(), ShellError> { let manager = TestCase::new().engine(); let invalid_custom_value = PluginCustomValue::new( "Invalid".into(), vec![0; 8], // should fail to decode to anything false, ); let span = Span::new(20, 30); let data = manager.prepare_pipeline_data( [Value::custom(Box::new(invalid_custom_value), span)] .into_pipeline_data(Span::test_data(), Signals::empty()), )?; let value = data .into_iter() .next() .expect("prepared pipeline data is empty"); match value { Value::Error { error, .. } => match *error { ShellError::CustomValueFailedToDecode { span: error_span, .. } => { assert_eq!(span, error_span, "error span not the same as the value's"); } _ => panic!("expected ShellError::CustomValueFailedToDecode, but got {error:?}"), }, _ => panic!("unexpected value, not error: {value:?}"), } Ok(()) } #[test] fn interface_hello_sends_protocol_info() -> Result<(), ShellError> { let test = TestCase::new(); let interface = test.engine().get_interface(); interface.hello()?; let written = test.next_written().expect("nothing written"); match written { PluginOutput::Hello(info) => { assert_eq!(ProtocolInfo::default().version, info.version); } _ => panic!("unexpected message written: {written:?}"), } assert!(!test.has_unconsumed_write()); Ok(()) } #[test] fn interface_write_response_with_value() -> Result<(), ShellError> { let test = TestCase::new(); let interface = test.engine().interface_for_context(33); interface .write_response(Ok::<_, ShellError>(PipelineData::value( Value::test_int(6), None, )))? .write()?; let written = test.next_written().expect("nothing written"); match written { PluginOutput::CallResponse(id, response) => { assert_eq!(33, id, "id"); match response { PluginCallResponse::PipelineData(header) => match header { PipelineDataHeader::Value(value, _) => assert_eq!(6, value.as_int()?), _ => panic!("unexpected pipeline data header: {header:?}"), }, _ => panic!("unexpected response: {response:?}"), } } _ => panic!("unexpected message written: {written:?}"), } assert!(!test.has_unconsumed_write()); Ok(()) } #[test] fn interface_write_response_with_stream() -> Result<(), ShellError> { let test = TestCase::new(); let manager = test.engine(); let interface = manager.interface_for_context(34); interface .write_response(Ok::<_, ShellError>( [Value::test_int(3), Value::test_int(4), Value::test_int(5)] .into_pipeline_data(Span::test_data(), Signals::empty()), ))? .write()?; let written = test.next_written().expect("nothing written"); let info = match written { PluginOutput::CallResponse(_, response) => match response { PluginCallResponse::PipelineData(header) => match header { PipelineDataHeader::ListStream(info) => info, _ => panic!("expected ListStream header: {header:?}"), }, _ => panic!("wrong response: {response:?}"), }, _ => panic!("wrong output written: {written:?}"), }; for number in [3, 4, 5] { match test.next_written().expect("missing stream Data message") { PluginOutput::Data(id, data) => { assert_eq!(info.id, id, "Data id"); match data { StreamData::List(val) => assert_eq!(number, val.as_int()?), _ => panic!("expected List data: {data:?}"), } } message => panic!("expected Data(..): {message:?}"), } } match test.next_written().expect("missing stream End message") { PluginOutput::End(id) => assert_eq!(info.id, id, "End id"), message => panic!("expected Data(..): {message:?}"), } assert!(!test.has_unconsumed_write()); Ok(()) } #[test] fn interface_write_response_with_error() -> Result<(), ShellError> { let test = TestCase::new(); let interface = test.engine().interface_for_context(35); let error: ShellError = LabeledError::new("this is an error") .with_help("a test error") .into(); interface.write_response(Err(error.clone()))?.write()?; let written = test.next_written().expect("nothing written"); match written { PluginOutput::CallResponse(id, response) => { assert_eq!(35, id, "id"); match response { PluginCallResponse::Error(err) => assert_eq!(error, err), _ => panic!("unexpected response: {response:?}"), } } _ => panic!("unexpected message written: {written:?}"), } assert!(!test.has_unconsumed_write()); Ok(()) } #[test] fn interface_write_signature() -> Result<(), ShellError> { let test = TestCase::new(); let interface = test.engine().interface_for_context(36); let signatures = vec![PluginSignature::build("test command")]; interface.write_signature(signatures.clone())?; let written = test.next_written().expect("nothing written"); match written { PluginOutput::CallResponse(id, response) => { assert_eq!(36, id, "id"); match response { PluginCallResponse::Signature(sigs) => assert_eq!(1, sigs.len(), "sigs.len"), _ => panic!("unexpected response: {response:?}"), } } _ => panic!("unexpected message written: {written:?}"), } assert!(!test.has_unconsumed_write()); Ok(()) } #[test] fn interface_write_engine_call_registers_subscription() -> Result<(), ShellError> { let mut manager = TestCase::new().engine(); assert!( manager.engine_call_subscriptions.is_empty(), "engine call subscriptions not empty before start of test" ); let interface = manager.interface_for_context(0); let _ = interface.write_engine_call(EngineCall::GetConfig)?; manager.receive_engine_call_subscriptions(); assert!( !manager.engine_call_subscriptions.is_empty(), "not registered" ); Ok(()) } #[test] fn interface_write_engine_call_writes_with_correct_context() -> Result<(), ShellError> { let test = TestCase::new(); let manager = test.engine(); let interface = manager.interface_for_context(32); let _ = interface.write_engine_call(EngineCall::GetConfig)?; match test.next_written().expect("nothing written") { PluginOutput::EngineCall { context, call, .. } => { assert_eq!(32, context, "context incorrect"); assert!( matches!(call, EngineCall::GetConfig), "incorrect engine call (expected GetConfig): {call:?}" ); } other => panic!("incorrect output: {other:?}"), } assert!(!test.has_unconsumed_write()); Ok(()) } /// Fake responses to requests for engine call messages fn start_fake_plugin_call_responder( manager: EngineInterfaceManager, take: usize, mut f: impl FnMut(EngineCallId) -> EngineCallResponse<PipelineData> + Send + 'static, ) { std::thread::Builder::new() .name("fake engine call responder".into()) .spawn(move || { for (id, sub) in manager .engine_call_subscription_receiver .into_iter() .take(take) { sub.send(f(id)).expect("failed to send"); } }) .expect("failed to spawn thread"); } #[test] fn interface_get_config() -> Result<(), ShellError> { let test = TestCase::new(); let manager = test.engine(); let interface = manager.interface_for_context(0); start_fake_plugin_call_responder(manager, 1, |_| { EngineCallResponse::Config(Config::default().into()) }); let _ = interface.get_config()?; assert!(test.has_unconsumed_write()); Ok(()) } #[test] fn interface_get_plugin_config() -> Result<(), ShellError> { let test = TestCase::new(); let manager = test.engine(); let interface = manager.interface_for_context(0); start_fake_plugin_call_responder(manager, 2, |id| { if id == 0 { EngineCallResponse::PipelineData(PipelineData::empty()) } else { EngineCallResponse::PipelineData(PipelineData::value(Value::test_int(2), None)) } }); let first_config = interface.get_plugin_config()?; assert!(first_config.is_none(), "should be None: {first_config:?}"); let second_config = interface.get_plugin_config()?; assert_eq!(Some(Value::test_int(2)), second_config); assert!(test.has_unconsumed_write()); Ok(()) } #[test] fn interface_get_env_var() -> Result<(), ShellError> { let test = TestCase::new(); let manager = test.engine(); let interface = manager.interface_for_context(0); start_fake_plugin_call_responder(manager, 2, |id| { if id == 0 { EngineCallResponse::empty() } else { EngineCallResponse::value(Value::test_string("/foo")) } }); let first_val = interface.get_env_var("FOO")?; assert!(first_val.is_none(), "should be None: {first_val:?}"); let second_val = interface.get_env_var("FOO")?; assert_eq!(Some(Value::test_string("/foo")), second_val); assert!(test.has_unconsumed_write()); Ok(()) } #[test] fn interface_get_current_dir() -> Result<(), ShellError> { let test = TestCase::new(); let manager = test.engine(); let interface = manager.interface_for_context(0); start_fake_plugin_call_responder(manager, 1, |_| { EngineCallResponse::value(Value::test_string("/current/directory")) }); let val = interface.get_env_var("FOO")?; assert_eq!(Some(Value::test_string("/current/directory")), val); assert!(test.has_unconsumed_write()); Ok(()) } #[test] fn interface_get_env_vars() -> Result<(), ShellError> { let test = TestCase::new(); let manager = test.engine(); let interface = manager.interface_for_context(0); let envs: HashMap<String, Value> = [("FOO".to_owned(), Value::test_string("foo"))] .into_iter() .collect(); let envs_clone = envs.clone(); start_fake_plugin_call_responder(manager, 1, move |_| { EngineCallResponse::ValueMap(envs_clone.clone()) }); let received_envs = interface.get_env_vars()?; assert_eq!(envs, received_envs); assert!(test.has_unconsumed_write()); Ok(()) } #[test] fn interface_add_env_var() -> Result<(), ShellError> { let test = TestCase::new(); let manager = test.engine(); let interface = manager.interface_for_context(0); start_fake_plugin_call_responder(manager, 1, move |_| EngineCallResponse::empty()); interface.add_env_var("FOO", Value::test_string("bar"))?; assert!(test.has_unconsumed_write()); Ok(()) } #[test] fn interface_get_help() -> Result<(), ShellError> { let test = TestCase::new(); let manager = test.engine(); let interface = manager.interface_for_context(0); start_fake_plugin_call_responder(manager, 1, move |_| { EngineCallResponse::value(Value::test_string("help string")) }); let help = interface.get_help()?; assert_eq!("help string", help); assert!(test.has_unconsumed_write()); Ok(()) } #[test] fn interface_get_span_contents() -> Result<(), ShellError> { let test = TestCase::new(); let manager = test.engine(); let interface = manager.interface_for_context(0); start_fake_plugin_call_responder(manager, 1, move |_| { EngineCallResponse::value(Value::test_binary(b"test string")) }); let contents = interface.get_span_contents(Span::test_data())?; assert_eq!(b"test string", &contents[..]); assert!(test.has_unconsumed_write()); Ok(()) } #[test] fn interface_eval_closure_with_stream() -> Result<(), ShellError> { let test = TestCase::new(); let manager = test.engine(); let interface = manager.interface_for_context(0); start_fake_plugin_call_responder(manager, 1, |_| { EngineCallResponse::PipelineData(PipelineData::value(Value::test_int(2), None)) }); let result = interface .eval_closure_with_stream( &Spanned { item: Closure { block_id: BlockId::new(42), captures: vec![(VarId::new(0), Value::test_int(5))], }, span: Span::test_data(), }, vec![Value::test_string("test")], PipelineData::empty(), true, false, )? .into_value(Span::test_data())?; assert_eq!(Value::test_int(2), result); // Double check the message that was written, as it's complicated match test.next_written().expect("nothing written") { PluginOutput::EngineCall { call, .. } => match call { EngineCall::EvalClosure { closure, positional, input, redirect_stdout, redirect_stderr, } => { assert_eq!( BlockId::new(42), closure.item.block_id, "closure.item.block_id" ); assert_eq!(1, closure.item.captures.len(), "closure.item.captures.len"); assert_eq!( (VarId::new(0), Value::test_int(5)), closure.item.captures[0], "closure.item.captures[0]" ); assert_eq!(Span::test_data(), closure.span, "closure.span"); assert_eq!(1, positional.len(), "positional.len");
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
true
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin/src/plugin/interface/mod.rs
crates/nu-plugin/src/plugin/interface/mod.rs
//! Interface used by the plugin to communicate with the engine. use nu_plugin_core::{ Interface, InterfaceManager, PipelineDataWriter, PluginRead, PluginWrite, StreamManager, StreamManagerHandle, util::{Waitable, WaitableMut}, }; use nu_plugin_protocol::{ CallInfo, CustomValueOp, EngineCall, EngineCallId, EngineCallResponse, EvaluatedCall, GetCompletionInfo, Ordering, PluginCall, PluginCallId, PluginCallResponse, PluginCustomValue, PluginInput, PluginOption, PluginOutput, ProtocolInfo, }; use nu_protocol::{ BlockId, Config, DeclId, DynamicSuggestion, Handler, HandlerGuard, Handlers, PipelineData, PluginMetadata, PluginSignature, ShellError, SignalAction, Signals, Span, Spanned, Value, engine::{Closure, Sequence}, ir::IrBlock, }; use nu_utils::SharedCow; use std::{ collections::{BTreeMap, HashMap, btree_map}, sync::{Arc, atomic::AtomicBool, mpsc}, }; /// Plugin calls that are received by the [`EngineInterfaceManager`] for handling. /// /// With each call, an [`EngineInterface`] is included that can be provided to the plugin code /// and should be used to send the response. The interface sent includes the [`PluginCallId`] for /// sending associated messages with the correct context. /// /// This is not a public API. #[derive(Debug)] #[doc(hidden)] pub enum ReceivedPluginCall { Metadata { engine: EngineInterface, }, Signature { engine: EngineInterface, }, Run { engine: EngineInterface, call: CallInfo<PipelineData>, }, GetCompletion { engine: EngineInterface, info: GetCompletionInfo, }, CustomValueOp { engine: EngineInterface, custom_value: Spanned<PluginCustomValue>, op: CustomValueOp, }, } #[cfg(test)] mod tests; /// Internal shared state between the manager and each interface. struct EngineInterfaceState { /// Protocol version info, set after `Hello` received protocol_info: Waitable<Arc<ProtocolInfo>>, /// Sequence for generating engine call ids engine_call_id_sequence: Sequence, /// Sequence for generating stream ids stream_id_sequence: Sequence, /// Sender to subscribe to an engine call response engine_call_subscription_sender: mpsc::Sender<(EngineCallId, mpsc::Sender<EngineCallResponse<PipelineData>>)>, /// The synchronized output writer writer: Box<dyn PluginWrite<PluginOutput>>, /// Mirror signals from `EngineState`. You can make use of this with /// `engine_interface.signals()` when constructing a Stream that requires signals signals: Signals, /// Registered signal handlers signal_handlers: Handlers, } impl std::fmt::Debug for EngineInterfaceState { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("EngineInterfaceState") .field("protocol_info", &self.protocol_info) .field("engine_call_id_sequence", &self.engine_call_id_sequence) .field("stream_id_sequence", &self.stream_id_sequence) .field( "engine_call_subscription_sender", &self.engine_call_subscription_sender, ) .finish_non_exhaustive() } } /// Manages reading and dispatching messages for [`EngineInterface`]s. /// /// This is not a public API. #[derive(Debug)] #[doc(hidden)] pub struct EngineInterfaceManager { /// Shared state state: Arc<EngineInterfaceState>, /// The writer for protocol info protocol_info_mut: WaitableMut<Arc<ProtocolInfo>>, /// Channel to send received PluginCalls to. This is removed after `Goodbye` is received. plugin_call_sender: Option<mpsc::Sender<ReceivedPluginCall>>, /// Receiver for PluginCalls. This is usually taken after initialization plugin_call_receiver: Option<mpsc::Receiver<ReceivedPluginCall>>, /// Subscriptions for engine call responses engine_call_subscriptions: BTreeMap<EngineCallId, mpsc::Sender<EngineCallResponse<PipelineData>>>, /// Receiver for engine call subscriptions engine_call_subscription_receiver: mpsc::Receiver<(EngineCallId, mpsc::Sender<EngineCallResponse<PipelineData>>)>, /// Manages stream messages and state stream_manager: StreamManager, } impl EngineInterfaceManager { pub(crate) fn new(writer: impl PluginWrite<PluginOutput> + 'static) -> EngineInterfaceManager { let (plug_tx, plug_rx) = mpsc::channel(); let (subscription_tx, subscription_rx) = mpsc::channel(); let protocol_info_mut = WaitableMut::new(); EngineInterfaceManager { state: Arc::new(EngineInterfaceState { protocol_info: protocol_info_mut.reader(), engine_call_id_sequence: Sequence::default(), stream_id_sequence: Sequence::default(), engine_call_subscription_sender: subscription_tx, writer: Box::new(writer), signals: Signals::new(Arc::new(AtomicBool::new(false))), signal_handlers: Handlers::new(), }), protocol_info_mut, plugin_call_sender: Some(plug_tx), plugin_call_receiver: Some(plug_rx), engine_call_subscriptions: BTreeMap::new(), engine_call_subscription_receiver: subscription_rx, stream_manager: StreamManager::new(), } } /// Get the receiving end of the plugin call channel. Plugin calls that need to be handled /// will be sent here. pub(crate) fn take_plugin_call_receiver( &mut self, ) -> Option<mpsc::Receiver<ReceivedPluginCall>> { self.plugin_call_receiver.take() } /// Create an [`EngineInterface`] associated with the given call id. fn interface_for_context(&self, context: PluginCallId) -> EngineInterface { EngineInterface { state: self.state.clone(), stream_manager_handle: self.stream_manager.get_handle(), context: Some(context), } } /// Send a [`ReceivedPluginCall`] to the channel fn send_plugin_call(&self, plugin_call: ReceivedPluginCall) -> Result<(), ShellError> { self.plugin_call_sender .as_ref() .ok_or_else(|| ShellError::PluginFailedToDecode { msg: "Received a plugin call after Goodbye".into(), })? .send(plugin_call) .map_err(|_| ShellError::NushellFailed { msg: "Received a plugin call, but there's nowhere to send it".into(), }) } /// Flush any remaining subscriptions in the receiver into the map fn receive_engine_call_subscriptions(&mut self) { for (id, subscription) in self.engine_call_subscription_receiver.try_iter() { if let btree_map::Entry::Vacant(e) = self.engine_call_subscriptions.entry(id) { e.insert(subscription); } else { log::warn!("Duplicate engine call ID ignored: {id}") } } } /// Send a [`EngineCallResponse`] to the appropriate sender fn send_engine_call_response( &mut self, id: EngineCallId, response: EngineCallResponse<PipelineData>, ) -> Result<(), ShellError> { // Ensure all of the subscriptions have been flushed out of the receiver self.receive_engine_call_subscriptions(); // Remove the sender - there is only one response per engine call if let Some(sender) = self.engine_call_subscriptions.remove(&id) { if sender.send(response).is_err() { log::warn!("Received an engine call response for id={id}, but the caller hung up"); } Ok(()) } else { Err(ShellError::PluginFailedToDecode { msg: format!("Unknown engine call ID: {id}"), }) } } /// True if there are no other copies of the state (which would mean there are no interfaces /// and no stream readers/writers) pub(crate) fn is_finished(&self) -> bool { Arc::strong_count(&self.state) < 2 } /// Loop on input from the given reader as long as `is_finished()` is false /// /// Any errors will be propagated to all read streams automatically. pub(crate) fn consume_all( &mut self, mut reader: impl PluginRead<PluginInput>, ) -> Result<(), ShellError> { while let Some(msg) = reader.read().transpose() { if self.is_finished() { break; } if let Err(err) = msg.and_then(|msg| self.consume(msg)) { // Error to streams let _ = self.stream_manager.broadcast_read_error(err.clone()); // Error to engine call waiters self.receive_engine_call_subscriptions(); for sender in std::mem::take(&mut self.engine_call_subscriptions).into_values() { let _ = sender.send(EngineCallResponse::Error(err.clone())); } return Err(err); } } Ok(()) } } impl InterfaceManager for EngineInterfaceManager { type Interface = EngineInterface; type Input = PluginInput; fn get_interface(&self) -> Self::Interface { EngineInterface { state: self.state.clone(), stream_manager_handle: self.stream_manager.get_handle(), context: None, } } fn consume(&mut self, input: Self::Input) -> Result<(), ShellError> { log::trace!("from engine: {input:?}"); match input { PluginInput::Hello(info) => { let info = Arc::new(info); self.protocol_info_mut.set(info.clone())?; let local_info = ProtocolInfo::default(); if local_info.is_compatible_with(&info)? { Ok(()) } else { Err(ShellError::PluginFailedToLoad { msg: format!( "Plugin is compiled for nushell version {}, \ which is not compatible with version {}", local_info.version, info.version ), }) } } _ if !self.state.protocol_info.is_set() => { // Must send protocol info first Err(ShellError::PluginFailedToLoad { msg: "Failed to receive initial Hello message. This engine might be too old" .into(), }) } // Stream messages PluginInput::Data(..) | PluginInput::End(..) | PluginInput::Drop(..) | PluginInput::Ack(..) => { self.consume_stream_message(input.try_into().map_err(|msg| { ShellError::NushellFailed { msg: format!("Failed to convert message {msg:?} to StreamMessage"), } })?) } PluginInput::Call(id, call) => { let interface = self.interface_for_context(id); // Read streams in the input let call = match call .map_data(|input| self.read_pipeline_data(input, &Signals::empty())) { Ok(call) => call, Err(err) => { // If there's an error with initialization of the input stream, just send // the error response rather than failing here return interface.write_response(Err(err))?.write(); } }; match call { // Ask the plugin for metadata PluginCall::Metadata => { self.send_plugin_call(ReceivedPluginCall::Metadata { engine: interface }) } // Ask the plugin for signatures PluginCall::Signature => { self.send_plugin_call(ReceivedPluginCall::Signature { engine: interface }) } // Parse custom values and send a ReceivedPluginCall PluginCall::Run(mut call_info) => { // Deserialize custom values in the arguments if let Err(err) = deserialize_call_args(&mut call_info.call) { return interface.write_response(Err(err))?.write(); } // Send the plugin call to the receiver self.send_plugin_call(ReceivedPluginCall::Run { engine: interface, call: call_info, }) } // Send request with the custom value PluginCall::CustomValueOp(custom_value, op) => { self.send_plugin_call(ReceivedPluginCall::CustomValueOp { engine: interface, custom_value, op, }) } PluginCall::GetCompletion(info) => { self.send_plugin_call(ReceivedPluginCall::GetCompletion { engine: interface, info, }) } } } PluginInput::Goodbye => { // Remove the plugin call sender so it hangs up drop(self.plugin_call_sender.take()); Ok(()) } PluginInput::EngineCallResponse(id, response) => { let response = response .map_data(|header| self.read_pipeline_data(header, &Signals::empty())) .unwrap_or_else(|err| { // If there's an error with initializing this stream, change it to an engine // call error response, but send it anyway EngineCallResponse::Error(err) }); self.send_engine_call_response(id, response) } PluginInput::Signal(action) => { match action { SignalAction::Interrupt => self.state.signals.trigger(), SignalAction::Reset => self.state.signals.reset(), } self.state.signal_handlers.run(action); Ok(()) } } } fn stream_manager(&self) -> &StreamManager { &self.stream_manager } fn prepare_pipeline_data(&self, mut data: PipelineData) -> Result<PipelineData, ShellError> { // Deserialize custom values in the pipeline data match data { PipelineData::Value(ref mut value, _) => { PluginCustomValue::deserialize_custom_values_in(value)?; Ok(data) } PipelineData::ListStream(stream, meta) => { let stream = stream.map(|mut value| { let span = value.span(); PluginCustomValue::deserialize_custom_values_in(&mut value) .map(|()| value) .unwrap_or_else(|err| Value::error(err, span)) }); Ok(PipelineData::list_stream(stream, meta)) } PipelineData::Empty | PipelineData::ByteStream(..) => Ok(data), } } } /// Deserialize custom values in call arguments fn deserialize_call_args(call: &mut crate::EvaluatedCall) -> Result<(), ShellError> { call.positional .iter_mut() .try_for_each(PluginCustomValue::deserialize_custom_values_in)?; call.named .iter_mut() .flat_map(|(_, value)| value.as_mut()) .try_for_each(PluginCustomValue::deserialize_custom_values_in) } /// A reference through which the nushell engine can be interacted with during execution. #[derive(Debug, Clone)] pub struct EngineInterface { /// Shared state with the manager state: Arc<EngineInterfaceState>, /// Handle to stream manager stream_manager_handle: StreamManagerHandle, /// The plugin call this interface belongs to. context: Option<PluginCallId>, } impl EngineInterface { /// Write the protocol info. This should be done after initialization pub(crate) fn hello(&self) -> Result<(), ShellError> { self.write(PluginOutput::Hello(ProtocolInfo::default()))?; self.flush() } fn context(&self) -> Result<PluginCallId, ShellError> { self.context.ok_or_else(|| ShellError::NushellFailed { msg: "Tried to call an EngineInterface method that requires a call context \ outside of one" .into(), }) } /// Write an OK call response or an error. pub(crate) fn write_ok( &self, result: Result<(), impl Into<ShellError>>, ) -> Result<(), ShellError> { let response = match result { Ok(()) => PluginCallResponse::Ok, Err(err) => PluginCallResponse::Error(err.into()), }; self.write(PluginOutput::CallResponse(self.context()?, response))?; self.flush() } /// Write a call response of either [`PipelineData`] or an error. Returns the stream writer /// to finish writing the stream pub(crate) fn write_response( &self, result: Result<PipelineData, impl Into<ShellError>>, ) -> Result<PipelineDataWriter<Self>, ShellError> { match result { Ok(data) => { let (header, writer) = match self.init_write_pipeline_data(data, &()) { Ok(tup) => tup, // If we get an error while trying to construct the pipeline data, send that // instead Err(err) => return self.write_response(Err(err)), }; // Write pipeline data header response, and the full stream let response = PluginCallResponse::PipelineData(header); self.write(PluginOutput::CallResponse(self.context()?, response))?; self.flush()?; Ok(writer) } Err(err) => { let response = PluginCallResponse::Error(err.into()); self.write(PluginOutput::CallResponse(self.context()?, response))?; self.flush()?; Ok(Default::default()) } } } /// Write a call response of plugin metadata. pub(crate) fn write_metadata(&self, metadata: PluginMetadata) -> Result<(), ShellError> { let response = PluginCallResponse::Metadata(metadata); self.write(PluginOutput::CallResponse(self.context()?, response))?; self.flush() } /// Write a call response of plugin signatures. /// /// Any custom values in the examples will be rendered using `to_base_value()`. pub(crate) fn write_signature( &self, signature: Vec<PluginSignature>, ) -> Result<(), ShellError> { let response = PluginCallResponse::Signature(signature); self.write(PluginOutput::CallResponse(self.context()?, response))?; self.flush() } /// Write a call response of completion items. pub(crate) fn write_completion_items( &self, items: Option<Vec<DynamicSuggestion>>, ) -> Result<(), ShellError> { let response = PluginCallResponse::CompletionItems(items); self.write(PluginOutput::CallResponse(self.context()?, response))?; self.flush() } /// Write an engine call message. Returns the writer for the stream, and the receiver for /// the response to the engine call. fn write_engine_call( &self, call: EngineCall<PipelineData>, ) -> Result< ( PipelineDataWriter<Self>, mpsc::Receiver<EngineCallResponse<PipelineData>>, ), ShellError, > { let context = self.context()?; let id = self.state.engine_call_id_sequence.next()?; let (tx, rx) = mpsc::channel(); // Convert the call into one with a header and handle the stream, if necessary let mut writer = None; let call = call.map_data(|input| { let (input_header, input_writer) = self.init_write_pipeline_data(input, &())?; writer = Some(input_writer); Ok(input_header) })?; // Register the channel self.state .engine_call_subscription_sender .send((id, tx)) .map_err(|_| ShellError::NushellFailed { msg: "EngineInterfaceManager hung up and is no longer accepting engine calls" .into(), })?; // Write request self.write(PluginOutput::EngineCall { context, id, call })?; self.flush()?; Ok((writer.unwrap_or_default(), rx)) } /// Perform an engine call. Input and output streams are handled. fn engine_call( &self, call: EngineCall<PipelineData>, ) -> Result<EngineCallResponse<PipelineData>, ShellError> { let (writer, rx) = self.write_engine_call(call)?; // Finish writing stream in the background writer.write_background()?; // Wait on receiver to get the response rx.recv().map_err(|_| ShellError::NushellFailed { msg: "Failed to get response to engine call because the channel was closed".into(), }) } /// Returns `true` if the plugin is communicating on stdio. When this is the case, stdin and /// stdout should not be used by the plugin for other purposes. /// /// If the plugin can not be used without access to stdio, an error should be presented to the /// user instead. pub fn is_using_stdio(&self) -> bool { self.state.writer.is_stdout() } /// Register a closure which will be called when the engine receives an interrupt signal. /// Returns a RAII guard that will keep the closure alive until it is dropped. pub fn register_signal_handler(&self, handler: Handler) -> Result<HandlerGuard, ShellError> { self.state.signal_handlers.register(handler) } /// Get the full shell configuration from the engine. As this is quite a large object, it is /// provided on request only. /// /// # Example /// /// Format a value in the user's preferred way: /// /// ```rust,no_run /// # use nu_protocol::{Value, ShellError}; /// # use nu_plugin::EngineInterface; /// # fn example(engine: &EngineInterface, value: &Value) -> Result<(), ShellError> { /// let config = engine.get_config()?; /// eprintln!("{}", value.to_expanded_string(", ", &config)); /// # Ok(()) /// # } /// ``` pub fn get_config(&self) -> Result<Arc<Config>, ShellError> { match self.engine_call(EngineCall::GetConfig)? { EngineCallResponse::Config(config) => Ok(SharedCow::into_arc(config)), EngineCallResponse::Error(err) => Err(err), _ => Err(ShellError::PluginFailedToDecode { msg: "Received unexpected response for EngineCall::GetConfig".into(), }), } } /// Do an engine call returning an `Option<Value>` as either `PipelineData::empty()` or /// `PipelineData::value` fn engine_call_option_value( &self, engine_call: EngineCall<PipelineData>, ) -> Result<Option<Value>, ShellError> { let name = engine_call.name(); match self.engine_call(engine_call)? { EngineCallResponse::PipelineData(PipelineData::Empty) => Ok(None), EngineCallResponse::PipelineData(PipelineData::Value(value, _)) => Ok(Some(value)), EngineCallResponse::Error(err) => Err(err), _ => Err(ShellError::PluginFailedToDecode { msg: format!("Received unexpected response for EngineCall::{name}"), }), } } /// Get the plugin-specific configuration from the engine. This lives in /// `$env.config.plugins.NAME` for a plugin named `NAME`. If the config is set to a closure, /// it is automatically evaluated each time. /// /// # Example /// /// Print this plugin's config: /// /// ```rust,no_run /// # use nu_protocol::{Value, ShellError}; /// # use nu_plugin::EngineInterface; /// # fn example(engine: &EngineInterface, value: &Value) -> Result<(), ShellError> { /// let config = engine.get_plugin_config()?; /// eprintln!("{:?}", config); /// # Ok(()) /// # } /// ``` pub fn get_plugin_config(&self) -> Result<Option<Value>, ShellError> { self.engine_call_option_value(EngineCall::GetPluginConfig) } /// Get an environment variable from the engine. /// /// Returns `Some(value)` if present, and `None` if not found. /// /// # Example /// /// Get `$env.PATH`: /// /// ```rust,no_run /// # use nu_protocol::{Value, ShellError}; /// # use nu_plugin::EngineInterface; /// # fn example(engine: &EngineInterface) -> Result<Option<Value>, ShellError> { /// engine.get_env_var("PATH") // => Ok(Some(Value::List([...]))) /// # } /// ``` pub fn get_env_var(&self, name: impl Into<String>) -> Result<Option<Value>, ShellError> { self.engine_call_option_value(EngineCall::GetEnvVar(name.into())) } /// Get the current working directory from the engine. The result is always an absolute path. /// /// # Example /// ```rust,no_run /// # use nu_protocol::{Value, ShellError}; /// # use nu_plugin::EngineInterface; /// # fn example(engine: &EngineInterface) -> Result<String, ShellError> { /// engine.get_current_dir() // => "/home/user" /// # } /// ``` pub fn get_current_dir(&self) -> Result<String, ShellError> { match self.engine_call(EngineCall::GetCurrentDir)? { // Always a string, and the span doesn't matter. EngineCallResponse::PipelineData(PipelineData::Value(Value::String { val, .. }, _)) => { Ok(val) } EngineCallResponse::Error(err) => Err(err), _ => Err(ShellError::PluginFailedToDecode { msg: "Received unexpected response for EngineCall::GetCurrentDir".into(), }), } } /// Get all environment variables from the engine. /// /// Since this is quite a large map that has to be sent, prefer to use /// [`.get_env_var()`] (Self::get_env_var) if the variables needed are known ahead of time /// and there are only a small number needed. /// /// # Example /// ```rust,no_run /// # use nu_protocol::{Value, ShellError}; /// # use nu_plugin::EngineInterface; /// # use std::collections::HashMap; /// # fn example(engine: &EngineInterface) -> Result<HashMap<String, Value>, ShellError> { /// engine.get_env_vars() // => Ok({"PATH": Value::List([...]), ...}) /// # } /// ``` pub fn get_env_vars(&self) -> Result<HashMap<String, Value>, ShellError> { match self.engine_call(EngineCall::GetEnvVars)? { EngineCallResponse::ValueMap(map) => Ok(map), EngineCallResponse::Error(err) => Err(err), _ => Err(ShellError::PluginFailedToDecode { msg: "Received unexpected response type for EngineCall::GetEnvVars".into(), }), } } /// Set an environment variable in the caller's scope. /// /// If called after the plugin response has already been sent (i.e. during a stream), this will /// only affect the environment for engine calls related to this plugin call, and will not be /// propagated to the environment of the caller. /// /// # Example /// ```rust,no_run /// # use nu_protocol::{Value, ShellError}; /// # use nu_plugin::EngineInterface; /// # fn example(engine: &EngineInterface) -> Result<(), ShellError> { /// engine.add_env_var("FOO", Value::test_string("bar")) /// # } /// ``` pub fn add_env_var(&self, name: impl Into<String>, value: Value) -> Result<(), ShellError> { match self.engine_call(EngineCall::AddEnvVar(name.into(), value))? { EngineCallResponse::PipelineData(_) => Ok(()), EngineCallResponse::Error(err) => Err(err), _ => Err(ShellError::PluginFailedToDecode { msg: "Received unexpected response type for EngineCall::AddEnvVar".into(), }), } } /// Get the help string for the current command. /// /// This returns the same string as passing `--help` would, and can be used for the top-level /// command in a command group that doesn't do anything on its own (e.g. `query`). /// /// # Example /// ```rust,no_run /// # use nu_protocol::{Value, ShellError}; /// # use nu_plugin::EngineInterface; /// # fn example(engine: &EngineInterface) -> Result<(), ShellError> { /// eprintln!("{}", engine.get_help()?); /// # Ok(()) /// # } /// ``` pub fn get_help(&self) -> Result<String, ShellError> { match self.engine_call(EngineCall::GetHelp)? { EngineCallResponse::PipelineData(PipelineData::Value(Value::String { val, .. }, _)) => { Ok(val) } _ => Err(ShellError::PluginFailedToDecode { msg: "Received unexpected response type for EngineCall::GetHelp".into(), }), } } /// Returns a guard that will keep the plugin in the foreground as long as the guard is alive. /// /// Moving the plugin to the foreground is necessary for plugins that need to receive input and /// signals directly from the terminal. /// /// The exact implementation is operating system-specific. On Unix, this ensures that the /// plugin process becomes part of the process group controlling the terminal. pub fn enter_foreground(&self) -> Result<ForegroundGuard, ShellError> { match self.engine_call(EngineCall::EnterForeground)? { EngineCallResponse::Error(error) => Err(error), EngineCallResponse::PipelineData(PipelineData::Value( Value::Int { val: pgrp, .. }, _, )) => { set_pgrp_from_enter_foreground(pgrp)?; Ok(ForegroundGuard(Some(self.clone()))) } EngineCallResponse::PipelineData(PipelineData::Empty) => { Ok(ForegroundGuard(Some(self.clone()))) } _ => Err(ShellError::PluginFailedToDecode { msg: "Received unexpected response type for EngineCall::SetForeground".into(), }), } } /// Internal: for exiting the foreground after `enter_foreground()`. Called from the guard. fn leave_foreground(&self) -> Result<(), ShellError> { match self.engine_call(EngineCall::LeaveForeground)? { EngineCallResponse::Error(error) => Err(error), EngineCallResponse::PipelineData(PipelineData::Empty) => Ok(()), _ => Err(ShellError::PluginFailedToDecode { msg: "Received unexpected response type for EngineCall::LeaveForeground".into(), }), } } /// Get the contents of a [`Span`] from the engine. /// /// This method returns `Vec<u8>` as it's possible for the matched span to not be a valid UTF-8 /// string, perhaps because it sliced through the middle of a UTF-8 byte sequence, as the /// offsets are byte-indexed. Use [`String::from_utf8_lossy()`] for display if necessary. pub fn get_span_contents(&self, span: Span) -> Result<Vec<u8>, ShellError> { match self.engine_call(EngineCall::GetSpanContents(span))? { EngineCallResponse::PipelineData(PipelineData::Value(Value::Binary { val, .. }, _)) => { Ok(val) } _ => Err(ShellError::PluginFailedToDecode { msg: "Received unexpected response type for EngineCall::GetSpanContents".into(), }), } } /// Ask the engine to evaluate a closure. Input to the closure is passed as a stream, and the /// output is available as a stream. /// /// Set `redirect_stdout` to `true` to capture the standard output stream of an external /// command, if the closure results in an external command. /// /// Set `redirect_stderr` to `true` to capture the standard error stream of an external command,
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
true
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-engine/src/declaration.rs
crates/nu-plugin-engine/src/declaration.rs
use nu_engine::{command_prelude::*, get_eval_expression}; use nu_plugin_protocol::{ CallInfo, DynamicCompletionCall, EvaluatedCall, GetCompletionArgType, GetCompletionInfo, }; use nu_protocol::engine::ArgType; use nu_protocol::{DynamicCompletionCallRef, DynamicSuggestion}; use nu_protocol::{PluginIdentity, PluginSignature, engine::CommandType}; use std::sync::Arc; use crate::{GetPlugin, PluginExecutionCommandContext, PluginSource}; /// The command declaration proxy used within the engine for all plugin commands. #[derive(Clone)] pub struct PluginDeclaration { name: String, signature: PluginSignature, source: PluginSource, } impl PluginDeclaration { pub fn new(plugin: Arc<dyn GetPlugin>, signature: PluginSignature) -> Self { Self { name: signature.sig.name.clone(), signature, source: PluginSource::new(plugin), } } } impl Command for PluginDeclaration { fn name(&self) -> &str { &self.name } fn signature(&self) -> Signature { self.signature.sig.clone() } fn description(&self) -> &str { self.signature.sig.description.as_str() } fn extra_description(&self) -> &str { self.signature.sig.extra_description.as_str() } fn search_terms(&self) -> Vec<&str> { self.signature .sig .search_terms .iter() .map(|term| term.as_str()) .collect() } fn examples(&self) -> Vec<Example<'_>> { let mut res = vec![]; for e in self.signature.examples.iter() { res.push(Example { example: &e.example, description: &e.description, result: e.result.clone(), }) } res } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let eval_expression = get_eval_expression(engine_state); // Create the EvaluatedCall to send to the plugin first - it's best for this to fail early, // before we actually try to run the plugin command let evaluated_call = EvaluatedCall::try_from_call(call, engine_state, stack, eval_expression)?; // Get the engine config let engine_config = stack.get_config(engine_state); // Get, or start, the plugin. let plugin = self .source .persistent(None) .and_then(|p| { // Set the garbage collector config from the local config before running p.set_gc_config(engine_config.plugin_gc.get(p.identity().name())); p.get_plugin(Some((engine_state, stack))) }) .map_err(|err| { let decl = engine_state.get_decl(call.decl_id); ShellError::GenericError { error: format!("Unable to spawn plugin for `{}`", decl.name()), msg: err.to_string(), span: Some(call.head), help: None, inner: vec![], } })?; // Create the context to execute in - this supports engine calls and custom values let mut context = PluginExecutionCommandContext::new( self.source.identity.clone(), engine_state, stack, call, ); plugin.run( CallInfo { name: self.name.clone(), call: evaluated_call, input, }, &mut context, ) } fn command_type(&self) -> CommandType { CommandType::Plugin } fn plugin_identity(&self) -> Option<&PluginIdentity> { Some(&self.source.identity) } #[expect(deprecated, reason = "internal usage")] fn get_dynamic_completion( &self, engine_state: &EngineState, stack: &mut Stack, call: DynamicCompletionCallRef, arg_type: &ArgType, _experimental: nu_protocol::engine::ExperimentalMarker, ) -> Result<Option<Vec<DynamicSuggestion>>, ShellError> { // Get the engine config let engine_config = stack.get_config(engine_state); // Get, or start, the plugin. let plugin = self .source .persistent(None) .and_then(|p| { // Set the garbage collector config from the local config before running p.set_gc_config(engine_config.plugin_gc.get(p.identity().name())); p.get_plugin(Some((engine_state, stack))) }) .map_err(|err| ShellError::GenericError { error: "failed to get custom completion".to_string(), msg: err.to_string(), span: None, help: None, inner: vec![], })?; let arg_info = match arg_type { ArgType::Flag(flag_name) => GetCompletionArgType::Flag(flag_name.to_string()), ArgType::Positional(index) => GetCompletionArgType::Positional(*index), }; plugin.get_dynamic_completion(GetCompletionInfo { name: self.name.clone(), arg_type: arg_info, call: DynamicCompletionCall { call: call.call.clone(), strip: call.strip, pos: call.pos, }, }) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-engine/src/source.rs
crates/nu-plugin-engine/src/source.rs
use super::GetPlugin; use nu_protocol::{PluginIdentity, ShellError, Span}; use std::sync::{Arc, Weak}; /// The source of a custom value or plugin command. Includes a weak reference to the persistent /// plugin so it can be retrieved. #[derive(Debug, Clone)] pub struct PluginSource { /// The identity of the plugin pub(crate) identity: Arc<PluginIdentity>, /// A weak reference to the persistent plugin that might hold an interface to the plugin. /// /// This is weak to avoid cyclic references, but it does mean we might fail to upgrade if /// the engine state lost the [`PersistentPlugin`][crate::PersistentPlugin] at some point. pub(crate) persistent: Weak<dyn GetPlugin>, } impl PluginSource { /// Create from an implementation of `GetPlugin` pub fn new(plugin: Arc<dyn GetPlugin>) -> PluginSource { PluginSource { identity: plugin.identity().clone().into(), persistent: Arc::downgrade(&plugin), } } /// Create a new fake source with a fake identity, for testing /// /// Warning: [`.persistent()`](Self::persistent) will always return an error. pub fn new_fake(name: &str) -> PluginSource { PluginSource { identity: PluginIdentity::new_fake(name).into(), persistent: Weak::<crate::PersistentPlugin>::new(), } } /// Try to upgrade the persistent reference, and return an error referencing `span` as the /// object that referenced it otherwise pub fn persistent(&self, span: Option<Span>) -> Result<Arc<dyn GetPlugin>, ShellError> { self.persistent .upgrade() .ok_or_else(|| ShellError::GenericError { error: format!("The `{}` plugin is no longer present", self.identity.name()), msg: "removed since this object was created".into(), span, help: Some("try recreating the object that came from the plugin".into()), inner: vec![], }) } /// Sources are compatible if their identities are equal pub(crate) fn is_compatible(&self, other: &PluginSource) -> bool { self.identity == other.identity } } impl std::ops::Deref for PluginSource { type Target = PluginIdentity; fn deref(&self) -> &PluginIdentity { &self.identity } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-engine/src/lib.rs
crates/nu-plugin-engine/src/lib.rs
//! Provides functionality for running Nushell plugins from a Nushell engine. mod context; mod declaration; mod gc; mod init; mod interface; mod persistent; mod plugin_custom_value_with_source; mod process; mod source; mod util; #[cfg(test)] mod test_util; pub use context::{PluginExecutionCommandContext, PluginExecutionContext}; pub use declaration::PluginDeclaration; pub use gc::PluginGc; pub use init::*; pub use interface::{PluginInterface, PluginInterfaceManager}; pub use persistent::{GetPlugin, PersistentPlugin}; pub use plugin_custom_value_with_source::{PluginCustomValueWithSource, WithSource}; pub use source::PluginSource;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-engine/src/gc.rs
crates/nu-plugin-engine/src/gc.rs
use crate::PersistentPlugin; use nu_protocol::{PluginGcConfig, RegisteredPlugin}; use std::{ sync::{Arc, Weak, mpsc}, thread, time::{Duration, Instant}, }; /// Plugin garbage collector /// /// Many users don't want all of their plugins to stay running indefinitely after using them, so /// this runs a thread that monitors the plugin's usage and stops it automatically if it meets /// certain conditions of inactivity. #[derive(Debug, Clone)] pub struct PluginGc { sender: mpsc::Sender<PluginGcMsg>, } impl PluginGc { /// Start a new plugin garbage collector. Returns an error if the thread failed to spawn. pub fn new( config: PluginGcConfig, plugin: &Arc<PersistentPlugin>, ) -> std::io::Result<PluginGc> { let (sender, receiver) = mpsc::channel(); let mut state = PluginGcState { config, last_update: None, locks: 0, disabled: false, plugin: Arc::downgrade(plugin), name: plugin.identity().name().to_owned(), }; thread::Builder::new() .name(format!("plugin gc ({})", plugin.identity().name())) .spawn(move || state.run(receiver))?; Ok(PluginGc { sender }) } /// Update the garbage collector config pub fn set_config(&self, config: PluginGcConfig) { let _ = self.sender.send(PluginGcMsg::SetConfig(config)); } /// Ensure all GC messages have been processed pub fn flush(&self) { let (tx, rx) = mpsc::channel(); let _ = self.sender.send(PluginGcMsg::Flush(tx)); // This will block until the channel is dropped, which could be because the send failed, or // because the GC got the message let _ = rx.recv(); } /// Increment the number of locks held by the plugin pub fn increment_locks(&self, amount: i64) { let _ = self.sender.send(PluginGcMsg::AddLocks(amount)); } /// Decrement the number of locks held by the plugin pub fn decrement_locks(&self, amount: i64) { let _ = self.sender.send(PluginGcMsg::AddLocks(-amount)); } /// Set whether the GC is disabled by explicit request from the plugin. This is separate from /// the `enabled` option in the config, and overrides that option. pub fn set_disabled(&self, disabled: bool) { let _ = self.sender.send(PluginGcMsg::SetDisabled(disabled)); } /// Tell the GC to stop tracking the plugin. The plugin will not be stopped. The GC cannot be /// reactivated after this request - a new one must be created instead. pub fn stop_tracking(&self) { let _ = self.sender.send(PluginGcMsg::StopTracking); } /// Tell the GC that the plugin exited so that it can remove it from the persistent plugin. /// /// The reason the plugin tells the GC rather than just stopping itself via `source` is that /// it can't guarantee that the plugin currently pointed to by `source` is itself, but if the /// GC is still running, it hasn't received [`.stop_tracking()`](Self::stop_tracking) yet, which /// means it should be the right plugin. pub fn exited(&self) { let _ = self.sender.send(PluginGcMsg::Exited); } } #[derive(Debug)] enum PluginGcMsg { SetConfig(PluginGcConfig), Flush(mpsc::Sender<()>), AddLocks(i64), SetDisabled(bool), StopTracking, Exited, } #[derive(Debug)] struct PluginGcState { config: PluginGcConfig, last_update: Option<Instant>, locks: i64, disabled: bool, plugin: Weak<PersistentPlugin>, name: String, } impl PluginGcState { fn next_timeout(&self, now: Instant) -> Option<Duration> { if self.locks <= 0 && !self.disabled { self.last_update .zip(self.config.enabled.then_some(self.config.stop_after)) .map(|(last_update, stop_after)| { // If configured to stop, and used at some point, calculate the difference let stop_after_duration = Duration::from_nanos(stop_after.max(0) as u64); let duration_since_last_update = now.duration_since(last_update); stop_after_duration.saturating_sub(duration_since_last_update) }) } else { // Don't timeout if there are locks set, or disabled None } } // returns `Some()` if the GC should not continue to operate, with `true` if it should stop the // plugin, or `false` if it should not fn handle_message(&mut self, msg: PluginGcMsg) -> Option<bool> { match msg { PluginGcMsg::SetConfig(config) => { self.config = config; } PluginGcMsg::Flush(sender) => { // Rather than sending a message, we just drop the channel, which causes the other // side to disconnect equally well drop(sender); } PluginGcMsg::AddLocks(amount) => { self.locks += amount; if self.locks < 0 { log::warn!( "Plugin GC ({name}) problem: locks count below zero after adding \ {amount}: locks={locks}", name = self.name, locks = self.locks, ); } // Any time locks are modified, that counts as activity self.last_update = Some(Instant::now()); } PluginGcMsg::SetDisabled(disabled) => { self.disabled = disabled; } PluginGcMsg::StopTracking => { // Immediately exit without stopping the plugin return Some(false); } PluginGcMsg::Exited => { // Exit and stop the plugin return Some(true); } } None } fn run(&mut self, receiver: mpsc::Receiver<PluginGcMsg>) { let mut always_stop = false; loop { let Some(msg) = (match self.next_timeout(Instant::now()) { Some(duration) => receiver.recv_timeout(duration).ok(), None => receiver.recv().ok(), }) else { // If the timeout was reached, or the channel is disconnected, break the loop break; }; log::trace!("Plugin GC ({name}) message: {msg:?}", name = self.name); if let Some(should_stop) = self.handle_message(msg) { // Exit the GC if should_stop { // If should_stop = true, attempt to stop the plugin always_stop = true; break; } else { // Don't stop the plugin return; } } } // Upon exiting the loop, if the timeout reached zero, or we are exiting due to an Exited // message, stop the plugin if always_stop || self .next_timeout(Instant::now()) .is_some_and(|t| t.is_zero()) { // We only hold a weak reference, and it's not an error if we fail to upgrade it - // that just means the plugin is definitely stopped anyway. if let Some(plugin) = self.plugin.upgrade() { let name = &self.name; if let Err(err) = plugin.stop() { log::warn!("Plugin `{name}` failed to be stopped by GC: {err}"); } else { log::debug!("Plugin `{name}` successfully stopped by GC"); } } } } } #[cfg(test)] mod tests { use super::*; fn test_state() -> PluginGcState { PluginGcState { config: PluginGcConfig::default(), last_update: None, locks: 0, disabled: false, plugin: Weak::new(), name: "test".into(), } } #[test] fn timeout_configured_as_zero() { let now = Instant::now(); let mut state = test_state(); state.config.enabled = true; state.config.stop_after = 0; state.last_update = Some(now); assert_eq!(Some(Duration::ZERO), state.next_timeout(now)); } #[test] fn timeout_past_deadline() { let now = Instant::now(); let mut state = test_state(); state.config.enabled = true; state.config.stop_after = Duration::from_secs(1).as_nanos() as i64; state.last_update = Some(now.checked_sub(Duration::from_secs(2)).unwrap()); assert_eq!(Some(Duration::ZERO), state.next_timeout(now)); } #[test] fn timeout_with_deadline_in_future() { let now = Instant::now(); let mut state = test_state(); state.config.enabled = true; state.config.stop_after = Duration::from_secs(1).as_nanos() as i64; state.last_update = Some(now); assert_eq!(Some(Duration::from_secs(1)), state.next_timeout(now)); } #[test] fn no_timeout_if_disabled_by_config() { let now = Instant::now(); let mut state = test_state(); state.config.enabled = false; state.last_update = Some(now); assert_eq!(None, state.next_timeout(now)); } #[test] fn no_timeout_if_disabled_by_plugin() { let now = Instant::now(); let mut state = test_state(); state.config.enabled = true; state.disabled = true; state.last_update = Some(now); assert_eq!(None, state.next_timeout(now)); } #[test] fn no_timeout_if_locks_count_over_zero() { let now = Instant::now(); let mut state = test_state(); state.config.enabled = true; state.locks = 1; state.last_update = Some(now); assert_eq!(None, state.next_timeout(now)); } #[test] fn adding_locks_changes_last_update() { let mut state = test_state(); let original_last_update = Some(Instant::now().checked_sub(Duration::from_secs(1)).unwrap()); state.last_update = original_last_update; state.handle_message(PluginGcMsg::AddLocks(1)); assert_ne!(original_last_update, state.last_update, "not updated"); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-engine/src/process.rs
crates/nu-plugin-engine/src/process.rs
use std::sync::{Arc, Mutex, MutexGuard, atomic::AtomicU32}; use nu_protocol::{ShellError, Span}; use nu_system::ForegroundGuard; /// Provides a utility interface for a plugin interface to manage the process the plugin is running /// in. #[derive(Debug)] pub(crate) struct PluginProcess { pid: u32, mutable: Mutex<MutablePart>, } #[derive(Debug)] struct MutablePart { foreground_guard: Option<ForegroundGuard>, } impl PluginProcess { /// Manage a plugin process. pub(crate) fn new(pid: u32) -> PluginProcess { PluginProcess { pid, mutable: Mutex::new(MutablePart { foreground_guard: None, }), } } /// The process ID of the plugin. pub(crate) fn pid(&self) -> u32 { self.pid } fn lock_mutable(&self) -> Result<MutexGuard<'_, MutablePart>, ShellError> { self.mutable.lock().map_err(|_| ShellError::NushellFailed { msg: "the PluginProcess mutable lock has been poisoned".into(), }) } /// Move the plugin process to the foreground. See [`ForegroundGuard::new`]. /// /// This produces an error if the plugin process was already in the foreground. /// /// Returns `Some()` on Unix with the process group ID if the plugin process will need to join /// another process group to be part of the foreground. pub(crate) fn enter_foreground( &self, span: Span, pipeline_state: &Arc<(AtomicU32, AtomicU32)>, ) -> Result<Option<u32>, ShellError> { let pid = self.pid; let mut mutable = self.lock_mutable()?; if mutable.foreground_guard.is_none() { let guard = ForegroundGuard::new(pid, pipeline_state).map_err(|err| { ShellError::GenericError { error: "Failed to enter foreground".into(), msg: err.to_string(), span: Some(span), help: None, inner: vec![], } })?; let pgrp = guard.pgrp(); mutable.foreground_guard = Some(guard); Ok(pgrp) } else { Err(ShellError::GenericError { error: "Can't enter foreground".into(), msg: "this plugin is already running in the foreground".into(), span: Some(span), help: Some( "you may be trying to run the command in parallel, or this may be a bug in \ the plugin" .into(), ), inner: vec![], }) } } /// Move the plugin process out of the foreground. See [`ForegroundGuard`]. /// /// This is a no-op if the plugin process was already in the background. pub(crate) fn exit_foreground(&self) -> Result<(), ShellError> { let mut mutable = self.lock_mutable()?; drop(mutable.foreground_guard.take()); Ok(()) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-engine/src/test_util.rs
crates/nu-plugin-engine/src/test_util.rs
use std::sync::Arc; use nu_plugin_core::interface_test_util::TestCase; use nu_plugin_protocol::{PluginInput, PluginOutput, test_util::test_plugin_custom_value}; use crate::{PluginCustomValueWithSource, PluginInterfaceManager, PluginSource}; pub trait TestCaseExt { /// Create a new [`PluginInterfaceManager`] that writes to this test case. fn plugin(&self, name: &str) -> PluginInterfaceManager; } impl TestCaseExt for TestCase<PluginOutput, PluginInput> { fn plugin(&self, name: &str) -> PluginInterfaceManager { PluginInterfaceManager::new(PluginSource::new_fake(name).into(), None, self.clone()) } } pub fn test_plugin_custom_value_with_source() -> PluginCustomValueWithSource { PluginCustomValueWithSource::new( test_plugin_custom_value(), Arc::new(PluginSource::new_fake("test")), ) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-engine/src/init.rs
crates/nu-plugin-engine/src/init.rs
use std::{ io::{BufReader, BufWriter}, path::Path, process::Child, sync::{Arc, Mutex}, }; #[cfg(unix)] use std::os::unix::process::CommandExt; #[cfg(windows)] use std::os::windows::process::CommandExt; use nu_plugin_core::{ CommunicationMode, EncodingType, InterfaceManager, PreparedServerCommunication, ServerCommunicationIo, }; use nu_protocol::{ PluginIdentity, PluginRegistryFile, PluginRegistryItem, PluginRegistryItemData, RegisteredPlugin, ShellError, Span, engine::StateWorkingSet, report_shell_error, }; use crate::{ PersistentPlugin, PluginDeclaration, PluginGc, PluginInterface, PluginInterfaceManager, PluginSource, }; /// This should be larger than the largest commonly sent message to avoid excessive fragmentation. /// /// The buffers coming from byte streams are typically each 8192 bytes, so double that. pub(crate) const OUTPUT_BUFFER_SIZE: usize = 16384; /// Spawn the command for a plugin, in the given `mode`. After spawning, it can be passed to /// [`make_plugin_interface()`] to get a [`PluginInterface`]. pub fn create_command( path: &Path, mut shell: Option<&Path>, mode: &CommunicationMode, ) -> std::process::Command { log::trace!("Starting plugin: {path:?}, shell = {shell:?}, mode = {mode:?}"); let mut shell_args = vec![]; if shell.is_none() { // We only have to do this for things that are not executable by Rust's Command API on // Windows. They do handle bat/cmd files for us, helpfully. // // Also include anything that wouldn't be executable with a shebang, like JAR files. shell = match path.extension().and_then(|e| e.to_str()) { Some("sh") => { if cfg!(unix) { // We don't want to override what might be in the shebang if this is Unix, since // some scripts will have a shebang specifying bash even if they're .sh None } else { Some(Path::new("sh")) } } Some("nu") => { shell_args.push("--stdin"); Some(Path::new("nu")) } Some("py") => Some(Path::new("python")), Some("rb") => Some(Path::new("ruby")), Some("jar") => { shell_args.push("-jar"); Some(Path::new("java")) } _ => None, }; } let mut process = if let Some(shell) = shell { let mut process = std::process::Command::new(shell); process.args(shell_args); process.arg(path); process } else { std::process::Command::new(path) }; process.args(mode.args()); // Setup I/O according to the communication mode mode.setup_command_io(&mut process); // The plugin should be run in a new process group to prevent Ctrl-C from stopping it #[cfg(unix)] process.process_group(0); #[cfg(windows)] process.creation_flags(windows::Win32::System::Threading::CREATE_NEW_PROCESS_GROUP.0); // In order to make bugs with improper use of filesystem without getting the engine current // directory more obvious, the plugin always starts in the directory of its executable if let Some(dirname) = path.parent() { process.current_dir(dirname); } process } /// Create a plugin interface from a spawned child process. /// /// `comm` determines the communication type the process was spawned with, and whether stdio will /// be taken from the child. pub fn make_plugin_interface( mut child: Child, comm: PreparedServerCommunication, source: Arc<PluginSource>, pid: Option<u32>, gc: Option<PluginGc>, ) -> Result<PluginInterface, ShellError> { match comm.connect(&mut child)? { ServerCommunicationIo::Stdio(stdin, stdout) => make_plugin_interface_with_streams( stdout, stdin, move || { let _ = child.wait(); }, source, pid, gc, ), #[cfg(feature = "local-socket")] ServerCommunicationIo::LocalSocket { read_out, write_in } => { make_plugin_interface_with_streams( read_out, write_in, move || { let _ = child.wait(); }, source, pid, gc, ) } } } /// Create a plugin interface from low-level components. /// /// - `after_close` is called to clean up after the `reader` ends. /// - `source` is required so that custom values produced by the plugin can spawn it. /// - `pid` may be provided for process management (e.g. `EnterForeground`). /// - `gc` may be provided for communication with the plugin's GC (e.g. `SetGcDisabled`). pub fn make_plugin_interface_with_streams( mut reader: impl std::io::Read + Send + 'static, writer: impl std::io::Write + Send + 'static, after_close: impl FnOnce() + Send + 'static, source: Arc<PluginSource>, pid: Option<u32>, gc: Option<PluginGc>, ) -> Result<PluginInterface, ShellError> { let encoder = get_plugin_encoding(&mut reader)?; let reader = BufReader::with_capacity(OUTPUT_BUFFER_SIZE, reader); let writer = BufWriter::with_capacity(OUTPUT_BUFFER_SIZE, writer); let mut manager = PluginInterfaceManager::new(source.clone(), pid, (Mutex::new(writer), encoder)); manager.set_garbage_collector(gc); let interface = manager.get_interface(); interface.hello()?; // Spawn the reader on a new thread. We need to be able to read messages at the same time that // we write, because we are expected to be able to handle multiple messages coming in from the // plugin at any time, including stream messages like `Drop`. std::thread::Builder::new() .name(format!( "plugin interface reader ({})", source.identity.name() )) .spawn(move || { if let Err(err) = manager.consume_all((reader, encoder)) { log::warn!("Error in PluginInterfaceManager: {err}"); } // If the loop has ended, drop the manager so everyone disconnects and then run // after_close drop(manager); after_close(); }) .map_err(|err| ShellError::PluginFailedToLoad { msg: format!("Failed to spawn thread for plugin: {err}"), })?; Ok(interface) } /// Determine the plugin's encoding from a freshly opened stream. /// /// The plugin is expected to send a 1-byte length and either `json` or `msgpack`, so this reads /// that and determines the right length. pub fn get_plugin_encoding( child_stdout: &mut impl std::io::Read, ) -> Result<EncodingType, ShellError> { let mut length_buf = [0u8; 1]; child_stdout .read_exact(&mut length_buf) .map_err(|e| ShellError::PluginFailedToLoad { msg: format!("unable to get encoding from plugin: {e}"), })?; let mut buf = vec![0u8; length_buf[0] as usize]; child_stdout .read_exact(&mut buf) .map_err(|e| ShellError::PluginFailedToLoad { msg: format!("unable to get encoding from plugin: {e}"), })?; EncodingType::try_from_bytes(&buf).ok_or_else(|| { let encoding_for_debug = String::from_utf8_lossy(&buf); ShellError::PluginFailedToLoad { msg: format!("get unsupported plugin encoding: {encoding_for_debug}"), } }) } /// Load the definitions from the plugin file into the engine state pub fn load_plugin_file( working_set: &mut StateWorkingSet, plugin_registry_file: &PluginRegistryFile, span: Option<Span>, ) { for plugin in &plugin_registry_file.plugins { // Any errors encountered should just be logged. if let Err(err) = load_plugin_registry_item(working_set, plugin, span) { report_shell_error(None, working_set.permanent_state, &err) } } } /// Load a definition from the plugin file into the engine state pub fn load_plugin_registry_item( working_set: &mut StateWorkingSet, plugin: &PluginRegistryItem, span: Option<Span>, ) -> Result<Arc<PersistentPlugin>, ShellError> { let identity = PluginIdentity::new(plugin.filename.clone(), plugin.shell.clone()).map_err(|_| { ShellError::GenericError { error: "Invalid plugin filename in plugin registry file".into(), msg: "loaded from here".into(), span, help: Some(format!( "the filename for `{}` is not a valid nushell plugin: {}", plugin.name, plugin.filename.display() )), inner: vec![], } })?; match &plugin.data { PluginRegistryItemData::Valid { metadata, commands } => { let plugin = add_plugin_to_working_set(working_set, &identity)?; // Ensure that the plugin is reset. We're going to load new signatures, so we want to // make sure the running plugin reflects those new signatures, and it's possible that it // doesn't. plugin.reset()?; // Set the plugin metadata from the file plugin.set_metadata(Some(metadata.clone())); // Create the declarations from the commands for signature in commands { let decl = PluginDeclaration::new(plugin.clone(), signature.clone()); working_set.add_decl(Box::new(decl)); } Ok(plugin) } PluginRegistryItemData::Invalid => Err(ShellError::PluginRegistryDataInvalid { plugin_name: identity.name().to_owned(), span, add_command: identity.add_command(), }), } } /// Find [`PersistentPlugin`] with the given `identity` in the `working_set`, or construct it /// if it doesn't exist. /// /// The garbage collection config is always found and set in either case. pub fn add_plugin_to_working_set( working_set: &mut StateWorkingSet, identity: &PluginIdentity, ) -> Result<Arc<PersistentPlugin>, ShellError> { // Find garbage collection config for the plugin let gc_config = working_set .get_config() .plugin_gc .get(identity.name()) .clone(); // Add it to / get it from the working set let plugin = working_set.find_or_create_plugin(identity, || { Arc::new(PersistentPlugin::new(identity.clone(), gc_config.clone())) }); plugin.set_gc_config(&gc_config); // Downcast the plugin to `PersistentPlugin` - we generally expect this to succeed. // The trait object only exists so that nu-protocol can contain plugins without knowing // anything about their implementation, but we only use `PersistentPlugin` in practice. plugin .as_any() .downcast() .map_err(|_| ShellError::NushellFailed { msg: "encountered unexpected RegisteredPlugin type".into(), }) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-engine/src/persistent.rs
crates/nu-plugin-engine/src/persistent.rs
use crate::{ PluginGc, init::{create_command, make_plugin_interface}, }; use super::{PluginInterface, PluginSource}; use nu_plugin_core::CommunicationMode; use nu_protocol::{ HandlerGuard, Handlers, PluginGcConfig, PluginIdentity, PluginMetadata, RegisteredPlugin, ShellError, engine::{EngineState, Stack}, shell_error::io::IoError, }; use std::{ collections::HashMap, sync::{Arc, Mutex}, }; /// A box that can keep a plugin that was spawned persistent for further uses. The plugin may or /// may not be currently running. [`.get()`] gets the currently running plugin, or spawns it if it's /// not running. #[derive(Debug)] pub struct PersistentPlugin { /// Identity (filename, shell, name) of the plugin identity: PluginIdentity, /// Mutable state mutable: Mutex<MutableState>, } /// The mutable state for the persistent plugin. This should all be behind one lock to prevent lock /// order problems. #[derive(Debug)] struct MutableState { /// Reference to the plugin if running running: Option<RunningPlugin>, /// Metadata for the plugin, e.g. version. metadata: Option<PluginMetadata>, /// Plugin's preferred communication mode (if known) preferred_mode: Option<PreferredCommunicationMode>, /// Garbage collector config gc_config: PluginGcConfig, /// RAII guard for this plugin's signal handler signal_guard: Option<HandlerGuard>, } #[derive(Debug, Clone, Copy)] enum PreferredCommunicationMode { Stdio, #[cfg(feature = "local-socket")] LocalSocket, } #[derive(Debug)] struct RunningPlugin { /// Interface (which can be cloned) to the running plugin interface: PluginInterface, /// Garbage collector for the plugin gc: PluginGc, } impl PersistentPlugin { /// Create a new persistent plugin. The plugin will not be spawned immediately. pub fn new(identity: PluginIdentity, gc_config: PluginGcConfig) -> PersistentPlugin { PersistentPlugin { identity, mutable: Mutex::new(MutableState { running: None, metadata: None, preferred_mode: None, gc_config, signal_guard: None, }), } } /// Get the plugin interface of the running plugin, or spawn it if it's not currently running. /// /// Will call `envs` to get environment variables to spawn the plugin if the plugin needs to be /// spawned. pub fn get( self: Arc<Self>, envs: impl FnOnce() -> Result<HashMap<String, String>, ShellError>, ) -> Result<PluginInterface, ShellError> { let mut mutable = self.mutable.lock().map_err(|_| ShellError::NushellFailed { msg: format!( "plugin `{}` mutex poisoned, probably panic during spawn", self.identity.name() ), })?; if let Some(ref running) = mutable.running { // It exists, so just clone the interface Ok(running.interface.clone()) } else { // Try to spawn. On success, `mutable.running` should have been set to the new running // plugin by `spawn()` so we just then need to clone the interface from there. // // We hold the lock the whole time to prevent others from trying to spawn and ending // up with duplicate plugins // // TODO: We should probably store the envs somewhere, in case we have to launch without // envs (e.g. from a custom value) let envs = envs()?; let result = self.clone().spawn(&envs, &mut mutable); // Check if we were using an alternate communication mode and may need to fall back to // stdio. if result.is_err() && !matches!( mutable.preferred_mode, Some(PreferredCommunicationMode::Stdio) ) { log::warn!( "{}: Trying again with stdio communication because mode {:?} failed with {result:?}", self.identity.name(), mutable.preferred_mode ); // Reset to stdio and try again, but this time don't catch any error mutable.preferred_mode = Some(PreferredCommunicationMode::Stdio); self.clone().spawn(&envs, &mut mutable)?; } Ok(mutable .running .as_ref() .ok_or_else(|| ShellError::NushellFailed { msg: "spawn() succeeded but didn't set interface".into(), })? .interface .clone()) } } /// Run the plugin command, then set up and set `mutable.running` to the new running plugin. fn spawn( self: Arc<Self>, envs: &HashMap<String, String>, mutable: &mut MutableState, ) -> Result<(), ShellError> { // Make sure `running` is set to None to begin if let Some(running) = mutable.running.take() { // Stop the GC if there was a running plugin running.gc.stop_tracking(); } let source_file = self.identity.filename(); // Determine the mode to use based on the preferred mode let mode = match mutable.preferred_mode { // If not set, we try stdio first and then might retry if another mode is supported Some(PreferredCommunicationMode::Stdio) | None => CommunicationMode::Stdio, // Local socket only if enabled #[cfg(feature = "local-socket")] Some(PreferredCommunicationMode::LocalSocket) => { CommunicationMode::local_socket(source_file) } }; let mut plugin_cmd = create_command(source_file, self.identity.shell(), &mode); // We need the current environment variables for `python` based plugins // Or we'll likely have a problem when a plugin is implemented in a virtual Python environment. plugin_cmd.envs(envs); let program_name = plugin_cmd.get_program().to_os_string().into_string(); // Before running the command, prepare communication let comm = mode.serve()?; // Run the plugin command let child = plugin_cmd.spawn().map_err(|err| { let error_msg = match err.kind() { std::io::ErrorKind::NotFound => match program_name { Ok(prog_name) => { format!( "Can't find {prog_name}, please make sure that {prog_name} is in PATH." ) } _ => { format!("Error spawning child process: {err}") } }, _ => { format!("Error spawning child process: {err}") } }; ShellError::PluginFailedToLoad { msg: error_msg } })?; // Start the plugin garbage collector let gc = PluginGc::new(mutable.gc_config.clone(), &self).map_err(|err| { IoError::new_internal(err, "Could not start plugin gc", nu_protocol::location!()) })?; let pid = child.id(); let interface = make_plugin_interface( child, comm, Arc::new(PluginSource::new(self.clone())), Some(pid), Some(gc.clone()), )?; // If our current preferred mode is None, check to see if the plugin might support another // mode. If so, retry spawn() with that mode #[cfg(feature = "local-socket")] if mutable.preferred_mode.is_none() && interface .protocol_info()? .supports_feature(&nu_plugin_protocol::Feature::LocalSocket) { log::trace!( "{}: Attempting to upgrade to local socket mode", self.identity.name() ); // Stop the GC we just created from tracking so that we don't accidentally try to // stop the new plugin gc.stop_tracking(); // Set the mode and try again mutable.preferred_mode = Some(PreferredCommunicationMode::LocalSocket); return self.spawn(envs, mutable); } mutable.running = Some(RunningPlugin { interface, gc }); Ok(()) } fn stop_internal(&self, reset: bool) -> Result<(), ShellError> { let mut mutable = self.mutable.lock().map_err(|_| ShellError::NushellFailed { msg: format!( "plugin `{}` mutable mutex poisoned, probably panic during spawn", self.identity.name() ), })?; // If the plugin is running, stop its GC, so that the GC doesn't accidentally try to stop // a future plugin if let Some(ref running) = mutable.running { running.gc.stop_tracking(); } // We don't try to kill the process or anything, we just drop the RunningPlugin. It should // exit soon after mutable.running = None; // If this is a reset, we should also reset other learned attributes like preferred_mode if reset { mutable.preferred_mode = None; } Ok(()) } } impl RegisteredPlugin for PersistentPlugin { fn identity(&self) -> &PluginIdentity { &self.identity } fn is_running(&self) -> bool { // If the lock is poisoned, we return false here. That may not be correct, but this is a // failure state anyway that would be noticed at some point self.mutable .lock() .map(|m| m.running.is_some()) .unwrap_or(false) } fn pid(&self) -> Option<u32> { // Again, we return None for a poisoned lock. self.mutable .lock() .ok() .and_then(|r| r.running.as_ref().and_then(|r| r.interface.pid())) } fn stop(&self) -> Result<(), ShellError> { self.stop_internal(false) } fn reset(&self) -> Result<(), ShellError> { self.stop_internal(true) } fn metadata(&self) -> Option<PluginMetadata> { self.mutable.lock().ok().and_then(|m| m.metadata.clone()) } fn set_metadata(&self, metadata: Option<PluginMetadata>) { if let Ok(mut mutable) = self.mutable.lock() { mutable.metadata = metadata; } } fn set_gc_config(&self, gc_config: &PluginGcConfig) { if let Ok(mut mutable) = self.mutable.lock() { // Save the new config for future calls mutable.gc_config = gc_config.clone(); // If the plugin is already running, propagate the config change to the running GC if let Some(gc) = mutable.running.as_ref().map(|running| running.gc.clone()) { // We don't want to get caught holding the lock drop(mutable); gc.set_config(gc_config.clone()); gc.flush(); } } } fn as_any(self: Arc<Self>) -> Arc<dyn std::any::Any + Send + Sync> { self } fn configure_signal_handler(self: Arc<Self>, handlers: &Handlers) -> Result<(), ShellError> { let guard = { // We take a weakref to the plugin so that we don't create a cycle to the // RAII guard that will be stored on the plugin. let plugin = Arc::downgrade(&self); handlers.register(Box::new(move |action| { // write a signal packet through the PluginInterface if the plugin is alive and // running if let Some(plugin) = plugin.upgrade() && let Ok(mutable) = plugin.mutable.lock() && let Some(ref running) = mutable.running { let _ = running.interface.signal(action); } }))? }; if let Ok(mut mutable) = self.mutable.lock() { mutable.signal_guard = Some(guard); } Ok(()) } } /// Anything that can produce a plugin interface. pub trait GetPlugin: RegisteredPlugin { /// Retrieve or spawn a [`PluginInterface`]. The `context` may be used for determining /// environment variables to launch the plugin with. fn get_plugin( self: Arc<Self>, context: Option<(&EngineState, &mut Stack)>, ) -> Result<PluginInterface, ShellError>; } impl GetPlugin for PersistentPlugin { fn get_plugin( self: Arc<Self>, mut context: Option<(&EngineState, &mut Stack)>, ) -> Result<PluginInterface, ShellError> { self.get(|| { // Get envs from the context if provided. let envs = context .as_mut() .map(|(engine_state, stack)| { // We need the current environment variables for `python` based plugins. Or // we'll likely have a problem when a plugin is implemented in a virtual Python // environment. let stack = &mut stack.start_collect_value(); nu_engine::env::env_to_strings(engine_state, stack) }) .transpose()?; Ok(envs.unwrap_or_default()) }) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-engine/src/context.rs
crates/nu-plugin-engine/src/context.rs
use crate::util::MutableCow; use nu_engine::{ClosureEvalOnce, get_eval_block_with_early_return, get_full_help}; use nu_plugin_protocol::EvaluatedCall; use nu_protocol::{ BlockId, Config, DeclId, IntoSpanned, OutDest, PipelineData, PluginIdentity, ShellError, Signals, Span, Spanned, Value, engine::{Call, Closure, EngineState, Redirection, Stack}, ir::{self, IrBlock}, }; use std::{ borrow::Cow, collections::HashMap, sync::{Arc, atomic::AtomicU32}, }; /// Object safe trait for abstracting operations required of the plugin context. pub trait PluginExecutionContext: Send + Sync { /// A span pointing to the command being executed fn span(&self) -> Span; /// The [`Signals`] struct, if present fn signals(&self) -> &Signals; /// The pipeline externals state, for tracking the foreground process group, if present fn pipeline_externals_state(&self) -> Option<&Arc<(AtomicU32, AtomicU32)>>; /// Get engine configuration fn get_config(&self) -> Result<Arc<Config>, ShellError>; /// Get plugin configuration fn get_plugin_config(&self) -> Result<Option<Value>, ShellError>; /// Get an environment variable from `$env` fn get_env_var(&self, name: &str) -> Result<Option<&Value>, ShellError>; /// Get all environment variables fn get_env_vars(&self) -> Result<HashMap<String, Value>, ShellError>; /// Get current working directory fn get_current_dir(&self) -> Result<Spanned<String>, ShellError>; /// Set an environment variable fn add_env_var(&mut self, name: String, value: Value) -> Result<(), ShellError>; /// Get help for the current command fn get_help(&self) -> Result<Spanned<String>, ShellError>; /// Get the contents of a [`Span`] fn get_span_contents(&self, span: Span) -> Result<Spanned<Vec<u8>>, ShellError>; /// Evaluate a closure passed to the plugin fn eval_closure( &self, closure: Spanned<Closure>, positional: Vec<Value>, input: PipelineData, redirect_stdout: bool, redirect_stderr: bool, ) -> Result<PipelineData, ShellError>; /// Find a declaration by name fn find_decl(&self, name: &str) -> Result<Option<DeclId>, ShellError>; /// Get the compiled IR for a block fn get_block_ir(&self, block_id: BlockId) -> Result<IrBlock, ShellError>; /// Call a declaration with arguments and input fn call_decl( &mut self, decl_id: DeclId, call: EvaluatedCall, input: PipelineData, redirect_stdout: bool, redirect_stderr: bool, ) -> Result<PipelineData, ShellError>; /// Create an owned version of the context with `'static` lifetime fn boxed(&self) -> Box<dyn PluginExecutionContext>; } /// The execution context of a plugin command. Can be borrowed. pub struct PluginExecutionCommandContext<'a> { identity: Arc<PluginIdentity>, engine_state: Cow<'a, EngineState>, stack: MutableCow<'a, Stack>, call: Call<'a>, } impl<'a> PluginExecutionCommandContext<'a> { pub fn new( identity: Arc<PluginIdentity>, engine_state: &'a EngineState, stack: &'a mut Stack, call: &'a Call<'a>, ) -> PluginExecutionCommandContext<'a> { PluginExecutionCommandContext { identity, engine_state: Cow::Borrowed(engine_state), stack: MutableCow::Borrowed(stack), call: call.clone(), } } } impl PluginExecutionContext for PluginExecutionCommandContext<'_> { fn span(&self) -> Span { self.call.head } fn signals(&self) -> &Signals { self.engine_state.signals() } fn pipeline_externals_state(&self) -> Option<&Arc<(AtomicU32, AtomicU32)>> { Some(&self.engine_state.pipeline_externals_state) } fn get_config(&self) -> Result<Arc<Config>, ShellError> { Ok(self.stack.get_config(&self.engine_state)) } fn get_plugin_config(&self) -> Result<Option<Value>, ShellError> { // Fetch the configuration for a plugin // // The `plugin` must match the registered name of a plugin. For `plugin add // nu_plugin_example` the plugin config lookup uses `"example"` Ok(self .get_config()? .plugins .get(self.identity.name()) .cloned() .map(|value| { let span = value.span(); match value { Value::Closure { val, .. } => { ClosureEvalOnce::new(&self.engine_state, &self.stack, *val) .run_with_input(PipelineData::empty()) .and_then(|data| data.into_value(span)) .unwrap_or_else(|err| Value::error(err, self.call.head)) } _ => value.clone(), } })) } fn get_env_var(&self, name: &str) -> Result<Option<&Value>, ShellError> { Ok(self .stack .get_env_var_insensitive(&self.engine_state, name) .map(|(_, value)| value)) } fn get_env_vars(&self) -> Result<HashMap<String, Value>, ShellError> { Ok(self.stack.get_env_vars(&self.engine_state)) } fn get_current_dir(&self) -> Result<Spanned<String>, ShellError> { #[allow(deprecated)] let cwd = nu_engine::env::current_dir_str(&self.engine_state, &self.stack)?; // The span is not really used, so just give it call.head Ok(cwd.into_spanned(self.call.head)) } fn add_env_var(&mut self, name: String, value: Value) -> Result<(), ShellError> { self.stack.add_env_var(name, value); Ok(()) } fn get_help(&self) -> Result<Spanned<String>, ShellError> { let decl = self.engine_state.get_decl(self.call.decl_id); Ok( get_full_help(decl, &self.engine_state, &mut self.stack.clone()) .into_spanned(self.call.head), ) } fn get_span_contents(&self, span: Span) -> Result<Spanned<Vec<u8>>, ShellError> { Ok(self .engine_state .get_span_contents(span) .to_vec() .into_spanned(self.call.head)) } fn eval_closure( &self, closure: Spanned<Closure>, positional: Vec<Value>, input: PipelineData, redirect_stdout: bool, redirect_stderr: bool, ) -> Result<PipelineData, ShellError> { let block = self .engine_state .try_get_block(closure.item.block_id) .ok_or_else(|| ShellError::GenericError { error: "Plugin misbehaving".into(), msg: format!( "Tried to evaluate unknown block id: {}", closure.item.block_id.get() ), span: Some(closure.span), help: None, inner: vec![], })?; let mut stack = self .stack .captures_to_stack(closure.item.captures) .reset_pipes(); let stack = &mut stack.push_redirection( redirect_stdout.then_some(Redirection::Pipe(OutDest::PipeSeparate)), redirect_stderr.then_some(Redirection::Pipe(OutDest::PipeSeparate)), ); // Set up the positional arguments for (idx, value) in positional.into_iter().enumerate() { if let Some(arg) = block.signature.get_positional(idx) { if let Some(var_id) = arg.var_id { stack.add_var(var_id, value); } else { return Err(ShellError::NushellFailedSpanned { msg: "Error while evaluating closure from plugin".into(), label: "closure argument missing var_id".into(), span: closure.span, }); } } } let eval_block_with_early_return = get_eval_block_with_early_return(&self.engine_state); eval_block_with_early_return(&self.engine_state, stack, block, input).map(|p| p.body) } fn find_decl(&self, name: &str) -> Result<Option<DeclId>, ShellError> { Ok(self.engine_state.find_decl(name.as_bytes(), &[])) } fn get_block_ir(&self, block_id: BlockId) -> Result<IrBlock, ShellError> { let block = self.engine_state .try_get_block(block_id) .ok_or_else(|| ShellError::GenericError { error: "Plugin misbehaving".into(), msg: format!("Tried to get IR for unknown block id: {}", block_id.get()), span: Some(self.call.head), help: None, inner: vec![], })?; block .ir_block .clone() .ok_or_else(|| ShellError::GenericError { error: "Block has no IR".into(), msg: format!("Block {} was not compiled to IR", block_id.get()), span: Some(self.call.head), help: Some( "This block may be a declaration or built-in that has no IR representation" .into(), ), inner: vec![], }) } fn call_decl( &mut self, decl_id: DeclId, call: EvaluatedCall, input: PipelineData, redirect_stdout: bool, redirect_stderr: bool, ) -> Result<PipelineData, ShellError> { if decl_id.get() >= self.engine_state.num_decls() { return Err(ShellError::GenericError { error: "Plugin misbehaving".into(), msg: format!("Tried to call unknown decl id: {}", decl_id.get()), span: Some(call.head), help: None, inner: vec![], }); } let decl = self.engine_state.get_decl(decl_id); let stack = &mut self.stack.push_redirection( redirect_stdout.then_some(Redirection::Pipe(OutDest::PipeSeparate)), redirect_stderr.then_some(Redirection::Pipe(OutDest::PipeSeparate)), ); let mut call_builder = ir::Call::build(decl_id, call.head); for positional in call.positional { call_builder.add_positional(stack, positional.span(), positional); } for (name, value) in call.named { if let Some(value) = value { call_builder.add_named(stack, &name.item, "", name.span, value); } else { call_builder.add_flag(stack, &name.item, "", name.span); } } call_builder.with(stack, |stack, call| { decl.run(&self.engine_state, stack, call, input) }) } fn boxed(&self) -> Box<dyn PluginExecutionContext + 'static> { Box::new(PluginExecutionCommandContext { identity: self.identity.clone(), engine_state: Cow::Owned(self.engine_state.clone().into_owned()), stack: self.stack.owned(), call: self.call.to_owned(), }) } } /// A bogus execution context for testing that doesn't really implement anything properly #[cfg(test)] pub(crate) struct PluginExecutionBogusContext; #[cfg(test)] impl PluginExecutionContext for PluginExecutionBogusContext { fn span(&self) -> Span { Span::test_data() } fn signals(&self) -> &Signals { &Signals::EMPTY } fn pipeline_externals_state(&self) -> Option<&Arc<(AtomicU32, AtomicU32)>> { None } fn get_config(&self) -> Result<Arc<Config>, ShellError> { Err(ShellError::NushellFailed { msg: "get_config not implemented on bogus".into(), }) } fn get_plugin_config(&self) -> Result<Option<Value>, ShellError> { Ok(None) } fn get_env_var(&self, _name: &str) -> Result<Option<&Value>, ShellError> { Err(ShellError::NushellFailed { msg: "get_env_var not implemented on bogus".into(), }) } fn get_env_vars(&self) -> Result<HashMap<String, Value>, ShellError> { Err(ShellError::NushellFailed { msg: "get_env_vars not implemented on bogus".into(), }) } fn get_current_dir(&self) -> Result<Spanned<String>, ShellError> { Err(ShellError::NushellFailed { msg: "get_current_dir not implemented on bogus".into(), }) } fn add_env_var(&mut self, _name: String, _value: Value) -> Result<(), ShellError> { Err(ShellError::NushellFailed { msg: "add_env_var not implemented on bogus".into(), }) } fn get_help(&self) -> Result<Spanned<String>, ShellError> { Err(ShellError::NushellFailed { msg: "get_help not implemented on bogus".into(), }) } fn get_span_contents(&self, _span: Span) -> Result<Spanned<Vec<u8>>, ShellError> { Err(ShellError::NushellFailed { msg: "get_span_contents not implemented on bogus".into(), }) } fn eval_closure( &self, _closure: Spanned<Closure>, _positional: Vec<Value>, _input: PipelineData, _redirect_stdout: bool, _redirect_stderr: bool, ) -> Result<PipelineData, ShellError> { Err(ShellError::NushellFailed { msg: "eval_closure not implemented on bogus".into(), }) } fn find_decl(&self, _name: &str) -> Result<Option<DeclId>, ShellError> { Err(ShellError::NushellFailed { msg: "find_decl not implemented on bogus".into(), }) } fn get_block_ir(&self, _block_id: BlockId) -> Result<IrBlock, ShellError> { Err(ShellError::NushellFailed { msg: "get_block_ir not implemented on bogus".into(), }) } fn call_decl( &mut self, _decl_id: DeclId, _call: EvaluatedCall, _input: PipelineData, _redirect_stdout: bool, _redirect_stderr: bool, ) -> Result<PipelineData, ShellError> { Err(ShellError::NushellFailed { msg: "call_decl not implemented on bogus".into(), }) } fn boxed(&self) -> Box<dyn PluginExecutionContext + 'static> { Box::new(PluginExecutionBogusContext) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-engine/src/util/mutable_cow.rs
crates/nu-plugin-engine/src/util/mutable_cow.rs
/// Like [`Cow`][std::borrow::Cow] but with a mutable reference instead. So not exactly /// clone-on-write, but can be made owned. pub enum MutableCow<'a, T> { Borrowed(&'a mut T), Owned(T), } impl<T: Clone> MutableCow<'_, T> { pub fn owned(&self) -> MutableCow<'static, T> { match self { MutableCow::Borrowed(r) => MutableCow::Owned((*r).clone()), MutableCow::Owned(o) => MutableCow::Owned(o.clone()), } } } impl<T> std::ops::Deref for MutableCow<'_, T> { type Target = T; fn deref(&self) -> &T { match self { MutableCow::Borrowed(r) => r, MutableCow::Owned(o) => o, } } } impl<T> std::ops::DerefMut for MutableCow<'_, T> { fn deref_mut(&mut self) -> &mut Self::Target { match self { MutableCow::Borrowed(r) => r, MutableCow::Owned(o) => o, } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-engine/src/util/mod.rs
crates/nu-plugin-engine/src/util/mod.rs
mod mutable_cow; pub use mutable_cow::MutableCow;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-engine/src/interface/tests.rs
crates/nu-plugin-engine/src/interface/tests.rs
use super::{ Context, PluginCallState, PluginInterface, PluginInterfaceManager, ReceivedPluginCallMessage, }; use crate::{ PluginCustomValueWithSource, PluginSource, context::PluginExecutionBogusContext, interface::CurrentCallState, plugin_custom_value_with_source::WithSource, test_util::*, }; use nu_engine::command_prelude::IoError; use nu_plugin_core::{Interface, InterfaceManager, interface_test_util::TestCase}; use nu_plugin_protocol::{ ByteStreamInfo, CallInfo, CustomValueOp, DynamicCompletionCall, EngineCall, EngineCallResponse, EvaluatedCall, GetCompletionInfo, ListStreamInfo, PipelineDataHeader, PluginCall, PluginCallId, PluginCallResponse, PluginCustomValue, PluginInput, PluginOutput, Protocol, ProtocolInfo, StreamData, StreamMessage, test_util::{expected_test_custom_value, test_plugin_custom_value}, }; use nu_protocol::{ BlockId, ByteStreamType, CustomValue, DynamicSuggestion, Id, IntoInterruptiblePipelineData, IntoSpanned, PipelineData, PipelineMetadata, PluginMetadata, PluginSignature, ShellError, Signals, Span, Spanned, Value, ast::{Math, Operator}, engine::Closure, shell_error, }; use serde::{Deserialize, Serialize}; use std::{ collections::HashMap, sync::{Arc, mpsc}, time::Duration, }; #[test] fn manager_consume_all_consumes_messages() -> Result<(), ShellError> { let mut test = TestCase::new(); let mut manager = test.plugin("test"); // This message should be non-problematic test.add(PluginOutput::Hello(ProtocolInfo::default())); manager.consume_all(&mut test)?; assert!(!test.has_unconsumed_read()); Ok(()) } #[test] fn manager_consume_all_exits_after_streams_and_interfaces_are_dropped() -> Result<(), ShellError> { let mut test = TestCase::new(); let mut manager = test.plugin("test"); // Add messages that won't cause errors for _ in 0..5 { test.add(PluginOutput::Hello(ProtocolInfo::default())); } // Create a stream... let stream = manager.read_pipeline_data( PipelineDataHeader::list_stream(ListStreamInfo::new(0, Span::test_data())), &Signals::empty(), )?; // and an interface... let interface = manager.get_interface(); // Expect that is_finished is false assert!( !manager.is_finished(), "is_finished is true even though active stream/interface exists" ); // After dropping, it should be true drop(stream); drop(interface); assert!( manager.is_finished(), "is_finished is false even though manager has no stream or interface" ); // When it's true, consume_all shouldn't consume everything manager.consume_all(&mut test)?; assert!( test.has_unconsumed_read(), "consume_all consumed the messages" ); Ok(()) } fn test_io_error() -> ShellError { ShellError::Io(IoError::new_with_additional_context( shell_error::io::ErrorKind::from_std(std::io::ErrorKind::Other), Span::test_data(), None, "test io error", )) } fn check_test_io_error(error: &ShellError) { assert!( format!("{error:?}").contains("test io error"), "error: {error}" ); } #[test] fn manager_consume_all_propagates_io_error_to_readers() -> Result<(), ShellError> { let mut test = TestCase::new(); let mut manager = test.plugin("test"); test.set_read_error(test_io_error()); let stream = manager.read_pipeline_data( PipelineDataHeader::list_stream(ListStreamInfo::new(0, Span::test_data())), &Signals::empty(), )?; manager .consume_all(&mut test) .expect_err("consume_all did not error"); // Ensure end of stream drop(manager); let value = stream.into_iter().next().expect("stream is empty"); if let Value::Error { error, .. } = value { check_test_io_error(&error); Ok(()) } else { panic!("did not get an error"); } } fn invalid_output() -> PluginOutput { // This should definitely cause an error, as 0.0.0 is not compatible with any version other than // itself PluginOutput::Hello(ProtocolInfo { protocol: Protocol::NuPlugin, version: "0.0.0".into(), features: vec![], }) } fn check_invalid_output_error(error: &ShellError) { // the error message should include something about the version... assert!(format!("{error:?}").contains("0.0.0"), "error: {error}"); } #[test] fn manager_consume_all_propagates_message_error_to_readers() -> Result<(), ShellError> { let mut test = TestCase::new(); let mut manager = test.plugin("test"); test.add(invalid_output()); let stream = manager.read_pipeline_data( PipelineDataHeader::byte_stream(ByteStreamInfo::new( 0, Span::test_data(), ByteStreamType::Unknown, )), &Signals::empty(), )?; manager .consume_all(&mut test) .expect_err("consume_all did not error"); // Ensure end of stream drop(manager); let value = stream.into_iter().next().expect("stream is empty"); if let Value::Error { error, .. } = value { check_invalid_output_error(&error); Ok(()) } else { panic!("did not get an error"); } } fn fake_plugin_call( manager: &mut PluginInterfaceManager, id: PluginCallId, ) -> mpsc::Receiver<ReceivedPluginCallMessage> { // Set up a fake plugin call subscription let (tx, rx) = mpsc::channel(); manager.plugin_call_states.insert( id, PluginCallState { sender: Some(tx), dont_send_response: false, signals: Signals::empty(), context_rx: None, span: None, keep_plugin_custom_values: mpsc::channel(), remaining_streams_to_read: 0, }, ); rx } #[test] fn manager_consume_all_propagates_io_error_to_plugin_calls() -> Result<(), ShellError> { let mut test = TestCase::new(); let mut manager = test.plugin("test"); let interface = manager.get_interface(); test.set_read_error(test_io_error()); // Set up a fake plugin call subscription let rx = fake_plugin_call(&mut manager, 0); manager .consume_all(&mut test) .expect_err("consume_all did not error"); let message = rx.try_recv().expect("failed to get plugin call message"); match message { ReceivedPluginCallMessage::Error(error) => { check_test_io_error(&error); } _ => panic!("received something other than an error: {message:?}"), } // Check that further calls also cause the error match interface.get_signature() { Ok(_) => panic!("plugin call after exit did not cause error somehow"), Err(err) => { check_test_io_error(&err); Ok(()) } } } #[test] fn manager_consume_all_propagates_message_error_to_plugin_calls() -> Result<(), ShellError> { let mut test = TestCase::new(); let mut manager = test.plugin("test"); let interface = manager.get_interface(); test.add(invalid_output()); // Set up a fake plugin call subscription let rx = fake_plugin_call(&mut manager, 0); manager .consume_all(&mut test) .expect_err("consume_all did not error"); let message = rx.try_recv().expect("failed to get plugin call message"); match message { ReceivedPluginCallMessage::Error(error) => { check_invalid_output_error(&error); } _ => panic!("received something other than an error: {message:?}"), } // Check that further calls also cause the error match interface.get_signature() { Ok(_) => panic!("plugin call after exit did not cause error somehow"), Err(err) => { check_invalid_output_error(&err); Ok(()) } } } #[test] fn manager_consume_sets_protocol_info_on_hello() -> Result<(), ShellError> { let mut manager = TestCase::new().plugin("test"); let info = ProtocolInfo::default(); manager.consume(PluginOutput::Hello(info.clone()))?; let set_info = manager .state .protocol_info .try_get()? .expect("protocol info not set"); assert_eq!(info.version, set_info.version); Ok(()) } #[test] fn manager_consume_errors_on_wrong_nushell_version() -> Result<(), ShellError> { let mut manager = TestCase::new().plugin("test"); let info = ProtocolInfo { protocol: Protocol::NuPlugin, version: "0.0.0".into(), features: vec![], }; manager .consume(PluginOutput::Hello(info)) .expect_err("version 0.0.0 should cause an error"); Ok(()) } #[test] fn manager_consume_errors_on_sending_other_messages_before_hello() -> Result<(), ShellError> { let mut manager = TestCase::new().plugin("test"); // hello not set assert!(!manager.state.protocol_info.is_set()); let error = manager .consume(PluginOutput::Drop(0)) .expect_err("consume before Hello should cause an error"); assert!(format!("{error:?}").contains("Hello")); Ok(()) } fn set_default_protocol_info(manager: &mut PluginInterfaceManager) -> Result<(), ShellError> { manager .protocol_info_mut .set(Arc::new(ProtocolInfo::default())) } #[test] fn manager_consume_call_response_forwards_to_subscriber_with_pipeline_data() -> Result<(), ShellError> { let mut manager = TestCase::new().plugin("test"); set_default_protocol_info(&mut manager)?; let rx = fake_plugin_call(&mut manager, 0); manager.consume(PluginOutput::CallResponse( 0, PluginCallResponse::PipelineData(PipelineDataHeader::list_stream(ListStreamInfo::new( 0, Span::test_data(), ))), ))?; for i in 0..2 { manager.consume(PluginOutput::Data(0, Value::test_int(i).into()))?; } manager.consume(PluginOutput::End(0))?; // Make sure the streams end and we don't deadlock drop(manager); let message = rx .try_recv() .expect("failed to get plugin call response message"); match message { ReceivedPluginCallMessage::Response(response) => match response { PluginCallResponse::PipelineData(data) => { // Ensure we manage to receive the stream messages assert_eq!(2, data.into_iter().count()); Ok(()) } _ => panic!("unexpected response: {response:?}"), }, _ => panic!("unexpected response message: {message:?}"), } } #[test] fn manager_consume_call_response_registers_streams() -> Result<(), ShellError> { let mut manager = TestCase::new().plugin("test"); set_default_protocol_info(&mut manager)?; for n in [0, 1] { fake_plugin_call(&mut manager, n); } // Check list streams, byte streams manager.consume(PluginOutput::CallResponse( 0, PluginCallResponse::PipelineData(PipelineDataHeader::list_stream(ListStreamInfo::new( 0, Span::test_data(), ))), ))?; manager.consume(PluginOutput::CallResponse( 1, PluginCallResponse::PipelineData(PipelineDataHeader::byte_stream(ByteStreamInfo::new( 1, Span::test_data(), ByteStreamType::Unknown, ))), ))?; // ListStream should have one if let Some(sub) = manager.plugin_call_states.get(&0) { assert_eq!( 1, sub.remaining_streams_to_read, "ListStream remaining_streams_to_read should be 1" ); } else { panic!("failed to find subscription for ListStream (0), maybe it was removed"); } assert_eq!( Some(&0), manager.plugin_call_input_streams.get(&0), "plugin_call_input_streams[0] should be Some(0)" ); // ByteStream should have one if let Some(sub) = manager.plugin_call_states.get(&1) { assert_eq!( 1, sub.remaining_streams_to_read, "ByteStream remaining_streams_to_read should be 1" ); } else { panic!("failed to find subscription for ByteStream (1), maybe it was removed"); } assert_eq!( Some(&1), manager.plugin_call_input_streams.get(&1), "plugin_call_input_streams[1] should be Some(1)" ); Ok(()) } #[test] fn manager_consume_engine_call_forwards_to_subscriber_with_pipeline_data() -> Result<(), ShellError> { let mut manager = TestCase::new().plugin("test"); set_default_protocol_info(&mut manager)?; let rx = fake_plugin_call(&mut manager, 37); manager.consume(PluginOutput::EngineCall { context: 37, id: 46, call: EngineCall::EvalClosure { closure: Spanned { item: Closure { block_id: BlockId::new(0), captures: vec![], }, span: Span::test_data(), }, positional: vec![], input: PipelineDataHeader::list_stream(ListStreamInfo::new(2, Span::test_data())), redirect_stdout: false, redirect_stderr: false, }, })?; for i in 0..2 { manager.consume(PluginOutput::Data(2, Value::test_int(i).into()))?; } manager.consume(PluginOutput::End(2))?; // Make sure the streams end and we don't deadlock drop(manager); let message = rx.try_recv().expect("failed to get plugin call message"); match message { ReceivedPluginCallMessage::EngineCall(id, call) => { assert_eq!(46, id, "id"); match call { EngineCall::EvalClosure { input, .. } => { // Count the stream messages assert_eq!(2, input.into_iter().count()); Ok(()) } _ => panic!("unexpected call: {call:?}"), } } _ => panic!("unexpected response message: {message:?}"), } } #[test] fn manager_handle_engine_call_after_response_received() -> Result<(), ShellError> { let test = TestCase::new(); let mut manager = test.plugin("test"); set_default_protocol_info(&mut manager)?; let (context_tx, context_rx) = mpsc::channel(); // Set up a situation identical to what we would find if the response had been read, but there // was still a stream being processed. We have nowhere to send the engine call in that case, // so the manager has to create a place to handle it. manager.plugin_call_states.insert( 0, PluginCallState { sender: None, dont_send_response: false, signals: Signals::empty(), context_rx: Some(context_rx), span: None, keep_plugin_custom_values: mpsc::channel(), remaining_streams_to_read: 1, }, ); // The engine will get the context from the channel let bogus = Context(Box::new(PluginExecutionBogusContext)); context_tx.send(bogus).expect("failed to send"); manager.send_engine_call(0, 0, EngineCall::GetConfig)?; // Not really much choice but to wait here, as the thread will have been spawned in the // background; we don't have a way to know if it's executed let mut waited = 0; while !test.has_unconsumed_write() { if waited > 100 { panic!("nothing written before timeout, expected engine call response"); } else { std::thread::sleep(Duration::from_millis(1)); waited += 1; } } // The GetConfig call on bogus should result in an error response being written match test.next_written().expect("nothing written") { PluginInput::EngineCallResponse(id, resp) => { assert_eq!(0, id, "id"); match resp { EngineCallResponse::Error(err) => { assert!(err.to_string().contains("bogus"), "wrong error: {err}"); } _ => panic!("unexpected engine call response, expected error: {resp:?}"), } } other => panic!("unexpected message, not engine call response: {other:?}"), } // Whatever was used to make this happen should have been held onto, since spawning a thread // is expensive let sender = &manager .plugin_call_states .get(&0) .expect("missing subscription 0") .sender; assert!( sender.is_some(), "failed to keep spawned engine call handler channel" ); Ok(()) } #[test] fn manager_send_plugin_call_response_removes_context_only_if_no_streams_to_read() -> Result<(), ShellError> { let mut manager = TestCase::new().plugin("test"); for n in [0, 1] { manager.plugin_call_states.insert( n, PluginCallState { sender: None, dont_send_response: false, signals: Signals::empty(), context_rx: None, span: None, keep_plugin_custom_values: mpsc::channel(), remaining_streams_to_read: n as i32, }, ); } for n in [0, 1] { manager.send_plugin_call_response(n, PluginCallResponse::Signature(vec![]))?; } // 0 should not still be present, but 1 should be assert!( !manager.plugin_call_states.contains_key(&0), "didn't clean up when there weren't remaining streams" ); assert!( manager.plugin_call_states.contains_key(&1), "clean up even though there were remaining streams" ); Ok(()) } #[test] fn manager_consume_stream_end_removes_context_only_if_last_stream() -> Result<(), ShellError> { let mut manager = TestCase::new().plugin("test"); set_default_protocol_info(&mut manager)?; for n in [1, 2] { manager.plugin_call_states.insert( n, PluginCallState { sender: None, dont_send_response: false, signals: Signals::empty(), context_rx: None, span: None, keep_plugin_custom_values: mpsc::channel(), remaining_streams_to_read: n as i32, }, ); } // 1 owns [10], 2 owns [21, 22] manager.plugin_call_input_streams.insert(10, 1); manager.plugin_call_input_streams.insert(21, 2); manager.plugin_call_input_streams.insert(22, 2); // Register the streams so we don't have errors let streams: Vec<_> = [10, 21, 22] .into_iter() .map(|id| { let interface = manager.get_interface(); manager .stream_manager .get_handle() .read_stream::<Value, _>(id, interface) }) .collect(); // Ending 10 should cause 1 to be removed manager.consume(StreamMessage::End(10).into())?; assert!( !manager.plugin_call_states.contains_key(&1), "contains(1) after End(10)" ); // Ending 21 should not cause 2 to be removed manager.consume(StreamMessage::End(21).into())?; assert!( manager.plugin_call_states.contains_key(&2), "!contains(2) after End(21)" ); // Ending 22 should cause 2 to be removed manager.consume(StreamMessage::End(22).into())?; assert!( !manager.plugin_call_states.contains_key(&2), "contains(2) after End(22)" ); drop(streams); Ok(()) } #[test] fn manager_prepare_pipeline_data_adds_source_to_values() -> Result<(), ShellError> { let manager = TestCase::new().plugin("test"); let data = manager.prepare_pipeline_data(PipelineData::value( Value::test_custom_value(Box::new(test_plugin_custom_value())), None, ))?; let value = data .into_iter() .next() .expect("prepared pipeline data is empty"); let custom_value: &PluginCustomValueWithSource = value .as_custom_value()? .as_any() .downcast_ref() .expect("{value:?} is not a PluginCustomValueWithSource"); assert_eq!("test", custom_value.source().name()); Ok(()) } #[test] fn manager_prepare_pipeline_data_adds_source_to_list_streams() -> Result<(), ShellError> { let manager = TestCase::new().plugin("test"); let data = manager.prepare_pipeline_data( [Value::test_custom_value(Box::new( test_plugin_custom_value(), ))] .into_pipeline_data(Span::test_data(), Signals::empty()), )?; let value = data .into_iter() .next() .expect("prepared pipeline data is empty"); let custom_value: &PluginCustomValueWithSource = value .as_custom_value()? .as_any() .downcast_ref() .expect("{value:?} is not a PluginCustomValueWithSource"); assert_eq!("test", custom_value.source().name()); Ok(()) } #[test] fn interface_hello_sends_protocol_info() -> Result<(), ShellError> { let test = TestCase::new(); let interface = test.plugin("test").get_interface(); interface.hello()?; let written = test.next_written().expect("nothing written"); match written { PluginInput::Hello(info) => { assert_eq!(ProtocolInfo::default().version, info.version); } _ => panic!("unexpected message written: {written:?}"), } assert!(!test.has_unconsumed_write()); Ok(()) } #[test] fn interface_goodbye() -> Result<(), ShellError> { let test = TestCase::new(); let interface = test.plugin("test").get_interface(); interface.goodbye()?; let written = test.next_written().expect("nothing written"); assert!( matches!(written, PluginInput::Goodbye), "not goodbye: {written:?}" ); assert!(!test.has_unconsumed_write()); Ok(()) } #[test] fn interface_write_plugin_call_registers_subscription() -> Result<(), ShellError> { let mut manager = TestCase::new().plugin("test"); assert!( manager.plugin_call_states.is_empty(), "plugin call subscriptions not empty before start of test" ); let interface = manager.get_interface(); let _ = interface.write_plugin_call(PluginCall::Signature, None)?; manager.receive_plugin_call_subscriptions(); assert!(!manager.plugin_call_states.is_empty(), "not registered"); Ok(()) } #[test] fn interface_write_plugin_call_writes_signature() -> Result<(), ShellError> { let test = TestCase::new(); let manager = test.plugin("test"); let interface = manager.get_interface(); let result = interface.write_plugin_call(PluginCall::Signature, None)?; result.writer.write()?; let written = test.next_written().expect("nothing written"); match written { PluginInput::Call(_, call) => assert!( matches!(call, PluginCall::Signature), "not Signature: {call:?}" ), _ => panic!("unexpected message written: {written:?}"), } Ok(()) } #[test] fn interface_write_plugin_call_writes_custom_value_op() -> Result<(), ShellError> { let test = TestCase::new(); let manager = test.plugin("test"); let interface = manager.get_interface(); let result = interface.write_plugin_call( PluginCall::CustomValueOp( Spanned { item: test_plugin_custom_value(), span: Span::test_data(), }, CustomValueOp::ToBaseValue, ), None, )?; result.writer.write()?; let written = test.next_written().expect("nothing written"); match written { PluginInput::Call(_, call) => assert!( matches!( call, PluginCall::CustomValueOp(_, CustomValueOp::ToBaseValue) ), "expected CustomValueOp(_, ToBaseValue), got {call:?}" ), _ => panic!("unexpected message written: {written:?}"), } Ok(()) } #[test] fn interface_write_plugin_call_writes_run_with_value_input() -> Result<(), ShellError> { let test = TestCase::new(); let manager = test.plugin("test"); let interface = manager.get_interface(); let metadata0 = PipelineMetadata { content_type: Some("baz".into()), ..Default::default() }; let result = interface.write_plugin_call( PluginCall::Run(CallInfo { name: "foo".into(), call: EvaluatedCall { head: Span::test_data(), positional: vec![], named: vec![], }, input: PipelineData::value(Value::test_int(-1), Some(metadata0.clone())), }), None, )?; result.writer.write()?; let written = test.next_written().expect("nothing written"); match written { PluginInput::Call(_, call) => match call { PluginCall::Run(CallInfo { name, input, .. }) => { assert_eq!("foo", name); match input { PipelineDataHeader::Value(value, metadata) => { assert_eq!(-1, value.as_int()?); assert_eq!(metadata0, metadata.expect("there should be metadata")); } _ => panic!("unexpected input header: {input:?}"), } } _ => panic!("unexpected Call: {call:?}"), }, _ => panic!("unexpected message written: {written:?}"), } Ok(()) } #[test] fn interface_write_plugin_call_writes_run_with_stream_input() -> Result<(), ShellError> { let test = TestCase::new(); let manager = test.plugin("test"); let interface = manager.get_interface(); let values = vec![Value::test_int(1), Value::test_int(2)]; let result = interface.write_plugin_call( PluginCall::Run(CallInfo { name: "foo".into(), call: EvaluatedCall { head: Span::test_data(), positional: vec![], named: vec![], }, input: values .clone() .into_pipeline_data(Span::test_data(), Signals::empty()), }), None, )?; result.writer.write()?; let written = test.next_written().expect("nothing written"); let info = match written { PluginInput::Call(_, call) => match call { PluginCall::Run(CallInfo { name, input, .. }) => { assert_eq!("foo", name); match input { PipelineDataHeader::ListStream(info) => info, _ => panic!("unexpected input header: {input:?}"), } } _ => panic!("unexpected Call: {call:?}"), }, _ => panic!("unexpected message written: {written:?}"), }; // Expect stream messages for value in values { match test .next_written() .expect("failed to get Data stream message") { PluginInput::Data(id, data) => { assert_eq!(info.id, id, "id"); match data { StreamData::List(data_value) => { assert_eq!(value, data_value, "wrong value in Data message"); } _ => panic!("not List stream data: {data:?}"), } } message => panic!("expected Stream(Data(..)) message: {message:?}"), } } match test .next_written() .expect("failed to get End stream message") { PluginInput::End(id) => { assert_eq!(info.id, id, "id"); } message => panic!("expected End(_) message: {message:?}"), } Ok(()) } #[test] fn interface_receive_plugin_call_receives_response() -> Result<(), ShellError> { let interface = TestCase::new().plugin("test").get_interface(); // Set up a fake channel that has the response in it let (tx, rx) = mpsc::channel(); tx.send(ReceivedPluginCallMessage::Response( PluginCallResponse::Signature(vec![]), )) .expect("failed to send on new channel"); drop(tx); // so we don't deadlock on recv() let response = interface.receive_plugin_call_response(rx, None, CurrentCallState::default())?; assert!( matches!(response, PluginCallResponse::Signature(_)), "wrong response: {response:?}" ); Ok(()) } #[test] fn interface_receive_plugin_call_receives_error() -> Result<(), ShellError> { let interface = TestCase::new().plugin("test").get_interface(); // Set up a fake channel that has the error in it let (tx, rx) = mpsc::channel(); tx.send(ReceivedPluginCallMessage::Error( ShellError::ExternalNotSupported { span: Span::test_data(), }, )) .expect("failed to send on new channel"); drop(tx); // so we don't deadlock on recv() let error = interface .receive_plugin_call_response(rx, None, CurrentCallState::default()) .expect_err("did not receive error"); assert!( matches!(error, ShellError::ExternalNotSupported { .. }), "wrong error: {error:?}" ); Ok(()) } #[test] fn interface_receive_plugin_call_handles_engine_call() -> Result<(), ShellError> { let test = TestCase::new(); let interface = test.plugin("test").get_interface(); // Set up a fake channel just for the engine call let (tx, rx) = mpsc::channel(); tx.send(ReceivedPluginCallMessage::EngineCall( 0, EngineCall::GetConfig, )) .expect("failed to send on new channel"); // The context should be a bogus context, which will return an error for GetConfig let mut context = PluginExecutionBogusContext; // We don't actually send a response, so `receive_plugin_call_response` should actually return // an error, but it should still do the engine call drop(tx); interface .receive_plugin_call_response(rx, Some(&mut context), CurrentCallState::default()) .expect_err("no error even though there was no response"); // Check for the engine call response output match test .next_written() .expect("no engine call response written") { PluginInput::EngineCallResponse(id, resp) => { assert_eq!(0, id, "id"); match resp { EngineCallResponse::Error(err) => { assert!(err.to_string().contains("bogus"), "wrong error: {err}"); } _ => panic!("unexpected engine call response, maybe bogus is wrong: {resp:?}"), } } other => panic!("unexpected message: {other:?}"), } assert!(!test.has_unconsumed_write()); Ok(()) } /// Fake responses to requests for plugin call messages fn start_fake_plugin_call_responder( manager: PluginInterfaceManager, take: usize, mut f: impl FnMut(PluginCallId) -> Vec<ReceivedPluginCallMessage> + Send + 'static, ) { std::thread::Builder::new() .name("fake plugin call responder".into()) .spawn(move || { for (id, state) in manager .plugin_call_subscription_receiver .into_iter() .take(take) { for message in f(id) { state .sender .as_ref() .expect("sender was not set") .send(message) .expect("failed to send"); } } }) .expect("failed to spawn thread"); } #[test] fn interface_get_metadata() -> Result<(), ShellError> { let test = TestCase::new(); let manager = test.plugin("test"); let interface = manager.get_interface(); start_fake_plugin_call_responder(manager, 1, |_| { vec![ReceivedPluginCallMessage::Response( PluginCallResponse::Metadata(PluginMetadata::new().with_version("test")), )] }); let metadata = interface.get_metadata()?; assert_eq!(Some("test"), metadata.version.as_deref()); assert!(test.has_unconsumed_write()); Ok(()) } #[test] fn interface_get_signature() -> Result<(), ShellError> { let test = TestCase::new(); let manager = test.plugin("test"); let interface = manager.get_interface(); start_fake_plugin_call_responder(manager, 1, |_| { vec![ReceivedPluginCallMessage::Response( PluginCallResponse::Signature(vec![PluginSignature::build("test")]), )] }); let signatures = interface.get_signature()?; assert_eq!(1, signatures.len()); assert!(test.has_unconsumed_write()); Ok(()) } #[test] fn interface_run() -> Result<(), ShellError> {
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
true
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-engine/src/interface/mod.rs
crates/nu-plugin-engine/src/interface/mod.rs
//! Interface used by the engine to communicate with the plugin. use nu_plugin_core::{ Interface, InterfaceManager, PipelineDataWriter, PluginRead, PluginWrite, StreamManager, StreamManagerHandle, util::{Waitable, WaitableMut, with_custom_values_in}, }; use nu_plugin_protocol::{ CallInfo, CustomValueOp, EngineCall, EngineCallId, EngineCallResponse, EvaluatedCall, GetCompletionInfo, Ordering, PluginCall, PluginCallId, PluginCallResponse, PluginCustomValue, PluginInput, PluginOption, PluginOutput, ProtocolInfo, StreamId, StreamMessage, }; use nu_protocol::{ CustomValue, DynamicSuggestion, IntoSpanned, PipelineData, PluginMetadata, PluginSignature, ShellError, SignalAction, Signals, Span, Spanned, Value, ast::Operator, casing::Casing, engine::Sequence, }; use nu_utils::SharedCow; use std::{ collections::{BTreeMap, btree_map}, path::Path, sync::{Arc, OnceLock, mpsc}, }; use crate::{ PluginCustomValueWithSource, PluginExecutionContext, PluginGc, PluginSource, process::PluginProcess, }; #[cfg(test)] mod tests; #[derive(Debug)] enum ReceivedPluginCallMessage { /// The final response to send Response(PluginCallResponse<PipelineData>), /// An critical error with the interface Error(ShellError), /// An engine call that should be evaluated and responded to, but is not the final response /// /// We send this back to the thread that made the plugin call so we don't block the reader /// thread EngineCall(EngineCallId, EngineCall<PipelineData>), } /// Context for plugin call execution pub(crate) struct Context(Box<dyn PluginExecutionContext>); impl std::fmt::Debug for Context { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("Context") } } impl std::ops::Deref for Context { type Target = dyn PluginExecutionContext; fn deref(&self) -> &Self::Target { &*self.0 } } /// Internal shared state between the manager and each interface. struct PluginInterfaceState { /// The source to be used for custom values coming from / going to the plugin source: Arc<PluginSource>, /// The plugin process being managed process: Option<PluginProcess>, /// Protocol version info, set after `Hello` received protocol_info: Waitable<Arc<ProtocolInfo>>, /// Sequence for generating plugin call ids plugin_call_id_sequence: Sequence, /// Sequence for generating stream ids stream_id_sequence: Sequence, /// Sender to subscribe to a plugin call response plugin_call_subscription_sender: mpsc::Sender<(PluginCallId, PluginCallState)>, /// An error that should be propagated to further plugin calls error: OnceLock<ShellError>, /// The synchronized output writer writer: Box<dyn PluginWrite<PluginInput>>, } impl std::fmt::Debug for PluginInterfaceState { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("PluginInterfaceState") .field("source", &self.source) .field("protocol_info", &self.protocol_info) .field("plugin_call_id_sequence", &self.plugin_call_id_sequence) .field("stream_id_sequence", &self.stream_id_sequence) .field( "plugin_call_subscription_sender", &self.plugin_call_subscription_sender, ) .field("error", &self.error) .finish_non_exhaustive() } } /// State that the manager keeps for each plugin call during its lifetime. #[derive(Debug)] struct PluginCallState { /// The sender back to the thread that is waiting for the plugin call response sender: Option<mpsc::Sender<ReceivedPluginCallMessage>>, /// Don't try to send the plugin call response. This is only used for `Dropped` to avoid an /// error dont_send_response: bool, /// Signals to be used for stream iterators signals: Signals, /// Channel to receive context on to be used if needed context_rx: Option<mpsc::Receiver<Context>>, /// Span associated with the call, if any span: Option<Span>, /// Channel for plugin custom values that should be kept alive for the duration of the plugin /// call. The plugin custom values on this channel are never read, we just hold on to it to keep /// them in memory so they can be dropped at the end of the call. We hold the sender as well so /// we can generate the CurrentCallState. keep_plugin_custom_values: ( mpsc::Sender<PluginCustomValueWithSource>, mpsc::Receiver<PluginCustomValueWithSource>, ), /// Number of streams that still need to be read from the plugin call response remaining_streams_to_read: i32, } impl Drop for PluginCallState { fn drop(&mut self) { // Clear the keep custom values channel, so drop notifications can be sent for value in self.keep_plugin_custom_values.1.try_iter() { log::trace!("Dropping custom value that was kept: {value:?}"); drop(value); } } } /// Manages reading and dispatching messages for [`PluginInterface`]s. #[derive(Debug)] pub struct PluginInterfaceManager { /// Shared state state: Arc<PluginInterfaceState>, /// The writer for protocol info protocol_info_mut: WaitableMut<Arc<ProtocolInfo>>, /// Manages stream messages and state stream_manager: StreamManager, /// State related to plugin calls plugin_call_states: BTreeMap<PluginCallId, PluginCallState>, /// Receiver for plugin call subscriptions plugin_call_subscription_receiver: mpsc::Receiver<(PluginCallId, PluginCallState)>, /// Tracker for which plugin call streams being read belong to /// /// This is necessary so we know when we can remove context for plugin calls plugin_call_input_streams: BTreeMap<StreamId, PluginCallId>, /// Garbage collector handle, to notify about the state of the plugin gc: Option<PluginGc>, } impl PluginInterfaceManager { pub fn new( source: Arc<PluginSource>, pid: Option<u32>, writer: impl PluginWrite<PluginInput> + 'static, ) -> PluginInterfaceManager { let (subscription_tx, subscription_rx) = mpsc::channel(); let protocol_info_mut = WaitableMut::new(); PluginInterfaceManager { state: Arc::new(PluginInterfaceState { source, process: pid.map(PluginProcess::new), protocol_info: protocol_info_mut.reader(), plugin_call_id_sequence: Sequence::default(), stream_id_sequence: Sequence::default(), plugin_call_subscription_sender: subscription_tx, error: OnceLock::new(), writer: Box::new(writer), }), protocol_info_mut, stream_manager: StreamManager::new(), plugin_call_states: BTreeMap::new(), plugin_call_subscription_receiver: subscription_rx, plugin_call_input_streams: BTreeMap::new(), gc: None, } } /// Add a garbage collector to this plugin. The manager will notify the garbage collector about /// the state of the plugin so that it can be automatically cleaned up if the plugin is /// inactive. pub fn set_garbage_collector(&mut self, gc: Option<PluginGc>) { self.gc = gc; } /// Consume pending messages in the `plugin_call_subscription_receiver` fn receive_plugin_call_subscriptions(&mut self) { while let Ok((id, state)) = self.plugin_call_subscription_receiver.try_recv() { if let btree_map::Entry::Vacant(e) = self.plugin_call_states.entry(id) { e.insert(state); } else { log::warn!("Duplicate plugin call ID ignored: {id}"); } } } /// Track the start of incoming stream(s) fn recv_stream_started(&mut self, call_id: PluginCallId, stream_id: StreamId) { self.plugin_call_input_streams.insert(stream_id, call_id); // Increment the number of streams on the subscription so context stays alive self.receive_plugin_call_subscriptions(); if let Some(state) = self.plugin_call_states.get_mut(&call_id) { state.remaining_streams_to_read += 1; } // Add a lock to the garbage collector for each stream if let Some(ref gc) = self.gc { gc.increment_locks(1); } } /// Track the end of an incoming stream fn recv_stream_ended(&mut self, stream_id: StreamId) { if let Some(call_id) = self.plugin_call_input_streams.remove(&stream_id) { if let btree_map::Entry::Occupied(mut e) = self.plugin_call_states.entry(call_id) { e.get_mut().remaining_streams_to_read -= 1; // Remove the subscription if there are no more streams to be read. if e.get().remaining_streams_to_read <= 0 { e.remove(); } } // Streams read from the plugin are tracked with locks on the GC so plugins don't get // stopped if they have active streams if let Some(ref gc) = self.gc { gc.decrement_locks(1); } } } /// Find the [`Signals`] struct corresponding to the given plugin call id fn get_signals(&mut self, id: PluginCallId) -> Result<Signals, ShellError> { // Make sure we're up to date self.receive_plugin_call_subscriptions(); // Find the subscription and return the context self.plugin_call_states .get(&id) .map(|state| state.signals.clone()) .ok_or_else(|| ShellError::PluginFailedToDecode { msg: format!("Unknown plugin call ID: {id}"), }) } /// Send a [`PluginCallResponse`] to the appropriate sender fn send_plugin_call_response( &mut self, id: PluginCallId, response: PluginCallResponse<PipelineData>, ) -> Result<(), ShellError> { // Ensure we're caught up on the subscriptions made self.receive_plugin_call_subscriptions(); if let btree_map::Entry::Occupied(mut e) = self.plugin_call_states.entry(id) { // Remove the subscription sender, since this will be the last message. // // We can spawn a new one if we need it for engine calls. if !e.get().dont_send_response && e.get_mut() .sender .take() .and_then(|s| s.send(ReceivedPluginCallMessage::Response(response)).ok()) .is_none() { log::warn!("Received a plugin call response for id={id}, but the caller hung up"); } // If there are no registered streams, just remove it if e.get().remaining_streams_to_read <= 0 { e.remove(); } Ok(()) } else { Err(ShellError::PluginFailedToDecode { msg: format!("Unknown plugin call ID: {id}"), }) } } /// Spawn a handler for engine calls for a plugin, in case we need to handle engine calls /// after the response has already been received (in which case we have nowhere to send them) fn spawn_engine_call_handler( &mut self, id: PluginCallId, ) -> Result<&mpsc::Sender<ReceivedPluginCallMessage>, ShellError> { let interface = self.get_interface(); if let Some(state) = self.plugin_call_states.get_mut(&id) { if state.sender.is_none() { let (tx, rx) = mpsc::channel(); let context_rx = state .context_rx .take() .ok_or_else(|| ShellError::NushellFailed { msg: "Tried to spawn the fallback engine call handler more than once" .into(), })?; // Generate the state needed to handle engine calls let mut current_call_state = CurrentCallState { context_tx: None, keep_plugin_custom_values_tx: Some(state.keep_plugin_custom_values.0.clone()), entered_foreground: false, span: state.span, }; let handler = move || { // We receive on the thread so that we don't block the reader thread let mut context = context_rx .recv() .ok() // The plugin call won't send context if it's not required. .map(|c| c.0); for msg in rx { // This thread only handles engine calls. match msg { ReceivedPluginCallMessage::EngineCall(engine_call_id, engine_call) => { if let Err(err) = interface.handle_engine_call( engine_call_id, engine_call, &mut current_call_state, context.as_deref_mut(), ) { log::warn!( "Error in plugin post-response engine call handler: \ {err:?}" ); return; } } other => log::warn!( "Bad message received in plugin post-response \ engine call handler: {other:?}" ), } } }; std::thread::Builder::new() .name("plugin engine call handler".into()) .spawn(handler) .expect("failed to spawn thread"); state.sender = Some(tx); Ok(state.sender.as_ref().unwrap_or_else(|| unreachable!())) } else { Err(ShellError::NushellFailed { msg: "Tried to spawn the fallback engine call handler before the plugin call \ response had been received" .into(), }) } } else { Err(ShellError::NushellFailed { msg: format!("Couldn't find plugin ID={id} in subscriptions"), }) } } /// Send an [`EngineCall`] to the appropriate sender fn send_engine_call( &mut self, plugin_call_id: PluginCallId, engine_call_id: EngineCallId, call: EngineCall<PipelineData>, ) -> Result<(), ShellError> { // Ensure we're caught up on the subscriptions made self.receive_plugin_call_subscriptions(); // Don't remove the sender, as there could be more calls or responses if let Some(subscription) = self.plugin_call_states.get(&plugin_call_id) { let msg = ReceivedPluginCallMessage::EngineCall(engine_call_id, call); // Call if there's an error sending the engine call let send_error = |this: &Self| { log::warn!( "Received an engine call for plugin_call_id={plugin_call_id}, \ but the caller hung up" ); // We really have no choice here but to send the response ourselves and hope we // don't block this.state.writer.write(&PluginInput::EngineCallResponse( engine_call_id, EngineCallResponse::Error(ShellError::GenericError { error: "Caller hung up".to_string(), msg: "Can't make engine call because the original caller hung up" .to_string(), span: None, help: None, inner: vec![], }), ))?; this.state.writer.flush() }; // Try to send to the sender if it exists if let Some(sender) = subscription.sender.as_ref() { sender.send(msg).or_else(|_| send_error(self)) } else { // The sender no longer exists. Spawn a specific one just for engine calls let sender = self.spawn_engine_call_handler(plugin_call_id)?; sender.send(msg).or_else(|_| send_error(self)) } } else { Err(ShellError::PluginFailedToDecode { msg: format!("Unknown plugin call ID: {plugin_call_id}"), }) } } /// True if there are no other copies of the state (which would mean there are no interfaces /// and no stream readers/writers) pub fn is_finished(&self) -> bool { Arc::strong_count(&self.state) < 2 } /// Loop on input from the given reader as long as `is_finished()` is false /// /// Any errors will be propagated to all read streams automatically. pub fn consume_all( &mut self, mut reader: impl PluginRead<PluginOutput>, ) -> Result<(), ShellError> { let mut result = Ok(()); while let Some(msg) = reader.read().transpose() { if self.is_finished() { break; } // We assume an error here is unrecoverable (at least, without restarting the plugin) if let Err(err) = msg.and_then(|msg| self.consume(msg)) { // Put the error in the state so that new calls see it let _ = self.state.error.set(err.clone()); // Error to streams let _ = self.stream_manager.broadcast_read_error(err.clone()); // Error to call waiters self.receive_plugin_call_subscriptions(); for subscription in std::mem::take(&mut self.plugin_call_states).into_values() { let _ = subscription .sender .as_ref() .map(|s| s.send(ReceivedPluginCallMessage::Error(err.clone()))); } result = Err(err); break; } } // Tell the GC we are exiting so that the plugin doesn't get stuck open if let Some(ref gc) = self.gc { gc.exited(); } result } } impl InterfaceManager for PluginInterfaceManager { type Interface = PluginInterface; type Input = PluginOutput; fn get_interface(&self) -> Self::Interface { PluginInterface { state: self.state.clone(), stream_manager_handle: self.stream_manager.get_handle(), gc: self.gc.clone(), } } fn consume(&mut self, input: Self::Input) -> Result<(), ShellError> { log::trace!("from plugin: {input:?}"); match input { PluginOutput::Hello(info) => { let info = Arc::new(info); self.protocol_info_mut.set(info.clone())?; let local_info = ProtocolInfo::default(); if local_info.is_compatible_with(&info)? { Ok(()) } else { Err(ShellError::PluginFailedToLoad { msg: format!( "Plugin `{}` is compiled for nushell version {}, \ which is not compatible with version {}", self.state.source.name(), info.version, local_info.version, ), }) } } _ if !self.state.protocol_info.is_set() => { // Must send protocol info first Err(ShellError::PluginFailedToLoad { msg: format!( "Failed to receive initial Hello message from `{}`. \ This plugin might be too old", self.state.source.name() ), }) } // Stream messages PluginOutput::Data(..) | PluginOutput::End(..) | PluginOutput::Drop(..) | PluginOutput::Ack(..) => { self.consume_stream_message(input.try_into().map_err(|msg| { ShellError::NushellFailed { msg: format!("Failed to convert message {msg:?} to StreamMessage"), } })?) } PluginOutput::Option(option) => match option { PluginOption::GcDisabled(disabled) => { // Turn garbage collection off/on. if let Some(ref gc) = self.gc { gc.set_disabled(disabled); } Ok(()) } }, PluginOutput::CallResponse(id, response) => { // Handle reading the pipeline data, if any let response = response .map_data(|data| { let signals = self.get_signals(id)?; // Register the stream in the response if let Some(stream_id) = data.stream_id() { self.recv_stream_started(id, stream_id); } self.read_pipeline_data(data, &signals) }) .unwrap_or_else(|err| { // If there's an error with initializing this stream, change it to a plugin // error response, but send it anyway PluginCallResponse::Error(err) }); let result = self.send_plugin_call_response(id, response); if result.is_ok() { // When a call ends, it releases a lock on the GC if let Some(ref gc) = self.gc { gc.decrement_locks(1); } } result } PluginOutput::EngineCall { context, id, call } => { let call = call // Handle reading the pipeline data, if any .map_data(|input| { let signals = self.get_signals(context)?; self.read_pipeline_data(input, &signals) }) // Do anything extra needed for each engine call setup .and_then(|mut engine_call| { match engine_call { EngineCall::EvalClosure { ref mut positional, .. } => { for arg in positional.iter_mut() { // Add source to any plugin custom values in the arguments PluginCustomValueWithSource::add_source_in( arg, &self.state.source, )?; } Ok(engine_call) } _ => Ok(engine_call), } }); match call { Ok(call) => self.send_engine_call(context, id, call), // If there was an error with setting up the call, just write the error Err(err) => self.get_interface().write_engine_call_response( id, EngineCallResponse::Error(err), &CurrentCallState::default(), ), } } } } fn stream_manager(&self) -> &StreamManager { &self.stream_manager } fn prepare_pipeline_data(&self, mut data: PipelineData) -> Result<PipelineData, ShellError> { // Add source to any values match data { PipelineData::Value(ref mut value, _) => { with_custom_values_in(value, |custom_value| { PluginCustomValueWithSource::add_source(custom_value.item, &self.state.source); Ok::<_, ShellError>(()) })?; Ok(data) } PipelineData::ListStream(stream, meta) => { let source = self.state.source.clone(); Ok(PipelineData::list_stream( stream.map(move |mut value| { let _ = PluginCustomValueWithSource::add_source_in(&mut value, &source); value }), meta, )) } PipelineData::Empty | PipelineData::ByteStream(..) => Ok(data), } } fn consume_stream_message(&mut self, message: StreamMessage) -> Result<(), ShellError> { // Keep track of streams that end if let StreamMessage::End(id) = message { self.recv_stream_ended(id); } self.stream_manager.handle_message(message) } } /// A reference through which a plugin can be interacted with during execution. /// /// This is not a public API. #[derive(Debug, Clone)] #[doc(hidden)] pub struct PluginInterface { /// Shared state state: Arc<PluginInterfaceState>, /// Handle to stream manager stream_manager_handle: StreamManagerHandle, /// Handle to plugin garbage collector gc: Option<PluginGc>, } impl PluginInterface { /// Get the process ID for the plugin, if known. pub fn pid(&self) -> Option<u32> { self.state.process.as_ref().map(|p| p.pid()) } /// Get the protocol info for the plugin. Will block to receive `Hello` if not received yet. pub fn protocol_info(&self) -> Result<Arc<ProtocolInfo>, ShellError> { self.state.protocol_info.get().and_then(|info| { info.ok_or_else(|| ShellError::PluginFailedToLoad { msg: format!( "Failed to get protocol info (`Hello` message) from the `{}` plugin", self.state.source.identity.name() ), }) }) } /// Write the protocol info. This should be done after initialization pub fn hello(&self) -> Result<(), ShellError> { self.write(PluginInput::Hello(ProtocolInfo::default()))?; self.flush() } /// Tell the plugin it should not expect any more plugin calls and should terminate after it has /// finished processing the ones it has already received. /// /// Note that this is automatically called when the last existing `PluginInterface` is dropped. /// You probably do not need to call this manually. pub fn goodbye(&self) -> Result<(), ShellError> { self.write(PluginInput::Goodbye)?; self.flush() } /// Send the plugin a signal. pub fn signal(&self, action: SignalAction) -> Result<(), ShellError> { self.write(PluginInput::Signal(action))?; self.flush() } /// Write an [`EngineCallResponse`]. Writes the full stream contained in any [`PipelineData`] /// before returning. pub fn write_engine_call_response( &self, id: EngineCallId, response: EngineCallResponse<PipelineData>, state: &CurrentCallState, ) -> Result<(), ShellError> { // Set up any stream if necessary let mut writer = None; let response = response.map_data(|data| { let (data_header, data_writer) = self.init_write_pipeline_data(data, state)?; writer = Some(data_writer); Ok(data_header) })?; // Write the response, including the pipeline data header if present self.write(PluginInput::EngineCallResponse(id, response))?; self.flush()?; // If we have a stream to write, do it now if let Some(writer) = writer { writer.write_background()?; } Ok(()) } /// Write a plugin call message. Returns the writer for the stream. fn write_plugin_call( &self, mut call: PluginCall<PipelineData>, context: Option<&dyn PluginExecutionContext>, ) -> Result<WritePluginCallResult, ShellError> { let id = self.state.plugin_call_id_sequence.next()?; let signals = context .map(|c| c.signals().clone()) .unwrap_or_else(Signals::empty); let (tx, rx) = mpsc::channel(); let (context_tx, context_rx) = mpsc::channel(); let keep_plugin_custom_values = mpsc::channel(); // Set up the state that will stay alive during the call. let state = CurrentCallState { context_tx: Some(context_tx), keep_plugin_custom_values_tx: Some(keep_plugin_custom_values.0.clone()), entered_foreground: false, span: call.span(), }; // Prepare the call with the state. state.prepare_plugin_call(&mut call, &self.state.source)?; // Convert the call into one with a header and handle the stream, if necessary let (call, writer) = match call { PluginCall::Metadata => (PluginCall::Metadata, Default::default()), PluginCall::Signature => (PluginCall::Signature, Default::default()), PluginCall::CustomValueOp(value, op) => { (PluginCall::CustomValueOp(value, op), Default::default()) } PluginCall::GetCompletion(flag_name) => { (PluginCall::GetCompletion(flag_name), Default::default()) } PluginCall::Run(CallInfo { name, call, input }) => { let (header, writer) = self.init_write_pipeline_data(input, &state)?; ( PluginCall::Run(CallInfo { name, call, input: header, }), writer, ) } }; // Don't try to send a response for a Dropped call. let dont_send_response = matches!(call, PluginCall::CustomValueOp(_, CustomValueOp::Dropped)); // Register the subscription to the response, and the context self.state .plugin_call_subscription_sender .send(( id, PluginCallState { sender: Some(tx).filter(|_| !dont_send_response), dont_send_response, signals, context_rx: Some(context_rx), span: call.span(), keep_plugin_custom_values, remaining_streams_to_read: 0, }, )) .map_err(|_| { let existing_error = self.state.error.get().cloned(); ShellError::GenericError { error: format!("Plugin `{}` closed unexpectedly", self.state.source.name()), msg: "can't complete this operation because the plugin is closed".into(), span: call.span(), help: Some(format!( "the plugin may have experienced an error. Try loading the plugin again \ with `{}`", self.state.source.identity.use_command(), )), inner: existing_error.into_iter().collect(), } })?; // Starting a plugin call adds a lock on the GC. Locks are not added for streams being read // by the plugin, so the plugin would have to explicitly tell us if it expects to stay alive // while reading streams in the background after the response ends. if let Some(ref gc) = self.gc { gc.increment_locks(1); } // Write request self.write(PluginInput::Call(id, call))?; self.flush()?; Ok(WritePluginCallResult { receiver: rx, writer, state, }) } /// Read the channel for plugin call messages and handle them until the response is received. fn receive_plugin_call_response( &self,
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
true
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-engine/src/plugin_custom_value_with_source/tests.rs
crates/nu-plugin-engine/src/plugin_custom_value_with_source/tests.rs
use std::sync::Arc; use nu_plugin_protocol::test_util::{TestCustomValue, test_plugin_custom_value}; use nu_protocol::{ BlockId, CustomValue, IntoSpanned, ShellError, Span, Value, VarId, engine::Closure, record, }; use crate::{ PluginCustomValueWithSource, PluginSource, test_util::test_plugin_custom_value_with_source, }; use super::WithSource; #[test] fn add_source_in_at_root() -> Result<(), ShellError> { let mut val = Value::test_custom_value(Box::new(test_plugin_custom_value())); let source = Arc::new(PluginSource::new_fake("foo")); PluginCustomValueWithSource::add_source_in(&mut val, &source)?; let custom_value = val.as_custom_value()?; let plugin_custom_value: &PluginCustomValueWithSource = custom_value .as_any() .downcast_ref() .expect("not PluginCustomValueWithSource"); assert_eq!( Arc::as_ptr(&source), Arc::as_ptr(&plugin_custom_value.source) ); Ok(()) } fn check_record_custom_values( val: &Value, keys: &[&str], mut f: impl FnMut(&str, &dyn CustomValue) -> Result<(), ShellError>, ) -> Result<(), ShellError> { let record = val.as_record()?; for key in keys { let val = record .get(key) .unwrap_or_else(|| panic!("record does not contain '{key}'")); let custom_value = val .as_custom_value() .unwrap_or_else(|_| panic!("'{key}' not custom value")); f(key, custom_value)?; } Ok(()) } #[test] fn add_source_in_nested_record() -> Result<(), ShellError> { let orig_custom_val = Value::test_custom_value(Box::new(test_plugin_custom_value())); let mut val = Value::test_record(record! { "foo" => orig_custom_val.clone(), "bar" => orig_custom_val.clone(), }); let source = Arc::new(PluginSource::new_fake("foo")); PluginCustomValueWithSource::add_source_in(&mut val, &source)?; check_record_custom_values(&val, &["foo", "bar"], |key, custom_value| { let plugin_custom_value: &PluginCustomValueWithSource = custom_value .as_any() .downcast_ref() .unwrap_or_else(|| panic!("'{key}' not PluginCustomValueWithSource")); assert_eq!( Arc::as_ptr(&source), Arc::as_ptr(&plugin_custom_value.source), "'{key}' source not set correctly" ); Ok(()) }) } fn check_list_custom_values( val: &Value, indices: impl IntoIterator<Item = usize>, mut f: impl FnMut(usize, &dyn CustomValue) -> Result<(), ShellError>, ) -> Result<(), ShellError> { let list = val.as_list()?; for index in indices { let val = list .get(index) .unwrap_or_else(|| panic!("[{index}] not present in list")); let custom_value = val .as_custom_value() .unwrap_or_else(|_| panic!("[{index}] not custom value")); f(index, custom_value)?; } Ok(()) } #[test] fn add_source_in_nested_list() -> Result<(), ShellError> { let orig_custom_val = Value::test_custom_value(Box::new(test_plugin_custom_value())); let mut val = Value::test_list(vec![orig_custom_val.clone(), orig_custom_val.clone()]); let source = Arc::new(PluginSource::new_fake("foo")); PluginCustomValueWithSource::add_source_in(&mut val, &source)?; check_list_custom_values(&val, 0..=1, |index, custom_value| { let plugin_custom_value: &PluginCustomValueWithSource = custom_value .as_any() .downcast_ref() .unwrap_or_else(|| panic!("[{index}] not PluginCustomValueWithSource")); assert_eq!( Arc::as_ptr(&source), Arc::as_ptr(&plugin_custom_value.source), "[{index}] source not set correctly" ); Ok(()) }) } fn check_closure_custom_values( val: &Value, indices: impl IntoIterator<Item = usize>, mut f: impl FnMut(usize, &dyn CustomValue) -> Result<(), ShellError>, ) -> Result<(), ShellError> { let closure = val.as_closure()?; for index in indices { let val = closure .captures .get(index) .unwrap_or_else(|| panic!("[{index}] not present in closure")); let custom_value = val .1 .as_custom_value() .unwrap_or_else(|_| panic!("[{index}] not custom value")); f(index, custom_value)?; } Ok(()) } #[test] fn add_source_in_nested_closure() -> Result<(), ShellError> { let orig_custom_val = Value::test_custom_value(Box::new(test_plugin_custom_value())); let mut val = Value::test_closure(Closure { block_id: BlockId::new(0), captures: vec![ (VarId::new(0), orig_custom_val.clone()), (VarId::new(1), orig_custom_val.clone()), ], }); let source = Arc::new(PluginSource::new_fake("foo")); PluginCustomValueWithSource::add_source_in(&mut val, &source)?; check_closure_custom_values(&val, 0..=1, |index, custom_value| { let plugin_custom_value: &PluginCustomValueWithSource = custom_value .as_any() .downcast_ref() .unwrap_or_else(|| panic!("[{index}] not PluginCustomValueWithSource")); assert_eq!( Arc::as_ptr(&source), Arc::as_ptr(&plugin_custom_value.source), "[{index}] source not set correctly" ); Ok(()) }) } #[test] fn verify_source_error_message() -> Result<(), ShellError> { let span = Span::new(5, 7); let ok_val = test_plugin_custom_value_with_source(); let native_val = TestCustomValue(32); let foreign_val = test_plugin_custom_value().with_source(Arc::new(PluginSource::new_fake("other"))); let source = PluginSource::new_fake("test"); PluginCustomValueWithSource::verify_source_of_custom_value( (&ok_val as &dyn CustomValue).into_spanned(span), &source, ) .expect("ok_val should be verified ok"); for (val, src_plugin) in [ (&native_val as &dyn CustomValue, None), (&foreign_val as &dyn CustomValue, Some("other")), ] { let error = PluginCustomValueWithSource::verify_source_of_custom_value( val.into_spanned(span), &source, ) .expect_err(&format!( "a custom value from {src_plugin:?} should result in an error" )); if let ShellError::CustomValueIncorrectForPlugin { name, span: err_span, dest_plugin, src_plugin: err_src_plugin, } = error { assert_eq!("TestCustomValue", name, "error.name from {src_plugin:?}"); assert_eq!(span, err_span, "error.span from {src_plugin:?}"); assert_eq!("test", dest_plugin, "error.dest_plugin from {src_plugin:?}"); assert_eq!(src_plugin, err_src_plugin.as_deref(), "error.src_plugin"); } else { panic!("the error returned should be CustomValueIncorrectForPlugin"); } } Ok(()) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-engine/src/plugin_custom_value_with_source/mod.rs
crates/nu-plugin-engine/src/plugin_custom_value_with_source/mod.rs
use std::{cmp::Ordering, path::Path, sync::Arc}; use nu_plugin_core::util::with_custom_values_in; use nu_plugin_protocol::PluginCustomValue; use nu_protocol::{ CustomValue, IntoSpanned, ShellError, Span, Spanned, Value, ast::Operator, casing::Casing, }; use serde::Serialize; use crate::{PluginInterface, PluginSource}; #[cfg(test)] mod tests; /// Wraps a [`PluginCustomValue`] together with its [`PluginSource`], so that the [`CustomValue`] /// methods can be implemented by calling the plugin, and to ensure that any custom values sent to a /// plugin came from it originally. #[derive(Debug, Clone)] pub struct PluginCustomValueWithSource { inner: PluginCustomValue, /// Which plugin the custom value came from. This is not sent over the serialization boundary. source: Arc<PluginSource>, } impl PluginCustomValueWithSource { /// Wrap a [`PluginCustomValue`] together with its source. pub fn new(inner: PluginCustomValue, source: Arc<PluginSource>) -> PluginCustomValueWithSource { PluginCustomValueWithSource { inner, source } } /// Create a [`Value`] containing this custom value. pub fn into_value(self, span: Span) -> Value { Value::custom(Box::new(self), span) } /// Which plugin the custom value came from. This provides a direct reference to be able to get /// a plugin interface in order to make a call, when needed. pub fn source(&self) -> &Arc<PluginSource> { &self.source } /// Unwrap the [`PluginCustomValueWithSource`], discarding the source. pub fn without_source(self) -> PluginCustomValue { // Because of the `Drop` implementation, we can't destructure this. self.inner.clone() } /// Helper to get the plugin to implement an op fn get_plugin(&self, span: Option<Span>, for_op: &str) -> Result<PluginInterface, ShellError> { let wrap_err = |err: ShellError| ShellError::GenericError { error: format!( "Unable to spawn plugin `{}` to {for_op}", self.source.name() ), msg: err.to_string(), span, help: None, inner: vec![err], }; self.source .clone() .persistent(span) .and_then(|p| p.get_plugin(None)) .map_err(wrap_err) } /// Add a [`PluginSource`] to the given [`CustomValue`] if it is a [`PluginCustomValue`]. pub fn add_source(value: &mut Box<dyn CustomValue>, source: &Arc<PluginSource>) { if let Some(custom_value) = value.as_any().downcast_ref::<PluginCustomValue>() { *value = Box::new(custom_value.clone().with_source(source.clone())); } } /// Add a [`PluginSource`] to all [`PluginCustomValue`]s within the value, recursively. pub fn add_source_in(value: &mut Value, source: &Arc<PluginSource>) -> Result<(), ShellError> { with_custom_values_in(value, |custom_value| { Self::add_source(custom_value.item, source); Ok::<_, ShellError>(()) }) } /// Remove a [`PluginSource`] from the given [`CustomValue`] if it is a /// [`PluginCustomValueWithSource`]. This will turn it back into a [`PluginCustomValue`]. pub fn remove_source(value: &mut Box<dyn CustomValue>) { if let Some(custom_value) = value.as_any().downcast_ref::<PluginCustomValueWithSource>() { *value = Box::new(custom_value.clone().without_source()); } } /// Remove the [`PluginSource`] from all [`PluginCustomValue`]s within the value, recursively. pub fn remove_source_in(value: &mut Value) -> Result<(), ShellError> { with_custom_values_in(value, |custom_value| { Self::remove_source(custom_value.item); Ok::<_, ShellError>(()) }) } /// Check that `self` came from the given `source`, and return an `error` if not. pub fn verify_source(&self, span: Span, source: &PluginSource) -> Result<(), ShellError> { if self.source.is_compatible(source) { Ok(()) } else { Err(ShellError::CustomValueIncorrectForPlugin { name: self.name().to_owned(), span, dest_plugin: source.name().to_owned(), src_plugin: Some(self.source.name().to_owned()), }) } } /// Check that a [`CustomValue`] is a [`PluginCustomValueWithSource`] that came from the given /// `source`, and return an error if not. pub fn verify_source_of_custom_value( value: Spanned<&dyn CustomValue>, source: &PluginSource, ) -> Result<(), ShellError> { if let Some(custom_value) = value .item .as_any() .downcast_ref::<PluginCustomValueWithSource>() { custom_value.verify_source(value.span, source) } else { // Only PluginCustomValueWithSource can be sent Err(ShellError::CustomValueIncorrectForPlugin { name: value.item.type_name(), span: value.span, dest_plugin: source.name().to_owned(), src_plugin: None, }) } } } impl std::ops::Deref for PluginCustomValueWithSource { type Target = PluginCustomValue; fn deref(&self) -> &PluginCustomValue { &self.inner } } /// This `Serialize` implementation always produces an error. Strip the source before sending. impl Serialize for PluginCustomValueWithSource { fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { use serde::ser::Error; Err(Error::custom( "can't serialize PluginCustomValueWithSource, remove the source first", )) } } impl CustomValue for PluginCustomValueWithSource { fn clone_value(&self, span: Span) -> Value { self.clone().into_value(span) } fn type_name(&self) -> String { self.name().to_owned() } fn to_base_value(&self, span: Span) -> Result<Value, ShellError> { self.get_plugin(Some(span), "get base value")? .custom_value_to_base_value(self.clone().into_spanned(span)) } fn follow_path_int( &self, self_span: Span, index: usize, path_span: Span, optional: bool, ) -> Result<Value, ShellError> { self.get_plugin(Some(self_span), "follow cell path")? .custom_value_follow_path_int( self.clone().into_spanned(self_span), index.into_spanned(path_span), optional, ) } fn follow_path_string( &self, self_span: Span, column_name: String, path_span: Span, optional: bool, casing: Casing, ) -> Result<Value, ShellError> { self.get_plugin(Some(self_span), "follow cell path")? .custom_value_follow_path_string( self.clone().into_spanned(self_span), column_name.into_spanned(path_span), optional, casing, ) } fn partial_cmp(&self, other: &Value) -> Option<Ordering> { self.get_plugin(Some(other.span()), "perform comparison") .and_then(|plugin| { // We're passing Span::unknown() here because we don't have one, and it probably // shouldn't matter here and is just a consequence of the API plugin.custom_value_partial_cmp(self.clone(), other.clone()) }) .unwrap_or_else(|err| { // We can't do anything with the error other than log it. log::warn!( "Error in partial_cmp on plugin custom value (source={source:?}): {err}", source = self.source ); None }) .map(|ordering| ordering.into()) } fn operation( &self, lhs_span: Span, operator: Operator, op_span: Span, right: &Value, ) -> Result<Value, ShellError> { self.get_plugin(Some(lhs_span), "invoke operator")? .custom_value_operation( self.clone().into_spanned(lhs_span), operator.into_spanned(op_span), right.clone(), ) } fn save( &self, path: Spanned<&Path>, value_span: Span, save_span: Span, ) -> Result<(), ShellError> { self.get_plugin(Some(value_span), "save")? .custom_value_save(self.clone().into_spanned(value_span), path, save_span) } fn as_any(&self) -> &dyn std::any::Any { self } fn as_mut_any(&mut self) -> &mut dyn std::any::Any { self } #[doc(hidden)] fn typetag_name(&self) -> &'static str { "PluginCustomValueWithSource" } #[doc(hidden)] fn typetag_deserialize(&self) {} } impl Drop for PluginCustomValueWithSource { fn drop(&mut self) { // If the custom value specifies notify_on_drop and this is the last copy, we need to let // the plugin know about it if we can. if self.notify_on_drop() && self.inner.ref_count() == 1 { self.get_plugin(None, "drop") // While notifying drop, we don't need a copy of the source .and_then(|plugin| plugin.custom_value_dropped(self.inner.clone())) .unwrap_or_else(|err| { // We shouldn't do anything with the error except log it let name = self.name(); log::warn!("Failed to notify drop of custom value ({name}): {err}") }); } } } /// Helper trait for adding a source to a [`PluginCustomValue`] pub trait WithSource { /// Add a source to a plugin custom value fn with_source(self, source: Arc<PluginSource>) -> PluginCustomValueWithSource; } impl WithSource for PluginCustomValue { fn with_source(self, source: Arc<PluginSource>) -> PluginCustomValueWithSource { PluginCustomValueWithSource::new(self, source) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_inc/src/lib.rs
crates/nu_plugin_inc/src/lib.rs
mod inc; mod nu; pub use inc::Inc; pub use nu::IncPlugin;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_inc/src/inc.rs
crates/nu_plugin_inc/src/inc.rs
use nu_protocol::{LabeledError, Span, Value, ast::CellPath}; use semver::{BuildMetadata, Prerelease, Version}; #[derive(Debug, Eq, PartialEq, Clone, Copy)] pub enum Action { SemVerAction(SemVerAction), Default, } #[derive(Debug, Eq, PartialEq, Clone, Copy)] pub enum SemVerAction { Major, Minor, Patch, } #[derive(Default, Clone)] pub struct Inc { pub error: Option<String>, pub cell_path: Option<CellPath>, pub action: Option<Action>, } impl Inc { pub fn new() -> Self { Default::default() } fn apply(&self, input: &str, head: Span) -> Value { match &self.action { Some(Action::SemVerAction(act_on)) => { let mut ver = match semver::Version::parse(input) { Ok(parsed_ver) => parsed_ver, Err(_) => return Value::string(input, head), }; match act_on { SemVerAction::Major => Self::increment_major(&mut ver), SemVerAction::Minor => Self::increment_minor(&mut ver), SemVerAction::Patch => Self::increment_patch(&mut ver), } Value::string(ver.to_string(), head) } Some(Action::Default) | None => { if let Ok(v) = input.parse::<u64>() { Value::string((v + 1).to_string(), head) } else { Value::string(input, head) } } } } pub fn increment_patch(v: &mut Version) { v.patch += 1; v.pre = Prerelease::EMPTY; v.build = BuildMetadata::EMPTY; } pub fn increment_minor(v: &mut Version) { v.minor += 1; v.patch = 0; v.pre = Prerelease::EMPTY; v.build = BuildMetadata::EMPTY; } pub fn increment_major(v: &mut Version) { v.major += 1; v.minor = 0; v.patch = 0; v.pre = Prerelease::EMPTY; v.build = BuildMetadata::EMPTY; } pub fn for_semver(&mut self, part: SemVerAction) { if self.permit() { self.action = Some(Action::SemVerAction(part)); } else { self.log_error("can only apply one"); } } fn permit(&mut self) -> bool { self.action.is_none() } fn log_error(&mut self, message: &str) { self.error = Some(message.to_string()); } pub fn inc(&self, head: Span, value: &Value) -> Result<Value, LabeledError> { if let Some(cell_path) = &self.cell_path { let cell_value = value.follow_cell_path(&cell_path.members)?; let cell_value = self.inc_value(head, &cell_value)?; let mut value = value.clone(); value.update_data_at_cell_path(&cell_path.members, cell_value)?; Ok(value) } else { self.inc_value(head, value) } } pub fn inc_value(&self, head: Span, value: &Value) -> Result<Value, LabeledError> { match value { Value::Int { val, .. } => Ok(Value::int(val + 1, head)), Value::String { val, .. } => Ok(self.apply(val, head)), x => { let msg = x.coerce_string().map_err(|e| { LabeledError::new("Unable to extract string").with_label( format!("value cannot be converted to string {x:?} - {e}"), head, ) })?; Err(LabeledError::new("Incorrect value").with_label(msg, head)) } } } } #[cfg(test)] mod tests { mod semver { use nu_protocol::{Span, Value}; use crate::Inc; use crate::inc::SemVerAction; #[test] fn major() { let expected = Value::test_string("1.0.0"); let mut inc = Inc::new(); inc.for_semver(SemVerAction::Major); assert_eq!(inc.apply("0.1.3", Span::test_data()), expected) } #[test] fn minor() { let expected = Value::test_string("0.2.0"); let mut inc = Inc::new(); inc.for_semver(SemVerAction::Minor); assert_eq!(inc.apply("0.1.3", Span::test_data()), expected) } #[test] fn patch() { let expected = Value::test_string("0.1.4"); let mut inc = Inc::new(); inc.for_semver(SemVerAction::Patch); assert_eq!(inc.apply("0.1.3", Span::test_data()), expected) } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_inc/src/main.rs
crates/nu_plugin_inc/src/main.rs
use nu_plugin::{JsonSerializer, serve_plugin}; use nu_plugin_inc::IncPlugin; fn main() { serve_plugin(&IncPlugin, JsonSerializer {}) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_inc/src/nu/mod.rs
crates/nu_plugin_inc/src/nu/mod.rs
use crate::{Inc, inc::SemVerAction}; use nu_plugin::{EngineInterface, EvaluatedCall, Plugin, PluginCommand, SimplePluginCommand}; use nu_protocol::{LabeledError, Signature, SyntaxShape, Value, ast::CellPath}; pub struct IncPlugin; impl Plugin for IncPlugin { fn version(&self) -> String { env!("CARGO_PKG_VERSION").into() } fn commands(&self) -> Vec<Box<dyn PluginCommand<Plugin = Self>>> { vec![Box::new(Inc::new())] } } impl SimplePluginCommand for Inc { type Plugin = IncPlugin; fn name(&self) -> &str { "inc" } fn description(&self) -> &str { "Increment a value or version. Optionally use the column of a table." } fn signature(&self) -> Signature { Signature::build(PluginCommand::name(self)) .optional("cell_path", SyntaxShape::CellPath, "cell path to update") .switch( "major", "increment the major version (eg 1.2.1 -> 2.0.0)", Some('M'), ) .switch( "minor", "increment the minor version (eg 1.2.1 -> 1.3.0)", Some('m'), ) .switch( "patch", "increment the patch version (eg 1.2.1 -> 1.2.2)", Some('p'), ) } fn run( &self, _plugin: &IncPlugin, _engine: &EngineInterface, call: &EvaluatedCall, input: &Value, ) -> Result<Value, LabeledError> { let mut inc = self.clone(); let cell_path: Option<CellPath> = call.opt(0)?; inc.cell_path = cell_path; if call.has_flag("major")? { inc.for_semver(SemVerAction::Major); } if call.has_flag("minor")? { inc.for_semver(SemVerAction::Minor); } if call.has_flag("patch")? { inc.for_semver(SemVerAction::Patch); } inc.inc(call.head, input) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-protocol/src/evaluated_call.rs
crates/nu-plugin-protocol/src/evaluated_call.rs
use nu_protocol::{ FromValue, ShellError, Span, Spanned, Value, ast::{self, Expression}, engine::{Call, CallImpl, EngineState, Stack}, ir, }; use serde::{Deserialize, Serialize}; /// A representation of the plugin's invocation command including command line args /// /// The `EvaluatedCall` contains information about the way a `Plugin` was invoked representing the /// [`Span`] corresponding to the invocation as well as the arguments it was invoked with. It is /// one of the items passed to `PluginCommand::run()`, along with the plugin reference, the engine /// interface, and a [`Value`] that represents the input. /// /// The evaluated call is used with the Plugins because the plugin doesn't have /// access to the Stack and the EngineState the way a built in command might. For that /// reason, before encoding the message to the plugin all the arguments to the original /// call (which are expressions) are evaluated and passed to Values #[derive(Debug, Clone, Serialize, Deserialize)] pub struct EvaluatedCall { /// Span of the command invocation pub head: Span, /// Values of positional arguments pub positional: Vec<Value>, /// Names and values of named arguments pub named: Vec<(Spanned<String>, Option<Value>)>, } impl EvaluatedCall { /// Create a new [`EvaluatedCall`] with the given head span. pub fn new(head: Span) -> EvaluatedCall { EvaluatedCall { head, positional: vec![], named: vec![], } } /// Add a positional argument to an [`EvaluatedCall`]. /// /// # Example /// /// ```rust /// # use nu_protocol::{Value, Span, IntoSpanned}; /// # use nu_plugin_protocol::EvaluatedCall; /// # let head = Span::test_data(); /// let mut call = EvaluatedCall::new(head); /// call.add_positional(Value::test_int(1337)); /// ``` pub fn add_positional(&mut self, value: Value) -> &mut Self { self.positional.push(value); self } /// Add a named argument to an [`EvaluatedCall`]. /// /// # Example /// /// ```rust /// # use nu_protocol::{Value, Span, IntoSpanned}; /// # use nu_plugin_protocol::EvaluatedCall; /// # let head = Span::test_data(); /// let mut call = EvaluatedCall::new(head); /// call.add_named("foo".into_spanned(head), Value::test_string("bar")); /// ``` pub fn add_named(&mut self, name: Spanned<impl Into<String>>, value: Value) -> &mut Self { self.named.push((name.map(Into::into), Some(value))); self } /// Add a flag argument to an [`EvaluatedCall`]. A flag argument is a named argument with no /// value. /// /// # Example /// /// ```rust /// # use nu_protocol::{Value, Span, IntoSpanned}; /// # use nu_plugin_protocol::EvaluatedCall; /// # let head = Span::test_data(); /// let mut call = EvaluatedCall::new(head); /// call.add_flag("pretty".into_spanned(head)); /// ``` pub fn add_flag(&mut self, name: Spanned<impl Into<String>>) -> &mut Self { self.named.push((name.map(Into::into), None)); self } /// Builder variant of [`.add_positional()`](Self::add_positional). pub fn with_positional(mut self, value: Value) -> Self { self.add_positional(value); self } /// Builder variant of [`.add_named()`](Self::add_named). pub fn with_named(mut self, name: Spanned<impl Into<String>>, value: Value) -> Self { self.add_named(name, value); self } /// Builder variant of [`.add_flag()`](Self::add_flag). pub fn with_flag(mut self, name: Spanned<impl Into<String>>) -> Self { self.add_flag(name); self } /// Try to create an [`EvaluatedCall`] from a command `Call`. pub fn try_from_call( call: &Call, engine_state: &EngineState, stack: &mut Stack, eval_expression_fn: fn(&EngineState, &mut Stack, &Expression) -> Result<Value, ShellError>, ) -> Result<Self, ShellError> { match &call.inner { CallImpl::AstRef(call) => { Self::try_from_ast_call(call, engine_state, stack, eval_expression_fn) } CallImpl::AstBox(call) => { Self::try_from_ast_call(call, engine_state, stack, eval_expression_fn) } CallImpl::IrRef(call) => Self::try_from_ir_call(call, stack), CallImpl::IrBox(call) => Self::try_from_ir_call(call, stack), } } fn try_from_ast_call( call: &ast::Call, engine_state: &EngineState, stack: &mut Stack, eval_expression_fn: fn(&EngineState, &mut Stack, &Expression) -> Result<Value, ShellError>, ) -> Result<Self, ShellError> { let positional = call.rest_iter_flattened(0, |expr| eval_expression_fn(engine_state, stack, expr))?; let mut named = Vec::with_capacity(call.named_len()); for (string, _, expr) in call.named_iter() { let value = match expr { None => None, Some(expr) => Some(eval_expression_fn(engine_state, stack, expr)?), }; named.push((string.clone(), value)) } Ok(Self { head: call.head, positional, named, }) } fn try_from_ir_call(call: &ir::Call, stack: &Stack) -> Result<Self, ShellError> { let positional = call.rest_iter_flattened(stack, 0)?; let mut named = Vec::with_capacity(call.named_len(stack)); named.extend( call.named_iter(stack) .map(|(name, value)| (name.map(|s| s.to_owned()), value.cloned())), ); Ok(Self { head: call.head, positional, named, }) } /// Check if a flag (named parameter that does not take a value) is set /// Returns Ok(true) if flag is set or passed true value /// Returns Ok(false) if flag is not set or passed false value /// Returns Err if passed value is not a boolean /// /// # Examples /// Invoked as `my_command --foo`: /// ``` /// # use nu_protocol::{Spanned, Span, Value}; /// # use nu_plugin_protocol::EvaluatedCall; /// # let null_span = Span::new(0, 0); /// # let call = EvaluatedCall { /// # head: null_span, /// # positional: Vec::new(), /// # named: vec![( /// # Spanned { item: "foo".to_owned(), span: null_span}, /// # None /// # )], /// # }; /// assert!(call.has_flag("foo").unwrap()); /// ``` /// /// Invoked as `my_command --bar`: /// ``` /// # use nu_protocol::{Spanned, Span, Value}; /// # use nu_plugin_protocol::EvaluatedCall; /// # let null_span = Span::new(0, 0); /// # let call = EvaluatedCall { /// # head: null_span, /// # positional: Vec::new(), /// # named: vec![( /// # Spanned { item: "bar".to_owned(), span: null_span}, /// # None /// # )], /// # }; /// assert!(!call.has_flag("foo").unwrap()); /// ``` /// /// Invoked as `my_command --foo=true`: /// ``` /// # use nu_protocol::{Spanned, Span, Value}; /// # use nu_plugin_protocol::EvaluatedCall; /// # let null_span = Span::new(0, 0); /// # let call = EvaluatedCall { /// # head: null_span, /// # positional: Vec::new(), /// # named: vec![( /// # Spanned { item: "foo".to_owned(), span: null_span}, /// # Some(Value::bool(true, Span::unknown())) /// # )], /// # }; /// assert!(call.has_flag("foo").unwrap()); /// ``` /// /// Invoked as `my_command --foo=false`: /// ``` /// # use nu_protocol::{Spanned, Span, Value}; /// # use nu_plugin_protocol::EvaluatedCall; /// # let null_span = Span::new(0, 0); /// # let call = EvaluatedCall { /// # head: null_span, /// # positional: Vec::new(), /// # named: vec![( /// # Spanned { item: "foo".to_owned(), span: null_span}, /// # Some(Value::bool(false, Span::unknown())) /// # )], /// # }; /// assert!(!call.has_flag("foo").unwrap()); /// ``` /// /// Invoked with wrong type as `my_command --foo=1`: /// ``` /// # use nu_protocol::{Spanned, Span, Value}; /// # use nu_plugin_protocol::EvaluatedCall; /// # let null_span = Span::new(0, 0); /// # let call = EvaluatedCall { /// # head: null_span, /// # positional: Vec::new(), /// # named: vec![( /// # Spanned { item: "foo".to_owned(), span: null_span}, /// # Some(Value::int(1, Span::unknown())) /// # )], /// # }; /// assert!(call.has_flag("foo").is_err()); /// ``` pub fn has_flag(&self, flag_name: &str) -> Result<bool, ShellError> { for name in &self.named { if flag_name == name.0.item { return match &name.1 { Some(Value::Bool { val, .. }) => Ok(*val), None => Ok(true), Some(result) => Err(ShellError::CantConvert { to_type: "bool".into(), from_type: result.get_type().to_string(), span: result.span(), help: Some("".into()), }), }; } } Ok(false) } /// Returns the [`Span`] of the name of an optional named argument. /// /// This can be used in errors for named arguments that don't take values. pub fn get_flag_span(&self, flag_name: &str) -> Option<Span> { self.named .iter() .find(|(name, _)| name.item == flag_name) .map(|(name, _)| name.span) } /// Returns the [`Value`] of an optional named argument /// /// # Examples /// Invoked as `my_command --foo 123`: /// ``` /// # use nu_protocol::{Spanned, Span, Value}; /// # use nu_plugin_protocol::EvaluatedCall; /// # let null_span = Span::new(0, 0); /// # let call = EvaluatedCall { /// # head: null_span, /// # positional: Vec::new(), /// # named: vec![( /// # Spanned { item: "foo".to_owned(), span: null_span}, /// # Some(Value::int(123, null_span)) /// # )], /// # }; /// let opt_foo = match call.get_flag_value("foo") { /// Some(Value::Int { val, .. }) => Some(val), /// None => None, /// _ => panic!(), /// }; /// assert_eq!(opt_foo, Some(123)); /// ``` /// /// Invoked as `my_command`: /// ``` /// # use nu_protocol::{Spanned, Span, Value}; /// # use nu_plugin_protocol::EvaluatedCall; /// # let null_span = Span::new(0, 0); /// # let call = EvaluatedCall { /// # head: null_span, /// # positional: Vec::new(), /// # named: vec![], /// # }; /// let opt_foo = match call.get_flag_value("foo") { /// Some(Value::Int { val, .. }) => Some(val), /// None => None, /// _ => panic!(), /// }; /// assert_eq!(opt_foo, None); /// ``` pub fn get_flag_value(&self, flag_name: &str) -> Option<Value> { for name in &self.named { if flag_name == name.0.item { return name.1.clone(); } } None } /// Returns the [`Value`] of a given (zero indexed) positional argument, if present /// /// Examples: /// Invoked as `my_command a b c`: /// ``` /// # use nu_protocol::{Spanned, Span, Value}; /// # use nu_plugin_protocol::EvaluatedCall; /// # let null_span = Span::new(0, 0); /// # let call = EvaluatedCall { /// # head: null_span, /// # positional: vec![ /// # Value::string("a".to_owned(), null_span), /// # Value::string("b".to_owned(), null_span), /// # Value::string("c".to_owned(), null_span), /// # ], /// # named: vec![], /// # }; /// let arg = match call.nth(1) { /// Some(Value::String { val, .. }) => val, /// _ => panic!(), /// }; /// assert_eq!(arg, "b".to_owned()); /// /// let arg = call.nth(7); /// assert!(arg.is_none()); /// ``` pub fn nth(&self, pos: usize) -> Option<Value> { self.positional.get(pos).cloned() } /// Returns the value of a named argument interpreted as type `T` /// /// # Examples /// Invoked as `my_command --foo 123`: /// ``` /// # use nu_protocol::{Spanned, Span, Value}; /// # use nu_plugin_protocol::EvaluatedCall; /// # let null_span = Span::new(0, 0); /// # let call = EvaluatedCall { /// # head: null_span, /// # positional: Vec::new(), /// # named: vec![( /// # Spanned { item: "foo".to_owned(), span: null_span}, /// # Some(Value::int(123, null_span)) /// # )], /// # }; /// let foo = call.get_flag::<i64>("foo"); /// assert_eq!(foo.unwrap(), Some(123)); /// ``` /// /// Invoked as `my_command --bar 123`: /// ``` /// # use nu_protocol::{Spanned, Span, Value}; /// # use nu_plugin_protocol::EvaluatedCall; /// # let null_span = Span::new(0, 0); /// # let call = EvaluatedCall { /// # head: null_span, /// # positional: Vec::new(), /// # named: vec![( /// # Spanned { item: "bar".to_owned(), span: null_span}, /// # Some(Value::int(123, null_span)) /// # )], /// # }; /// let foo = call.get_flag::<i64>("foo"); /// assert_eq!(foo.unwrap(), None); /// ``` /// /// Invoked as `my_command --foo abc`: /// ``` /// # use nu_protocol::{Spanned, Span, Value}; /// # use nu_plugin_protocol::EvaluatedCall; /// # let null_span = Span::new(0, 0); /// # let call = EvaluatedCall { /// # head: null_span, /// # positional: Vec::new(), /// # named: vec![( /// # Spanned { item: "foo".to_owned(), span: null_span}, /// # Some(Value::string("abc".to_owned(), null_span)) /// # )], /// # }; /// let foo = call.get_flag::<i64>("foo"); /// assert!(foo.is_err()); /// ``` pub fn get_flag<T: FromValue>(&self, name: &str) -> Result<Option<T>, ShellError> { if let Some(value) = self.get_flag_value(name) { FromValue::from_value(value).map(Some) } else { Ok(None) } } /// Retrieve the Nth and all following positional arguments as type `T` /// /// # Example /// Invoked as `my_command zero one two three`: /// ``` /// # use nu_protocol::{Spanned, Span, Value}; /// # use nu_plugin_protocol::EvaluatedCall; /// # let null_span = Span::new(0, 0); /// # let call = EvaluatedCall { /// # head: null_span, /// # positional: vec![ /// # Value::string("zero".to_owned(), null_span), /// # Value::string("one".to_owned(), null_span), /// # Value::string("two".to_owned(), null_span), /// # Value::string("three".to_owned(), null_span), /// # ], /// # named: Vec::new(), /// # }; /// let args = call.rest::<String>(0); /// assert_eq!(args.unwrap(), vec!["zero", "one", "two", "three"]); /// /// let args = call.rest::<String>(2); /// assert_eq!(args.unwrap(), vec!["two", "three"]); /// ``` pub fn rest<T: FromValue>(&self, starting_pos: usize) -> Result<Vec<T>, ShellError> { self.positional .iter() .skip(starting_pos) .map(|value| FromValue::from_value(value.clone())) .collect() } /// Retrieve the value of an optional positional argument interpreted as type `T` /// /// Returns the value of a (zero indexed) positional argument of type `T`. /// Alternatively returns [`None`] if the positional argument does not exist /// or an error that can be passed back to the shell on error. pub fn opt<T: FromValue>(&self, pos: usize) -> Result<Option<T>, ShellError> { if let Some(value) = self.nth(pos) { FromValue::from_value(value).map(Some) } else { Ok(None) } } /// Retrieve the value of a mandatory positional argument as type `T` /// /// Expect a positional argument of type `T` and return its value or, if the /// argument does not exist or is of the wrong type, return an error that can /// be passed back to the shell. pub fn req<T: FromValue>(&self, pos: usize) -> Result<T, ShellError> { if let Some(value) = self.nth(pos) { FromValue::from_value(value) } else if self.positional.is_empty() { Err(ShellError::AccessEmptyContent { span: self.head }) } else { Err(ShellError::AccessBeyondEnd { max_idx: self.positional.len() - 1, span: self.head, }) } } } #[cfg(test)] mod test { use super::*; use nu_protocol::{Span, Spanned, Value}; #[test] fn call_to_value() { let call = EvaluatedCall { head: Span::new(0, 10), positional: vec![ Value::float(1.0, Span::new(0, 10)), Value::string("something", Span::new(0, 10)), ], named: vec![ ( Spanned { item: "name".to_string(), span: Span::new(0, 10), }, Some(Value::float(1.0, Span::new(0, 10))), ), ( Spanned { item: "flag".to_string(), span: Span::new(0, 10), }, None, ), ], }; let name: Option<f64> = call.get_flag("name").unwrap(); assert_eq!(name, Some(1.0)); assert!(call.has_flag("flag").unwrap()); let required: f64 = call.req(0).unwrap(); assert!((required - 1.0).abs() < f64::EPSILON); let optional: Option<String> = call.opt(1).unwrap(); assert_eq!(optional, Some("something".to_string())); let rest: Vec<String> = call.rest(1).unwrap(); assert_eq!(rest, vec!["something".to_string()]); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-protocol/src/lib.rs
crates/nu-plugin-protocol/src/lib.rs
//! Type definitions, including full `Serialize` and `Deserialize` implementations, for the protocol //! used for communication between the engine and a plugin. //! //! See the [plugin protocol reference](https://www.nushell.sh/contributor-book/plugin_protocol_reference.html) //! for more details on what exactly is being specified here. //! //! Plugins accept messages of [`PluginInput`] and send messages back of [`PluginOutput`]. This //! crate explicitly avoids implementing any functionality that depends on I/O, so the exact //! byte-level encoding scheme is not implemented here. See the protocol ref or `nu_plugin_core` for //! more details on how that works. mod evaluated_call; mod plugin_custom_value; mod protocol_info; #[cfg(test)] mod tests; /// Things that can help with protocol-related tests. Not part of the public API, just used by other /// nushell crates. #[doc(hidden)] pub mod test_util; use nu_protocol::{ BlockId, ByteStreamType, Config, DeclId, DynamicSuggestion, LabeledError, PipelineData, PipelineMetadata, PluginMetadata, PluginSignature, ShellError, SignalAction, Span, Spanned, Value, ast, ast::Operator, casing::Casing, engine::{ArgType, Closure}, ir::IrBlock, }; use nu_utils::SharedCow; use serde::{Deserialize, Serialize}; use std::{collections::HashMap, path::PathBuf}; pub use evaluated_call::EvaluatedCall; pub use plugin_custom_value::PluginCustomValue; #[allow(unused_imports)] // may be unused by compile flags pub use protocol_info::{Feature, Protocol, ProtocolInfo}; /// A sequential identifier for a stream pub type StreamId = usize; /// A sequential identifier for a [`PluginCall`] pub type PluginCallId = usize; /// A sequential identifier for an [`EngineCall`] pub type EngineCallId = usize; /// Information about a plugin command invocation. This includes an [`EvaluatedCall`] as a /// serializable representation of [`nu_protocol::ast::Call`]. The type parameter determines /// the input type. #[derive(Serialize, Deserialize, Debug, Clone)] pub struct CallInfo<D> { /// The name of the command to be run pub name: String, /// Information about the invocation, including arguments pub call: EvaluatedCall, /// Pipeline input. This is usually [`nu_protocol::PipelineData`] or [`PipelineDataHeader`] pub input: D, } #[derive(Serialize, Deserialize, Debug, Clone)] pub enum GetCompletionArgType { Flag(String), Positional(usize), } impl<'a> From<GetCompletionArgType> for ArgType<'a> { fn from(value: GetCompletionArgType) -> Self { match value { GetCompletionArgType::Flag(flag_name) => { ArgType::Flag(std::borrow::Cow::from(flag_name)) } GetCompletionArgType::Positional(idx) => ArgType::Positional(idx), } } } /// A simple wrapper for [`ast::Call`] which contains additional context about completion. /// It's used in plugin side. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DynamicCompletionCall { /// the real call, which is generated during parse time. pub call: ast::Call, /// Indicates if there is a placeholder in input buffer. pub strip: bool, /// The position in input buffer, which is useful to find placeholder from arguments. pub pos: usize, } /// Information about `get_dynamic_completion` of a plugin call invocation. #[derive(Serialize, Deserialize, Debug, Clone)] pub struct GetCompletionInfo { /// The name of the command to be run. pub name: String, /// The flag name to get completion items. pub arg_type: GetCompletionArgType, /// Information about the invocation. pub call: DynamicCompletionCall, } impl<D> CallInfo<D> { /// Convert the type of `input` from `D` to `T`. pub fn map_data<T>( self, f: impl FnOnce(D) -> Result<T, ShellError>, ) -> Result<CallInfo<T>, ShellError> { Ok(CallInfo { name: self.name, call: self.call, input: f(self.input)?, }) } } /// The initial (and perhaps only) part of any [`nu_protocol::PipelineData`] sent over the wire. /// /// This may contain a single value, or may initiate a stream with a [`StreamId`]. #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] pub enum PipelineDataHeader { /// No input Empty, /// A single value Value(Value, Option<PipelineMetadata>), /// Initiate [`nu_protocol::PipelineData::ListStream`]. /// /// Items are sent via [`StreamData`] ListStream(ListStreamInfo), /// Initiate [`nu_protocol::PipelineData::byte_stream`]. /// /// Items are sent via [`StreamData`] ByteStream(ByteStreamInfo), } impl PipelineDataHeader { /// Return the stream ID, if any, embedded in the header pub fn stream_id(&self) -> Option<StreamId> { match self { PipelineDataHeader::Empty => None, PipelineDataHeader::Value(_, _) => None, PipelineDataHeader::ListStream(info) => Some(info.id), PipelineDataHeader::ByteStream(info) => Some(info.id), } } pub fn value(value: Value) -> Self { PipelineDataHeader::Value(value, None) } pub fn list_stream(info: ListStreamInfo) -> Self { PipelineDataHeader::ListStream(info) } pub fn byte_stream(info: ByteStreamInfo) -> Self { PipelineDataHeader::ByteStream(info) } } /// Additional information about list (value) streams #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] pub struct ListStreamInfo { pub id: StreamId, pub span: Span, pub metadata: Option<PipelineMetadata>, } impl ListStreamInfo { /// Create a new `ListStreamInfo` with a unique ID pub fn new(id: StreamId, span: Span) -> Self { ListStreamInfo { id, span, metadata: None, } } } /// Additional information about byte streams #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] pub struct ByteStreamInfo { pub id: StreamId, pub span: Span, #[serde(rename = "type")] pub type_: ByteStreamType, pub metadata: Option<PipelineMetadata>, } impl ByteStreamInfo { /// Create a new `ByteStreamInfo` with a unique ID pub fn new(id: StreamId, span: Span, type_: ByteStreamType) -> Self { ByteStreamInfo { id, span, type_, metadata: None, } } } /// Calls that a plugin can execute. The type parameter determines the input type. #[derive(Serialize, Deserialize, Debug, Clone)] pub enum PluginCall<D> { Metadata, Signature, Run(CallInfo<D>), GetCompletion(GetCompletionInfo), CustomValueOp(Spanned<PluginCustomValue>, CustomValueOp), } impl<D> PluginCall<D> { /// Convert the data type from `D` to `T`. The function will not be called if the variant does /// not contain data. pub fn map_data<T>( self, f: impl FnOnce(D) -> Result<T, ShellError>, ) -> Result<PluginCall<T>, ShellError> { Ok(match self { PluginCall::Metadata => PluginCall::Metadata, PluginCall::Signature => PluginCall::Signature, PluginCall::GetCompletion(flag_name) => PluginCall::GetCompletion(flag_name), PluginCall::Run(call) => PluginCall::Run(call.map_data(f)?), PluginCall::CustomValueOp(custom_value, op) => { PluginCall::CustomValueOp(custom_value, op) } }) } /// The span associated with the call. pub fn span(&self) -> Option<Span> { match self { PluginCall::Metadata => None, PluginCall::Signature => None, PluginCall::GetCompletion(_) => None, PluginCall::Run(CallInfo { call, .. }) => Some(call.head), PluginCall::CustomValueOp(val, _) => Some(val.span), } } } /// Operations supported for custom values. #[derive(Serialize, Deserialize, Debug, Clone)] pub enum CustomValueOp { /// [`to_base_value()`](nu_protocol::CustomValue::to_base_value) ToBaseValue, /// [`follow_path_int()`](nu_protocol::CustomValue::follow_path_int) FollowPathInt { index: Spanned<usize>, optional: bool, }, /// [`follow_path_string()`](nu_protocol::CustomValue::follow_path_string) FollowPathString { column_name: Spanned<String>, optional: bool, casing: Casing, }, /// [`partial_cmp()`](nu_protocol::CustomValue::partial_cmp) PartialCmp(Value), /// [`operation()`](nu_protocol::CustomValue::operation) Operation(Spanned<Operator>, Value), /// [`save()`](nu_protocol::CustomValue::save) Save { path: Spanned<PathBuf>, save_call_span: Span, }, /// Notify that the custom value has been dropped, if /// [`notify_plugin_on_drop()`](nu_protocol::CustomValue::notify_plugin_on_drop) is true Dropped, } impl CustomValueOp { /// Get the name of the op, for error messages. pub fn name(&self) -> &'static str { match self { CustomValueOp::ToBaseValue => "to_base_value", CustomValueOp::FollowPathInt { .. } => "follow_path_int", CustomValueOp::FollowPathString { .. } => "follow_path_string", CustomValueOp::PartialCmp(_) => "partial_cmp", CustomValueOp::Operation(_, _) => "operation", CustomValueOp::Save { .. } => "save", CustomValueOp::Dropped => "dropped", } } } /// Any data sent to the plugin #[derive(Serialize, Deserialize, Debug, Clone)] pub enum PluginInput { /// This must be the first message. Indicates supported protocol Hello(ProtocolInfo), /// Execute a [`PluginCall`], such as `Run` or `Signature`. The ID should not have been used /// before. Call(PluginCallId, PluginCall<PipelineDataHeader>), /// Don't expect any more plugin calls. Exit after all currently executing plugin calls are /// finished. Goodbye, /// Response to an [`EngineCall`]. The ID should be the same one sent with the engine call this /// is responding to EngineCallResponse(EngineCallId, EngineCallResponse<PipelineDataHeader>), /// See [`StreamMessage::Data`]. Data(StreamId, StreamData), /// See [`StreamMessage::End`]. End(StreamId), /// See [`StreamMessage::Drop`]. Drop(StreamId), /// See [`StreamMessage::Ack`]. Ack(StreamId), /// Relay signals to the plugin Signal(SignalAction), } impl TryFrom<PluginInput> for StreamMessage { type Error = PluginInput; fn try_from(msg: PluginInput) -> Result<StreamMessage, PluginInput> { match msg { PluginInput::Data(id, data) => Ok(StreamMessage::Data(id, data)), PluginInput::End(id) => Ok(StreamMessage::End(id)), PluginInput::Drop(id) => Ok(StreamMessage::Drop(id)), PluginInput::Ack(id) => Ok(StreamMessage::Ack(id)), _ => Err(msg), } } } impl From<StreamMessage> for PluginInput { fn from(stream_msg: StreamMessage) -> PluginInput { match stream_msg { StreamMessage::Data(id, data) => PluginInput::Data(id, data), StreamMessage::End(id) => PluginInput::End(id), StreamMessage::Drop(id) => PluginInput::Drop(id), StreamMessage::Ack(id) => PluginInput::Ack(id), } } } /// A single item of stream data for a stream. #[derive(Serialize, Deserialize, Debug, Clone)] pub enum StreamData { List(Value), Raw(Result<Vec<u8>, LabeledError>), } impl From<Value> for StreamData { fn from(value: Value) -> Self { StreamData::List(value) } } impl From<Result<Vec<u8>, LabeledError>> for StreamData { fn from(value: Result<Vec<u8>, LabeledError>) -> Self { StreamData::Raw(value) } } impl From<Result<Vec<u8>, ShellError>> for StreamData { fn from(value: Result<Vec<u8>, ShellError>) -> Self { value.map_err(LabeledError::from).into() } } impl TryFrom<StreamData> for Value { type Error = ShellError; fn try_from(data: StreamData) -> Result<Value, ShellError> { match data { StreamData::List(value) => Ok(value), StreamData::Raw(_) => Err(ShellError::PluginFailedToDecode { msg: "expected list stream data, found raw data".into(), }), } } } impl TryFrom<StreamData> for Result<Vec<u8>, LabeledError> { type Error = ShellError; fn try_from(data: StreamData) -> Result<Result<Vec<u8>, LabeledError>, ShellError> { match data { StreamData::Raw(value) => Ok(value), StreamData::List(_) => Err(ShellError::PluginFailedToDecode { msg: "expected raw stream data, found list data".into(), }), } } } impl TryFrom<StreamData> for Result<Vec<u8>, ShellError> { type Error = ShellError; fn try_from(value: StreamData) -> Result<Result<Vec<u8>, ShellError>, ShellError> { Result::<Vec<u8>, LabeledError>::try_from(value).map(|res| res.map_err(ShellError::from)) } } /// A stream control or data message. #[derive(Serialize, Deserialize, Debug, Clone)] pub enum StreamMessage { /// Append data to the stream. Sent by the stream producer. Data(StreamId, StreamData), /// End of stream. Sent by the stream producer. End(StreamId), /// Notify that the read end of the stream has closed, and further messages should not be /// sent. Sent by the stream consumer. Drop(StreamId), /// Acknowledge that a message has been consumed. This is used to implement flow control by /// the stream producer. Sent by the stream consumer. Ack(StreamId), } /// Response to a [`PluginCall`]. The type parameter determines the output type for pipeline data. #[derive(Serialize, Deserialize, Debug, Clone)] pub enum PluginCallResponse<D> { Ok, Error(ShellError), Metadata(PluginMetadata), Signature(Vec<PluginSignature>), Ordering(Option<Ordering>), CompletionItems(Option<Vec<DynamicSuggestion>>), PipelineData(D), } impl<D> PluginCallResponse<D> { /// Convert the data type from `D` to `T`. The function will not be called if the variant does /// not contain data. pub fn map_data<T>( self, f: impl FnOnce(D) -> Result<T, ShellError>, ) -> Result<PluginCallResponse<T>, ShellError> { Ok(match self { PluginCallResponse::Ok => PluginCallResponse::Ok, PluginCallResponse::Error(err) => PluginCallResponse::Error(err), PluginCallResponse::Metadata(meta) => PluginCallResponse::Metadata(meta), PluginCallResponse::Signature(sigs) => PluginCallResponse::Signature(sigs), PluginCallResponse::Ordering(ordering) => PluginCallResponse::Ordering(ordering), PluginCallResponse::CompletionItems(items) => { PluginCallResponse::CompletionItems(items) } PluginCallResponse::PipelineData(input) => PluginCallResponse::PipelineData(f(input)?), }) } } impl PluginCallResponse<PipelineDataHeader> { /// Construct a plugin call response with a single value pub fn value(value: Value) -> PluginCallResponse<PipelineDataHeader> { if value.is_nothing() { PluginCallResponse::PipelineData(PipelineDataHeader::Empty) } else { PluginCallResponse::PipelineData(PipelineDataHeader::value(value)) } } } impl PluginCallResponse<PipelineData> { /// Does this response have a stream? pub fn has_stream(&self) -> bool { match self { PluginCallResponse::PipelineData(data) => match data { PipelineData::Empty => false, PipelineData::Value(..) => false, PipelineData::ListStream(..) => true, PipelineData::ByteStream(..) => true, }, _ => false, } } } /// Options that can be changed to affect how the engine treats the plugin #[derive(Serialize, Deserialize, Debug, Clone)] pub enum PluginOption { /// Send `GcDisabled(true)` to stop the plugin from being automatically garbage collected, or /// `GcDisabled(false)` to enable it again. /// /// See `EngineInterface::set_gc_disabled()` in `nu-plugin` for more information. GcDisabled(bool), } /// This is just a serializable version of [`std::cmp::Ordering`], and can be converted 1:1 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] pub enum Ordering { Less, Equal, Greater, } impl From<std::cmp::Ordering> for Ordering { fn from(value: std::cmp::Ordering) -> Self { match value { std::cmp::Ordering::Less => Ordering::Less, std::cmp::Ordering::Equal => Ordering::Equal, std::cmp::Ordering::Greater => Ordering::Greater, } } } impl From<Ordering> for std::cmp::Ordering { fn from(value: Ordering) -> Self { match value { Ordering::Less => std::cmp::Ordering::Less, Ordering::Equal => std::cmp::Ordering::Equal, Ordering::Greater => std::cmp::Ordering::Greater, } } } /// Information received from the plugin #[derive(Serialize, Deserialize, Debug, Clone)] pub enum PluginOutput { /// This must be the first message. Indicates supported protocol Hello(ProtocolInfo), /// Set option. No response expected Option(PluginOption), /// A response to a [`PluginCall`]. The ID should be the same sent with the plugin call this /// is a response to CallResponse(PluginCallId, PluginCallResponse<PipelineDataHeader>), /// Execute an [`EngineCall`]. Engine calls must be executed within the `context` of a plugin /// call, and the `id` should not have been used before EngineCall { /// The plugin call (by ID) to execute in the context of context: PluginCallId, /// A new identifier for this engine call. The response will reference this ID id: EngineCallId, call: EngineCall<PipelineDataHeader>, }, /// See [`StreamMessage::Data`]. Data(StreamId, StreamData), /// See [`StreamMessage::End`]. End(StreamId), /// See [`StreamMessage::Drop`]. Drop(StreamId), /// See [`StreamMessage::Ack`]. Ack(StreamId), } impl TryFrom<PluginOutput> for StreamMessage { type Error = PluginOutput; fn try_from(msg: PluginOutput) -> Result<StreamMessage, PluginOutput> { match msg { PluginOutput::Data(id, data) => Ok(StreamMessage::Data(id, data)), PluginOutput::End(id) => Ok(StreamMessage::End(id)), PluginOutput::Drop(id) => Ok(StreamMessage::Drop(id)), PluginOutput::Ack(id) => Ok(StreamMessage::Ack(id)), _ => Err(msg), } } } impl From<StreamMessage> for PluginOutput { fn from(stream_msg: StreamMessage) -> PluginOutput { match stream_msg { StreamMessage::Data(id, data) => PluginOutput::Data(id, data), StreamMessage::End(id) => PluginOutput::End(id), StreamMessage::Drop(id) => PluginOutput::Drop(id), StreamMessage::Ack(id) => PluginOutput::Ack(id), } } } /// A remote call back to the engine during the plugin's execution. /// /// The type parameter determines the input type, for calls that take pipeline data. #[derive(Serialize, Deserialize, Debug, Clone)] pub enum EngineCall<D> { /// Get the full engine configuration GetConfig, /// Get the plugin-specific configuration (`$env.config.plugins.NAME`) GetPluginConfig, /// Get an environment variable GetEnvVar(String), /// Get all environment variables GetEnvVars, /// Get current working directory GetCurrentDir, /// Set an environment variable in the caller's scope AddEnvVar(String, Value), /// Get help for the current command GetHelp, /// Move the plugin into the foreground for terminal interaction EnterForeground, /// Move the plugin out of the foreground once terminal interaction has finished LeaveForeground, /// Get the contents of a span. Response is a binary which may not parse to UTF-8 GetSpanContents(Span), /// Evaluate a closure with stream input/output EvalClosure { /// The closure to call. /// /// This may come from a [`Value::Closure`] passed in as an argument to the plugin. closure: Spanned<Closure>, /// Positional arguments to add to the closure call positional: Vec<Value>, /// Input to the closure input: D, /// Whether to redirect stdout from external commands redirect_stdout: bool, /// Whether to redirect stderr from external commands redirect_stderr: bool, }, /// Find a declaration by name FindDecl(String), /// Get the compiled IR for a block GetBlockIR(BlockId), /// Call a declaration with args CallDecl { /// The id of the declaration to be called (can be found with `FindDecl`) decl_id: DeclId, /// Information about the call (head span, arguments, etc.) call: EvaluatedCall, /// Pipeline input to the call input: D, /// Whether to redirect stdout from external commands redirect_stdout: bool, /// Whether to redirect stderr from external commands redirect_stderr: bool, }, } impl<D> EngineCall<D> { /// Get the name of the engine call so it can be embedded in things like error messages pub fn name(&self) -> &'static str { match self { EngineCall::GetConfig => "GetConfig", EngineCall::GetPluginConfig => "GetPluginConfig", EngineCall::GetEnvVar(_) => "GetEnv", EngineCall::GetEnvVars => "GetEnvs", EngineCall::GetCurrentDir => "GetCurrentDir", EngineCall::AddEnvVar(..) => "AddEnvVar", EngineCall::GetHelp => "GetHelp", EngineCall::EnterForeground => "EnterForeground", EngineCall::LeaveForeground => "LeaveForeground", EngineCall::GetSpanContents(_) => "GetSpanContents", EngineCall::EvalClosure { .. } => "EvalClosure", EngineCall::FindDecl(_) => "FindDecl", EngineCall::GetBlockIR(_) => "GetBlockIR", EngineCall::CallDecl { .. } => "CallDecl", } } /// Convert the data type from `D` to `T`. The function will not be called if the variant does /// not contain data. pub fn map_data<T>( self, f: impl FnOnce(D) -> Result<T, ShellError>, ) -> Result<EngineCall<T>, ShellError> { Ok(match self { EngineCall::GetConfig => EngineCall::GetConfig, EngineCall::GetPluginConfig => EngineCall::GetPluginConfig, EngineCall::GetEnvVar(name) => EngineCall::GetEnvVar(name), EngineCall::GetEnvVars => EngineCall::GetEnvVars, EngineCall::GetCurrentDir => EngineCall::GetCurrentDir, EngineCall::AddEnvVar(name, value) => EngineCall::AddEnvVar(name, value), EngineCall::GetHelp => EngineCall::GetHelp, EngineCall::EnterForeground => EngineCall::EnterForeground, EngineCall::LeaveForeground => EngineCall::LeaveForeground, EngineCall::GetSpanContents(span) => EngineCall::GetSpanContents(span), EngineCall::EvalClosure { closure, positional, input, redirect_stdout, redirect_stderr, } => EngineCall::EvalClosure { closure, positional, input: f(input)?, redirect_stdout, redirect_stderr, }, EngineCall::FindDecl(name) => EngineCall::FindDecl(name), EngineCall::GetBlockIR(block_id) => EngineCall::GetBlockIR(block_id), EngineCall::CallDecl { decl_id, call, input, redirect_stdout, redirect_stderr, } => EngineCall::CallDecl { decl_id, call, input: f(input)?, redirect_stdout, redirect_stderr, }, }) } } /// The response to an [`EngineCall`]. The type parameter determines the output type for pipeline /// data. #[derive(Serialize, Deserialize, Debug, Clone)] pub enum EngineCallResponse<D> { Error(ShellError), PipelineData(D), Config(SharedCow<Config>), ValueMap(HashMap<String, Value>), Identifier(DeclId), IrBlock(Box<IrBlock>), } impl<D> EngineCallResponse<D> { /// Convert the data type from `D` to `T`. The function will not be called if the variant does /// not contain data. pub fn map_data<T>( self, f: impl FnOnce(D) -> Result<T, ShellError>, ) -> Result<EngineCallResponse<T>, ShellError> { Ok(match self { EngineCallResponse::Error(err) => EngineCallResponse::Error(err), EngineCallResponse::PipelineData(data) => EngineCallResponse::PipelineData(f(data)?), EngineCallResponse::Config(config) => EngineCallResponse::Config(config), EngineCallResponse::ValueMap(map) => EngineCallResponse::ValueMap(map), EngineCallResponse::Identifier(id) => EngineCallResponse::Identifier(id), EngineCallResponse::IrBlock(ir) => EngineCallResponse::IrBlock(ir), }) } } impl EngineCallResponse<PipelineData> { /// Build an [`EngineCallResponse::PipelineData`] from a [`Value`] pub fn value(value: Value) -> EngineCallResponse<PipelineData> { EngineCallResponse::PipelineData(PipelineData::value(value, None)) } /// An [`EngineCallResponse::PipelineData`] with [`PipelineData::empty()`] pub const fn empty() -> EngineCallResponse<PipelineData> { EngineCallResponse::PipelineData(PipelineData::empty()) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-protocol/src/tests.rs
crates/nu-plugin-protocol/src/tests.rs
use super::*; #[test] fn protocol_info_compatible() -> Result<(), ShellError> { let ver_1_2_3 = ProtocolInfo { protocol: Protocol::NuPlugin, version: "1.2.3".into(), features: vec![], }; let ver_1_1_0 = ProtocolInfo { protocol: Protocol::NuPlugin, version: "1.1.0".into(), features: vec![], }; assert!(ver_1_1_0.is_compatible_with(&ver_1_2_3)?); assert!(ver_1_2_3.is_compatible_with(&ver_1_1_0)?); Ok(()) } #[test] fn protocol_info_incompatible() -> Result<(), ShellError> { let ver_2_0_0 = ProtocolInfo { protocol: Protocol::NuPlugin, version: "2.0.0".into(), features: vec![], }; let ver_1_1_0 = ProtocolInfo { protocol: Protocol::NuPlugin, version: "1.1.0".into(), features: vec![], }; assert!(!ver_2_0_0.is_compatible_with(&ver_1_1_0)?); assert!(!ver_1_1_0.is_compatible_with(&ver_2_0_0)?); Ok(()) } #[test] fn protocol_info_compatible_with_nightly() -> Result<(), ShellError> { let ver_1_2_3 = ProtocolInfo { protocol: Protocol::NuPlugin, version: "1.2.3".into(), features: vec![], }; let ver_1_1_0 = ProtocolInfo { protocol: Protocol::NuPlugin, version: "1.1.0-nightly.1".into(), features: vec![], }; assert!(ver_1_1_0.is_compatible_with(&ver_1_2_3)?); assert!(ver_1_2_3.is_compatible_with(&ver_1_1_0)?); Ok(()) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-protocol/src/test_util.rs
crates/nu-plugin-protocol/src/test_util.rs
use crate::PluginCustomValue; use nu_protocol::{CustomValue, ShellError, Span, Value}; use serde::{Deserialize, Serialize}; /// A custom value that can be used for testing. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct TestCustomValue(pub i32); #[typetag::serde(name = "nu_plugin_protocol::test_util::TestCustomValue")] impl CustomValue for TestCustomValue { fn clone_value(&self, span: Span) -> Value { Value::custom(Box::new(self.clone()), span) } fn type_name(&self) -> String { "TestCustomValue".into() } fn to_base_value(&self, span: Span) -> Result<Value, ShellError> { Ok(Value::int(self.0 as i64, span)) } fn as_any(&self) -> &dyn std::any::Any { self } fn as_mut_any(&mut self) -> &mut dyn std::any::Any { self } } /// A [`TestCustomValue`] serialized as a [`PluginCustomValue`]. pub fn test_plugin_custom_value() -> PluginCustomValue { let data = rmp_serde::to_vec(&expected_test_custom_value() as &dyn CustomValue) .expect("MessagePack serialization of the expected_test_custom_value() failed"); PluginCustomValue::new("TestCustomValue".into(), data, false) } /// The expected [`TestCustomValue`] that [`test_plugin_custom_value()`] should deserialize into. pub fn expected_test_custom_value() -> TestCustomValue { TestCustomValue(-1) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-protocol/src/protocol_info.rs
crates/nu-plugin-protocol/src/protocol_info.rs
use nu_protocol::ShellError; use semver::Prerelease; use serde::{Deserialize, Serialize}; /// Protocol information, sent as a `Hello` message on initialization. This determines the /// compatibility of the plugin and engine. They are considered to be compatible if the lower /// version is semver compatible with the higher one. #[derive(Serialize, Deserialize, Debug, Clone)] pub struct ProtocolInfo { /// The name of the protocol being implemented. Only one protocol is supported. This field /// can be safely ignored, because not matching is a deserialization error pub protocol: Protocol, /// The semantic version of the protocol. This should be the version of the `nu-plugin-protocol` /// crate pub version: String, /// Supported optional features. This helps to maintain semver compatibility when adding new /// features pub features: Vec<Feature>, } impl Default for ProtocolInfo { fn default() -> ProtocolInfo { ProtocolInfo { protocol: Protocol::NuPlugin, version: env!("CARGO_PKG_VERSION").into(), features: default_features(), } } } impl ProtocolInfo { /// True if the version specified in `self` is compatible with the version specified in `other`. pub fn is_compatible_with(&self, other: &ProtocolInfo) -> Result<bool, ShellError> { fn parse_failed(error: semver::Error) -> ShellError { ShellError::PluginFailedToLoad { msg: format!("Failed to parse protocol version: {error}"), } } let mut versions = [ semver::Version::parse(&self.version).map_err(parse_failed)?, semver::Version::parse(&other.version).map_err(parse_failed)?, ]; versions.sort(); // The version may be a nightly version (1.2.3-nightly.1). // It's good to mark the prerelease field as empty, so plugins // can work with a nightly version of Nushell. versions[1].pre = Prerelease::EMPTY; versions[0].pre = Prerelease::EMPTY; // For example, if the lower version is 1.1.0, and the higher version is 1.2.3, the // requirement is that 1.2.3 matches ^1.1.0 (which it does) Ok(semver::Comparator { op: semver::Op::Caret, major: versions[0].major, minor: Some(versions[0].minor), patch: Some(versions[0].patch), pre: versions[0].pre.clone(), } .matches(&versions[1])) } /// True if the protocol info contains a feature compatible with the given feature. pub fn supports_feature(&self, feature: &Feature) -> bool { self.features.iter().any(|f| feature.is_compatible_with(f)) } } /// Indicates the protocol in use. Only one protocol is supported. #[derive(Serialize, Deserialize, Debug, Clone, Default)] pub enum Protocol { /// Serializes to the value `"nu-plugin"` #[serde(rename = "nu-plugin")] #[default] NuPlugin, } /// Indicates optional protocol features. This can help to make non-breaking-change additions to /// the protocol. Features are not restricted to plain strings and can contain additional /// configuration data. /// /// Optional features should not be used by the protocol if they are not present in the /// [`ProtocolInfo`] sent by the other side. #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(tag = "name")] pub enum Feature { /// The plugin supports running with a local socket passed via `--local-socket` instead of /// stdio. LocalSocket, /// A feature that was not recognized on deserialization. Attempting to serialize this feature /// is an error. Matching against it may only be used if necessary to determine whether /// unsupported features are present. #[serde(other, skip_serializing)] Unknown, } impl Feature { /// True if the feature is considered to be compatible with another feature. pub fn is_compatible_with(&self, other: &Feature) -> bool { matches!((self, other), (Feature::LocalSocket, Feature::LocalSocket)) } } /// Protocol features compiled into this version of `nu-plugin`. pub fn default_features() -> Vec<Feature> { vec![ // Only available if compiled with the `local-socket` feature flag (enabled by default). #[cfg(feature = "local-socket")] Feature::LocalSocket, ] }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-protocol/src/plugin_custom_value/tests.rs
crates/nu-plugin-protocol/src/plugin_custom_value/tests.rs
use crate::test_util::{TestCustomValue, expected_test_custom_value, test_plugin_custom_value}; use super::PluginCustomValue; use nu_protocol::{BlockId, CustomValue, ShellError, Span, Value, VarId, engine::Closure, record}; fn check_record_custom_values( val: &Value, keys: &[&str], mut f: impl FnMut(&str, &dyn CustomValue) -> Result<(), ShellError>, ) -> Result<(), ShellError> { let record = val.as_record()?; for key in keys { let val = record .get(key) .unwrap_or_else(|| panic!("record does not contain '{key}'")); let custom_value = val .as_custom_value() .unwrap_or_else(|_| panic!("'{key}' not custom value")); f(key, custom_value)?; } Ok(()) } fn check_list_custom_values( val: &Value, indices: impl IntoIterator<Item = usize>, mut f: impl FnMut(usize, &dyn CustomValue) -> Result<(), ShellError>, ) -> Result<(), ShellError> { let list = val.as_list()?; for index in indices { let val = list .get(index) .unwrap_or_else(|| panic!("[{index}] not present in list")); let custom_value = val .as_custom_value() .unwrap_or_else(|_| panic!("[{index}] not custom value")); f(index, custom_value)?; } Ok(()) } fn check_closure_custom_values( val: &Value, indices: impl IntoIterator<Item = usize>, mut f: impl FnMut(usize, &dyn CustomValue) -> Result<(), ShellError>, ) -> Result<(), ShellError> { let closure = val.as_closure()?; for index in indices { let val = closure .captures .get(index) .unwrap_or_else(|| panic!("[{index}] not present in closure")); let custom_value = val .1 .as_custom_value() .unwrap_or_else(|_| panic!("[{index}] not custom value")); f(index, custom_value)?; } Ok(()) } #[test] fn serialize_deserialize() -> Result<(), ShellError> { let original_value = TestCustomValue(32); let span = Span::test_data(); let serialized = PluginCustomValue::serialize_from_custom_value(&original_value, span)?; assert_eq!(original_value.type_name(), serialized.name()); let deserialized = serialized.deserialize_to_custom_value(span)?; let downcasted = deserialized .as_any() .downcast_ref::<TestCustomValue>() .expect("failed to downcast: not TestCustomValue"); assert_eq!(original_value, *downcasted); Ok(()) } #[test] fn expected_serialize_output() -> Result<(), ShellError> { let original_value = expected_test_custom_value(); let span = Span::test_data(); let serialized = PluginCustomValue::serialize_from_custom_value(&original_value, span)?; assert_eq!( test_plugin_custom_value().data(), serialized.data(), "The bincode configuration is probably different from what we expected. \ Fix test_plugin_custom_value() to match it" ); Ok(()) } #[test] fn serialize_in_root() -> Result<(), ShellError> { let span = Span::new(4, 10); let mut val = Value::custom(Box::new(expected_test_custom_value()), span); PluginCustomValue::serialize_custom_values_in(&mut val)?; assert_eq!(span, val.span()); let custom_value = val.as_custom_value()?; if let Some(plugin_custom_value) = custom_value.as_any().downcast_ref::<PluginCustomValue>() { assert_eq!("TestCustomValue", plugin_custom_value.name()); assert_eq!( test_plugin_custom_value().data(), plugin_custom_value.data() ); } else { panic!("Failed to downcast to PluginCustomValue"); } Ok(()) } #[test] fn serialize_in_record() -> Result<(), ShellError> { let orig_custom_val = Value::test_custom_value(Box::new(TestCustomValue(32))); let mut val = Value::test_record(record! { "foo" => orig_custom_val.clone(), "bar" => orig_custom_val.clone(), }); PluginCustomValue::serialize_custom_values_in(&mut val)?; check_record_custom_values(&val, &["foo", "bar"], |key, custom_value| { let plugin_custom_value: &PluginCustomValue = custom_value .as_any() .downcast_ref() .unwrap_or_else(|| panic!("'{key}' not PluginCustomValue")); assert_eq!( "TestCustomValue", plugin_custom_value.name(), "'{key}' name not set correctly" ); Ok(()) }) } #[test] fn serialize_in_list() -> Result<(), ShellError> { let orig_custom_val = Value::test_custom_value(Box::new(TestCustomValue(24))); let mut val = Value::test_list(vec![orig_custom_val.clone(), orig_custom_val.clone()]); PluginCustomValue::serialize_custom_values_in(&mut val)?; check_list_custom_values(&val, 0..=1, |index, custom_value| { let plugin_custom_value: &PluginCustomValue = custom_value .as_any() .downcast_ref() .unwrap_or_else(|| panic!("[{index}] not PluginCustomValue")); assert_eq!( "TestCustomValue", plugin_custom_value.name(), "[{index}] name not set correctly" ); Ok(()) }) } #[test] fn serialize_in_closure() -> Result<(), ShellError> { let orig_custom_val = Value::test_custom_value(Box::new(TestCustomValue(24))); let mut val = Value::test_closure(Closure { block_id: BlockId::new(0), captures: vec![ (VarId::new(0), orig_custom_val.clone()), (VarId::new(1), orig_custom_val.clone()), ], }); PluginCustomValue::serialize_custom_values_in(&mut val)?; check_closure_custom_values(&val, 0..=1, |index, custom_value| { let plugin_custom_value: &PluginCustomValue = custom_value .as_any() .downcast_ref() .unwrap_or_else(|| panic!("[{index}] not PluginCustomValue")); assert_eq!( "TestCustomValue", plugin_custom_value.name(), "[{index}] name not set correctly" ); Ok(()) }) } #[test] fn deserialize_in_root() -> Result<(), ShellError> { let span = Span::new(4, 10); let mut val = Value::custom(Box::new(test_plugin_custom_value()), span); PluginCustomValue::deserialize_custom_values_in(&mut val)?; assert_eq!(span, val.span()); let custom_value = val.as_custom_value()?; if let Some(test_custom_value) = custom_value.as_any().downcast_ref::<TestCustomValue>() { assert_eq!(expected_test_custom_value(), *test_custom_value); } else { panic!("Failed to downcast to TestCustomValue"); } Ok(()) } #[test] fn deserialize_in_record() -> Result<(), ShellError> { let orig_custom_val = Value::test_custom_value(Box::new(test_plugin_custom_value())); let mut val = Value::test_record(record! { "foo" => orig_custom_val.clone(), "bar" => orig_custom_val.clone(), }); PluginCustomValue::deserialize_custom_values_in(&mut val)?; check_record_custom_values(&val, &["foo", "bar"], |key, custom_value| { let test_custom_value: &TestCustomValue = custom_value .as_any() .downcast_ref() .unwrap_or_else(|| panic!("'{key}' not TestCustomValue")); assert_eq!( expected_test_custom_value(), *test_custom_value, "{key} not deserialized correctly" ); Ok(()) }) } #[test] fn deserialize_in_list() -> Result<(), ShellError> { let orig_custom_val = Value::test_custom_value(Box::new(test_plugin_custom_value())); let mut val = Value::test_list(vec![orig_custom_val.clone(), orig_custom_val.clone()]); PluginCustomValue::deserialize_custom_values_in(&mut val)?; check_list_custom_values(&val, 0..=1, |index, custom_value| { let test_custom_value: &TestCustomValue = custom_value .as_any() .downcast_ref() .unwrap_or_else(|| panic!("[{index}] not TestCustomValue")); assert_eq!( expected_test_custom_value(), *test_custom_value, "[{index}] name not deserialized correctly" ); Ok(()) }) } #[test] fn deserialize_in_closure() -> Result<(), ShellError> { let orig_custom_val = Value::test_custom_value(Box::new(test_plugin_custom_value())); let mut val = Value::test_closure(Closure { block_id: BlockId::new(0), captures: vec![ (VarId::new(0), orig_custom_val.clone()), (VarId::new(1), orig_custom_val.clone()), ], }); PluginCustomValue::deserialize_custom_values_in(&mut val)?; check_closure_custom_values(&val, 0..=1, |index, custom_value| { let test_custom_value: &TestCustomValue = custom_value .as_any() .downcast_ref() .unwrap_or_else(|| panic!("[{index}] not TestCustomValue")); assert_eq!( expected_test_custom_value(), *test_custom_value, "[{index}] name not deserialized correctly" ); Ok(()) }) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-protocol/src/plugin_custom_value/mod.rs
crates/nu-plugin-protocol/src/plugin_custom_value/mod.rs
use std::{cmp::Ordering, path::Path}; use nu_protocol::{CustomValue, ShellError, Span, Spanned, Value, ast::Operator, casing::Casing}; use nu_utils::SharedCow; use serde::{Deserialize, Serialize}; #[cfg(test)] mod tests; /// An opaque container for a custom value that is handled fully by a plugin. /// /// This is the only type of custom value that is allowed to cross the plugin serialization /// boundary. /// /// The plugin is responsible for ensuring that local plugin custom values are converted to and from /// [`PluginCustomValue`] on the boundary. /// /// The engine is responsible for adding tracking the source of the custom value, ensuring that only /// [`PluginCustomValue`] is contained within any values sent, and that the source of any values /// sent matches the plugin it is being sent to. /// /// Most of the [`CustomValue`] methods on this type will result in a panic. The source must be /// added (see `nu_plugin_engine::PluginCustomValueWithSource`) in order to implement the /// functionality via plugin calls. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct PluginCustomValue(SharedCow<SharedContent>); /// Content shared across copies of a plugin custom value. #[derive(Clone, Debug, Serialize, Deserialize)] struct SharedContent { /// The name of the type of the custom value as defined by the plugin (`type_name()`) name: String, /// The bincoded representation of the custom value on the plugin side data: Vec<u8>, /// True if the custom value should notify the source if all copies of it are dropped. /// /// This is not serialized if `false`, since most custom values don't need it. #[serde(default, skip_serializing_if = "is_false")] notify_on_drop: bool, } fn is_false(b: &bool) -> bool { !b } #[typetag::serde] impl CustomValue for PluginCustomValue { fn clone_value(&self, span: Span) -> Value { self.clone().into_value(span) } fn type_name(&self) -> String { self.name().to_owned() } fn to_base_value(&self, _span: Span) -> Result<Value, ShellError> { panic!("to_base_value() not available on plugin custom value without source"); } fn follow_path_int( &self, _self_span: Span, _index: usize, _path_span: Span, _optional: bool, ) -> Result<Value, ShellError> { panic!("follow_path_int() not available on plugin custom value without source"); } fn follow_path_string( &self, _self_span: Span, _column_name: String, _path_span: Span, _optional: bool, _casing: Casing, ) -> Result<Value, ShellError> { panic!("follow_path_string() not available on plugin custom value without source"); } fn partial_cmp(&self, _other: &Value) -> Option<Ordering> { panic!("partial_cmp() not available on plugin custom value without source"); } fn operation( &self, _lhs_span: Span, _operator: Operator, _op_span: Span, _right: &Value, ) -> Result<Value, ShellError> { panic!("operation() not available on plugin custom value without source"); } fn save( &self, _path: Spanned<&Path>, _value_span: Span, _save_span: Span, ) -> Result<(), ShellError> { panic!("save() not available on plugin custom value without source"); } fn as_any(&self) -> &dyn std::any::Any { self } fn as_mut_any(&mut self) -> &mut dyn std::any::Any { self } } impl PluginCustomValue { /// Create a new [`PluginCustomValue`]. pub fn new(name: String, data: Vec<u8>, notify_on_drop: bool) -> PluginCustomValue { PluginCustomValue(SharedCow::new(SharedContent { name, data, notify_on_drop, })) } /// Create a [`Value`] containing this custom value. pub fn into_value(self, span: Span) -> Value { Value::custom(Box::new(self), span) } /// The name of the type of the custom value as defined by the plugin (`type_name()`) pub fn name(&self) -> &str { &self.0.name } /// The bincoded representation of the custom value on the plugin side pub fn data(&self) -> &[u8] { &self.0.data } /// True if the custom value should notify the source if all copies of it are dropped. pub fn notify_on_drop(&self) -> bool { self.0.notify_on_drop } /// Count the number of shared copies of this [`PluginCustomValue`]. pub fn ref_count(&self) -> usize { SharedCow::ref_count(&self.0) } /// Serialize a custom value into a [`PluginCustomValue`]. This should only be done on the /// plugin side. pub fn serialize_from_custom_value( custom_value: &dyn CustomValue, span: Span, ) -> Result<PluginCustomValue, ShellError> { let name = custom_value.type_name(); let notify_on_drop = custom_value.notify_plugin_on_drop(); rmp_serde::to_vec(custom_value) .map(|data| PluginCustomValue::new(name, data, notify_on_drop)) .map_err(|err| ShellError::CustomValueFailedToEncode { msg: err.to_string(), span, }) } /// Deserialize a [`PluginCustomValue`] into a `Box<dyn CustomValue>`. This should only be done /// on the plugin side. pub fn deserialize_to_custom_value( &self, span: Span, ) -> Result<Box<dyn CustomValue>, ShellError> { rmp_serde::from_slice::<Box<dyn CustomValue>>(self.data()).map_err(|err| { ShellError::CustomValueFailedToDecode { msg: err.to_string(), span, } }) } /// Convert all plugin-native custom values to [`PluginCustomValue`] within the given `value`, /// recursively. This should only be done on the plugin side. pub fn serialize_custom_values_in(value: &mut Value) -> Result<(), ShellError> { value.recurse_mut(&mut |value| { let span = value.span(); match value { Value::Custom { val, .. } => { if val.as_any().downcast_ref::<PluginCustomValue>().is_some() { // Already a PluginCustomValue Ok(()) } else { let serialized = Self::serialize_from_custom_value(&**val, span)?; *value = Value::custom(Box::new(serialized), span); Ok(()) } } _ => Ok(()), } }) } /// Convert all [`PluginCustomValue`]s to plugin-native custom values within the given `value`, /// recursively. This should only be done on the plugin side. pub fn deserialize_custom_values_in(value: &mut Value) -> Result<(), ShellError> { value.recurse_mut(&mut |value| { let span = value.span(); match value { Value::Custom { val, .. } => { if let Some(val) = val.as_any().downcast_ref::<PluginCustomValue>() { let deserialized = val.deserialize_to_custom_value(span)?; *value = Value::custom(deserialized, span); Ok(()) } else { // Already not a PluginCustomValue Ok(()) } } _ => Ok(()), } }) } /// Render any custom values in the `Value` using `to_base_value()` pub fn render_to_base_value_in(value: &mut Value) -> Result<(), ShellError> { value.recurse_mut(&mut |value| { let span = value.span(); match value { Value::Custom { val, .. } => { *value = val.to_base_value(span)?; Ok(()) } _ => Ok(()), } }) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-term-grid/src/lib.rs
crates/nu-term-grid/src/lib.rs
#![doc = include_str!("../README.md")] pub mod grid; pub use grid::Grid;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-term-grid/src/grid.rs
crates/nu-term-grid/src/grid.rs
// Thanks to https://github.com/ogham/rust-term-grid for making this available //! This library arranges textual data in a grid format suitable for //! fixed-width fonts, using an algorithm to minimise the amount of space //! needed. For example: //! //! ```rust //! use nu_term_grid::grid::{Grid, GridOptions, Direction, Filling, Cell}; //! //! let mut grid = Grid::new(GridOptions { //! filling: Filling::Spaces(1), //! direction: Direction::LeftToRight, //! }); //! //! for s in &["one", "two", "three", "four", "five", "six", "seven", //! "eight", "nine", "ten", "eleven", "twelve"] //! { //! grid.add(Cell::from(*s)); //! } //! //! println!("{}", grid.fit_into_width(24).unwrap()); //! ``` //! //! Produces the following tabular result: //! //! ```text //! one two three four //! five six seven eight //! nine ten eleven twelve //! ``` //! //! //! ## Creating a grid //! //! To add data to a grid, first create a new [`Grid`] value, and then add //! cells to them with the `add` function. //! //! There are two options that must be specified in the [`GridOptions`] value //! that dictate how the grid is formatted: //! //! - `filling`: what to put in between two columns — either a number of //! spaces, or a text string; //! - `direction`, which specifies whether the cells should go along //! rows, or columns: //! - `Direction::LeftToRight` starts them in the top left and //! moves *rightwards*, going to the start of a new row after reaching the //! final column; //! - `Direction::TopToBottom` starts them in the top left and moves //! *downwards*, going to the top of a new column after reaching the final //! row. //! //! //! ## Displaying a grid //! //! When display a grid, you can either specify the number of columns in advance, //! or try to find the maximum number of columns that can fit in an area of a //! given width. //! //! Splitting a series of cells into columns — or, in other words, starting a new //! row every <var>n</var> cells — is achieved with the [`fit_into_columns`] function //! on a `Grid` value. It takes as its argument the number of columns. //! //! Trying to fit as much data onto one screen as possible is the main use case //! for specifying a maximum width instead. This is achieved with the //! [`fit_into_width`] function. It takes the maximum allowed width, including //! separators, as its argument. However, it returns an *optional* [`Display`] //! value, depending on whether any of the cells actually had a width greater than //! the maximum width! If this is the case, your best bet is to just output the //! cells with one per line. //! //! //! ## Cells and data //! //! Grids to not take `String`s or `&str`s — they take [`Cell`] values. //! //! A **Cell** is a struct containing an individual cell’s contents, as a string, //! and its pre-computed length, which gets used when calculating a grid’s final //! dimensions. Usually, you want the *Unicode width* of the string to be used for //! this, so you can turn a `String` into a `Cell` with the `.into()` function. //! //! However, you may also want to supply your own width: when you already know the //! width in advance, or when you want to change the measurement, such as skipping //! over terminal control characters. For cases like these, the fields on the //! `Cell` values are public, meaning you can construct your own instances as //! necessary. //! //! [`Cell`]: ./struct.Cell.html //! [`Display`]: ./struct.Display.html //! [`Grid`]: ./struct.Grid.html //! [`fit_into_columns`]: ./struct.Grid.html#method.fit_into_columns //! [`fit_into_width`]: ./struct.Grid.html#method.fit_into_width //! [`GridOptions`]: ./struct.GridOptions.html use std::cmp::max; use std::fmt; use std::iter::repeat_n; use unicode_width::UnicodeWidthStr; fn unicode_width_strip_ansi(astring: &str) -> usize { nu_utils::strip_ansi_unlikely(astring).width() } /// Alignment indicate on which side the content should stick if some filling /// is required. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Alignment { /// The content will stick to the left. Left, /// The content will stick to the right. Right, } /// A **Cell** is the combination of a string and its pre-computed length. /// /// The easiest way to create a Cell is just by using `string.into()`, which /// uses the **unicode width** of the string (see the `unicode_width` crate). /// However, the fields are public, if you wish to provide your own length. #[derive(PartialEq, Eq, Debug, Clone)] pub struct Cell { /// The string to display when this cell gets rendered. pub contents: String, /// The pre-computed length of the string. pub width: Width, /// The side (left/right) to align the content if some filling is required. pub alignment: Alignment, } impl From<String> for Cell { fn from(string: String) -> Self { Self { width: unicode_width_strip_ansi(&string), contents: string, alignment: Alignment::Left, } } } impl<'a> From<&'a str> for Cell { fn from(string: &'a str) -> Self { Self { width: unicode_width_strip_ansi(string), contents: string.into(), alignment: Alignment::Left, } } } /// Direction cells should be written in — either across, or downwards. #[derive(PartialEq, Eq, Debug, Copy, Clone)] pub enum Direction { /// Starts at the top left and moves rightwards, going back to the first /// column for a new row, like a typewriter. LeftToRight, /// Starts at the top left and moves downwards, going back to the first /// row for a new column, like how `ls` lists files by default. TopToBottom, } /// The width of a cell, in columns. pub type Width = usize; /// The text to put in between each pair of columns. /// This does not include any spaces used when aligning cells. #[derive(PartialEq, Eq, Debug)] pub enum Filling { /// A certain number of spaces should be used as the separator. Spaces(Width), /// An arbitrary string. /// `"|"` is a common choice. Text(String), } impl Filling { fn width(&self) -> Width { match *self { Filling::Spaces(w) => w, Filling::Text(ref t) => unicode_width_strip_ansi(&t[..]), } } } /// The user-assignable options for a grid view that should be passed to /// [`Grid::new()`](struct.Grid.html#method.new). #[derive(PartialEq, Eq, Debug)] pub struct GridOptions { /// The direction that the cells should be written in — either /// across, or downwards. pub direction: Direction, /// The number of spaces to put in between each column of cells. pub filling: Filling, } #[derive(PartialEq, Eq, Debug)] struct Dimensions { /// The number of lines in the grid. num_lines: Width, /// The width of each column in the grid. The length of this vector serves /// as the number of columns. widths: Vec<Width>, } impl Dimensions { fn total_width(&self, separator_width: Width) -> Width { if self.widths.is_empty() { 0 } else { let values = self.widths.iter().sum::<Width>(); let separators = separator_width * (self.widths.len() - 1); values + separators } } } /// Everything needed to format the cells with the grid options. /// /// For more information, see the [`grid` crate documentation](index.html). #[derive(Eq, PartialEq, Debug)] pub struct Grid { options: GridOptions, cells: Vec<Cell>, widest_cell_length: Width, width_sum: Width, cell_count: usize, } impl Grid { /// Creates a new grid view with the given options. pub fn new(options: GridOptions) -> Self { let cells = Vec::new(); Self { options, cells, widest_cell_length: 0, width_sum: 0, cell_count: 0, } } /// Reserves space in the vector for the given number of additional cells /// to be added. (See the `Vec::reserve` function.) pub fn reserve(&mut self, additional: usize) { self.cells.reserve(additional) } /// Adds another cell onto the vector. pub fn add(&mut self, cell: Cell) { if cell.width > self.widest_cell_length { self.widest_cell_length = cell.width; } self.width_sum += cell.width; self.cell_count += 1; self.cells.push(cell) } /// Returns a displayable grid that’s been packed to fit into the given /// width in the fewest number of rows. /// /// Returns `None` if any of the cells has a width greater than the /// maximum width. pub fn fit_into_width(&self, maximum_width: Width) -> Option<Display<'_>> { self.width_dimensions(maximum_width).map(|dims| Display { grid: self, dimensions: dims, }) } /// Returns a displayable grid with the given number of columns, and no /// maximum width. pub fn fit_into_columns(&self, num_columns: usize) -> Display<'_> { Display { grid: self, dimensions: self.columns_dimensions(num_columns), } } fn columns_dimensions(&self, num_columns: usize) -> Dimensions { let mut num_lines = self.cells.len() / num_columns; if !self.cells.len().is_multiple_of(num_columns) { num_lines += 1; } self.column_widths(num_lines, num_columns) } fn column_widths(&self, num_lines: usize, num_columns: usize) -> Dimensions { let mut widths: Vec<Width> = repeat_n(0, num_columns).collect(); for (index, cell) in self.cells.iter().enumerate() { let index = match self.options.direction { Direction::LeftToRight => index % num_columns, Direction::TopToBottom => index / num_lines, }; widths[index] = max(widths[index], cell.width); } Dimensions { num_lines, widths } } fn theoretical_max_num_lines(&self, maximum_width: usize) -> usize { let mut theoretical_min_num_cols = 0; let mut col_total_width_so_far = 0; let mut cells = self.cells.clone(); cells.sort_unstable_by(|a, b| b.width.cmp(&a.width)); // Sort in reverse order for cell in &cells { if cell.width + col_total_width_so_far <= maximum_width { theoretical_min_num_cols += 1; col_total_width_so_far += cell.width; } else { let mut theoretical_max_num_lines = self.cell_count / theoretical_min_num_cols; if !self.cell_count.is_multiple_of(theoretical_min_num_cols) { theoretical_max_num_lines += 1; } return theoretical_max_num_lines; } col_total_width_so_far += self.options.filling.width() } // If we make it to this point, we have exhausted all cells before // reaching the maximum width; the theoretical max number of lines // needed to display all cells is 1. 1 } fn width_dimensions(&self, maximum_width: Width) -> Option<Dimensions> { if self.widest_cell_length > maximum_width { // Largest cell is wider than maximum width; it is impossible to fit. return None; } if self.cell_count == 0 { return Some(Dimensions { num_lines: 0, widths: Vec::new(), }); } if self.cell_count == 1 { let the_cell = &self.cells[0]; return Some(Dimensions { num_lines: 1, widths: vec![the_cell.width], }); } let theoretical_max_num_lines = self.theoretical_max_num_lines(maximum_width); if theoretical_max_num_lines == 1 { // This if—statement is necessary for the function to work correctly // for small inputs. return Some(Dimensions { num_lines: 1, // I clone self.cells twice. Once here, and once in // self.theoretical_max_num_lines. Perhaps not the best for // performance? widths: self .cells .clone() .into_iter() .map(|cell| cell.width) .collect(), }); } // Instead of numbers of columns, try to find the fewest number of *lines* // that the output will fit in. let mut smallest_dimensions_yet = None; for num_lines in (1..=theoretical_max_num_lines).rev() { // The number of columns is the number of cells divided by the number // of lines, *rounded up*. let mut num_columns = self.cell_count / num_lines; if !self.cell_count.is_multiple_of(num_lines) { num_columns += 1; } // Early abort: if there are so many columns that the width of the // *column separators* is bigger than the width of the screen, then // don’t even try to tabulate it. // This is actually a necessary check, because the width is stored as // a usize, and making it go negative makes it huge instead, but it // also serves as a speed-up. let total_separator_width = (num_columns - 1) * self.options.filling.width(); if maximum_width < total_separator_width { continue; } // Remove the separator width from the available space. let adjusted_width = maximum_width - total_separator_width; let potential_dimensions = self.column_widths(num_lines, num_columns); if potential_dimensions.widths.iter().sum::<Width>() < adjusted_width { smallest_dimensions_yet = Some(potential_dimensions); } else { return smallest_dimensions_yet; } } None } } /// A displayable representation of a [`Grid`](struct.Grid.html). /// /// This type implements `Display`, so you can get the textual version /// of the grid by calling `.to_string()`. #[derive(Eq, PartialEq, Debug)] pub struct Display<'grid> { /// The grid to display. grid: &'grid Grid, /// The pre-computed column widths for this grid. dimensions: Dimensions, } impl Display<'_> { /// Returns how many columns this display takes up, based on the separator /// width and the number and width of the columns. pub fn width(&self) -> Width { self.dimensions .total_width(self.grid.options.filling.width()) } /// Returns how many rows this display takes up. pub fn row_count(&self) -> usize { self.dimensions.num_lines } /// Returns whether this display takes up as many columns as were allotted /// to it. /// /// It’s possible to construct tables that don’t actually use up all the /// columns that they could, such as when there are more columns than /// cells! In this case, a column would have a width of zero. This just /// checks for that. pub fn is_complete(&self) -> bool { self.dimensions.widths.iter().all(|&x| x > 0) } } impl fmt::Display for Display<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { for y in 0..self.dimensions.num_lines { for x in 0..self.dimensions.widths.len() { let num = match self.grid.options.direction { Direction::LeftToRight => y * self.dimensions.widths.len() + x, Direction::TopToBottom => y + self.dimensions.num_lines * x, }; // Abandon a line mid-way through if that’s where the cells end if num >= self.grid.cells.len() { continue; } let cell = &self.grid.cells[num]; if x == self.dimensions.widths.len() - 1 { match cell.alignment { Alignment::Left => { // The final column doesn’t need to have trailing spaces, // as long as it’s left-aligned. write!(f, "{}", cell.contents)?; } Alignment::Right => { let extra_spaces = self.dimensions.widths[x] - cell.width; write!( f, "{}", pad_string(&cell.contents, extra_spaces, Alignment::Right) )?; } } } else { assert!(self.dimensions.widths[x] >= cell.width); match (&self.grid.options.filling, cell.alignment) { (Filling::Spaces(n), Alignment::Left) => { let extra_spaces = self.dimensions.widths[x] - cell.width + n; write!( f, "{}", pad_string(&cell.contents, extra_spaces, cell.alignment) )?; } (Filling::Spaces(n), Alignment::Right) => { let s = spaces(*n); let extra_spaces = self.dimensions.widths[x] - cell.width; write!( f, "{}{}", pad_string(&cell.contents, extra_spaces, cell.alignment), s )?; } (Filling::Text(t), _) => { let extra_spaces = self.dimensions.widths[x] - cell.width; write!( f, "{}{}", pad_string(&cell.contents, extra_spaces, cell.alignment), t )?; } } } } writeln!(f)?; } Ok(()) } } /// Pad a string with the given number of spaces. fn spaces(length: usize) -> String { " ".repeat(length) } /// Pad a string with the given alignment and number of spaces. /// /// This doesn’t take the width the string *should* be, rather the number /// of spaces to add. fn pad_string(string: &str, padding: usize, alignment: Alignment) -> String { if alignment == Alignment::Left { format!("{}{}", string, spaces(padding)) } else { format!("{}{}", spaces(padding), string) } } #[cfg(test)] mod test { use super::*; #[test] fn no_items() { let grid = Grid::new(GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), }); let display = grid.fit_into_width(40).unwrap(); assert_eq!(display.dimensions.num_lines, 0); assert!(display.dimensions.widths.is_empty()); assert_eq!(display.width(), 0); } #[test] fn one_item() { let mut grid = Grid::new(GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), }); grid.add(Cell::from("1")); let display = grid.fit_into_width(40).unwrap(); assert_eq!(display.dimensions.num_lines, 1); assert_eq!(display.dimensions.widths, vec![1]); assert_eq!(display.width(), 1); } #[test] fn one_item_exact_width() { let mut grid = Grid::new(GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), }); grid.add(Cell::from("1234567890")); let display = grid.fit_into_width(10).unwrap(); assert_eq!(display.dimensions.num_lines, 1); assert_eq!(display.dimensions.widths, vec![10]); assert_eq!(display.width(), 10); } #[test] fn one_item_just_over() { let mut grid = Grid::new(GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), }); grid.add(Cell::from("1234567890!")); assert_eq!(grid.fit_into_width(10), None); } #[test] fn two_small_items() { let mut grid = Grid::new(GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), }); grid.add(Cell::from("1")); grid.add(Cell::from("2")); let display = grid.fit_into_width(40).unwrap(); assert_eq!(display.dimensions.num_lines, 1); assert_eq!(display.dimensions.widths, vec![1, 1]); assert_eq!(display.width(), 1 + 2 + 1); } #[test] fn two_medium_size_items() { let mut grid = Grid::new(GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), }); grid.add(Cell::from("hello there")); grid.add(Cell::from("how are you today?")); let display = grid.fit_into_width(40).unwrap(); assert_eq!(display.dimensions.num_lines, 1); assert_eq!(display.dimensions.widths, vec![11, 18]); assert_eq!(display.width(), 11 + 2 + 18); } #[test] fn two_big_items() { let mut grid = Grid::new(GridOptions { direction: Direction::TopToBottom, filling: Filling::Spaces(2), }); grid.add(Cell::from( "nuihuneihsoenhisenouiuteinhdauisdonhuisudoiosadiuohnteihaosdinhteuieudi", )); grid.add(Cell::from( "oudisnuthasuouneohbueobaugceoduhbsauglcobeuhnaeouosbubaoecgueoubeohubeo", )); assert_eq!(grid.fit_into_width(40), None); } #[test] fn that_example_from_earlier() { let mut grid = Grid::new(GridOptions { filling: Filling::Spaces(1), direction: Direction::LeftToRight, }); for s in &[ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", ] { grid.add(Cell::from(*s)); } let bits = "one two three four\nfive six seven eight\nnine ten eleven twelve\n"; assert_eq!(grid.fit_into_width(24).unwrap().to_string(), bits); assert_eq!(grid.fit_into_width(24).unwrap().row_count(), 3); } #[test] fn number_grid_with_pipe() { let mut grid = Grid::new(GridOptions { filling: Filling::Text("|".into()), direction: Direction::LeftToRight, }); for s in &[ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", ] { grid.add(Cell::from(*s)); } let bits = "one |two|three |four\nfive|six|seven |eight\nnine|ten|eleven|twelve\n"; assert_eq!(grid.fit_into_width(24).unwrap().to_string(), bits); assert_eq!(grid.fit_into_width(24).unwrap().row_count(), 3); } #[test] fn numbers_right() { let mut grid = Grid::new(GridOptions { filling: Filling::Spaces(1), direction: Direction::LeftToRight, }); for s in &[ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", ] { let mut cell = Cell::from(*s); cell.alignment = Alignment::Right; grid.add(cell); } let bits = " one two three four\nfive six seven eight\nnine ten eleven twelve\n"; assert_eq!(grid.fit_into_width(24).unwrap().to_string(), bits); assert_eq!(grid.fit_into_width(24).unwrap().row_count(), 3); } #[test] fn numbers_right_pipe() { let mut grid = Grid::new(GridOptions { filling: Filling::Text("|".into()), direction: Direction::LeftToRight, }); for s in &[ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", ] { let mut cell = Cell::from(*s); cell.alignment = Alignment::Right; grid.add(cell); } let bits = " one|two| three| four\nfive|six| seven| eight\nnine|ten|eleven|twelve\n"; assert_eq!(grid.fit_into_width(24).unwrap().to_string(), bits); assert_eq!(grid.fit_into_width(24).unwrap().row_count(), 3); } #[test] fn huge_separator() { let mut grid = Grid::new(GridOptions { filling: Filling::Spaces(100), direction: Direction::LeftToRight, }); grid.add("a".into()); grid.add("b".into()); assert_eq!(grid.fit_into_width(99), None); } #[test] fn huge_yet_unused_separator() { let mut grid = Grid::new(GridOptions { filling: Filling::Spaces(100), direction: Direction::LeftToRight, }); grid.add("abcd".into()); let display = grid.fit_into_width(99).unwrap(); assert_eq!(display.dimensions.num_lines, 1); assert_eq!(display.dimensions.widths, vec![4]); assert_eq!(display.width(), 4); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-term-grid/examples/grid_demo.rs
crates/nu-term-grid/examples/grid_demo.rs
use nu_term_grid::grid::{Alignment, Cell, Direction, Filling, Grid, GridOptions}; // This produces: // // 1 | 128 | 16384 | 2097152 | 268435456 | 34359738368 | 4398046511104 // 2 | 256 | 32768 | 4194304 | 536870912 | 68719476736 | 8796093022208 // 4 | 512 | 65536 | 8388608 | 1073741824 | 137438953472 | 17592186044416 // 8 | 1024 | 131072 | 16777216 | 2147483648 | 274877906944 | 35184372088832 // 16 | 2048 | 262144 | 33554432 | 4294967296 | 549755813888 | 70368744177664 // 32 | 4096 | 524288 | 67108864 | 8589934592 | 1099511627776 | 140737488355328 // 64 | 8192 | 1048576 | 134217728 | 17179869184 | 2199023255552 | fn main() { let mut grid = Grid::new(GridOptions { direction: Direction::TopToBottom, filling: Filling::Text(" | ".into()), }); for i in 0..48 { let mut cell = Cell::from(format!("{}", 2_isize.pow(i))); cell.alignment = Alignment::Right; grid.add(cell) } if let Some(grid_display) = grid.fit_into_width(80) { println!("{grid_display}"); } else { println!("Couldn't fit grid into 80 columns!"); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-utils/src/lib.rs
crates/nu-utils/src/lib.rs
#![doc = include_str!("../README.md")] mod casing; mod deansi; pub mod emoji; pub mod filesystem; pub mod flatten_json; pub mod float; pub mod locale; mod multilife; mod nu_cow; mod quoting; mod shared_cow; mod split_read; pub mod strings; pub mod utils; pub use locale::get_system_locale; pub use utils::{ ConfigFileKind, enable_vt_processing, get_ls_colors, stderr_write_all_and_flush, stdout_write_all_and_flush, terminal_size, }; pub use casing::IgnoreCaseExt; pub use deansi::{ strip_ansi_likely, strip_ansi_string_likely, strip_ansi_string_unlikely, strip_ansi_unlikely, }; pub use emoji::contains_emoji; pub use flatten_json::JsonFlattener; pub use float::ObviousFloat; pub use multilife::MultiLife; pub use nu_cow::NuCow; pub use quoting::{escape_quote_string, needs_quoting}; pub use shared_cow::SharedCow; pub use split_read::SplitRead; #[cfg(unix)] pub use filesystem::users;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-utils/src/multilife.rs
crates/nu-utils/src/multilife.rs
use std::ops::Deref; pub enum MultiLife<'out, 'local, T> where 'out: 'local, T: ?Sized, { Out(&'out T), Local(&'local T), } impl<'out, 'local, T> Deref for MultiLife<'out, 'local, T> where 'out: 'local, T: ?Sized, { type Target = T; fn deref(&self) -> &Self::Target { match *self { MultiLife::Out(x) => x, MultiLife::Local(x) => x, } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-utils/src/filesystem.rs
crates/nu-utils/src/filesystem.rs
#[cfg(unix)] use nix::unistd::{AccessFlags, access}; #[cfg(any(windows, unix))] use std::path::Path; // The result of checking whether we have permission to cd to a directory #[derive(Debug)] pub enum PermissionResult { PermissionOk, PermissionDenied, } // TODO: Maybe we should use file_attributes() from https://doc.rust-lang.org/std/os/windows/fs/trait.MetadataExt.html // More on that here: https://learn.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants #[cfg(windows)] pub fn have_permission(dir: impl AsRef<Path>) -> PermissionResult { match dir.as_ref().read_dir() { Err(e) => { if matches!(e.kind(), std::io::ErrorKind::PermissionDenied) { PermissionResult::PermissionDenied } else { PermissionResult::PermissionOk } } Ok(_) => PermissionResult::PermissionOk, } } #[cfg(unix)] /// Check that the process' user id has permissions to execute or /// in the case of a directory traverse the particular directory pub fn have_permission(dir: impl AsRef<Path>) -> PermissionResult { // We check permissions for real user id, but that's fine, because in // proper installations of nushell, effective UID (EUID) rarely differs // from real UID (RUID). We strongly advise against setting the setuid bit // on the nushell executable or shebang scripts starts with `#!/usr/bin/env nu` e.g. // Most Unix systems ignore setuid on shebang by default anyway. access(dir.as_ref(), AccessFlags::X_OK).into() } #[cfg(unix)] pub mod users { use nix::unistd::{Gid, Group, Uid, User}; pub fn get_user_by_uid(uid: Uid) -> Option<User> { User::from_uid(uid).ok().flatten() } pub fn get_group_by_gid(gid: Gid) -> Option<Group> { Group::from_gid(gid).ok().flatten() } pub fn get_current_uid() -> Uid { Uid::current() } pub fn get_current_gid() -> Gid { Gid::current() } #[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "android")))] pub fn get_current_username() -> Option<String> { get_user_by_uid(get_current_uid()).map(|user| user.name) } #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "android"))] pub fn current_user_groups() -> Option<Vec<Gid>> { if let Ok(mut groups) = nix::unistd::getgroups() { groups.sort_unstable_by_key(|id| id.as_raw()); groups.dedup(); Some(groups) } else { None } } /// Returns groups for a provided user name and primary group id. /// /// # libc functions used /// /// - [`getgrouplist`](https://docs.rs/libc/*/libc/fn.getgrouplist.html) /// /// # Examples /// /// ```ignore /// use users::get_user_groups; /// /// for group in get_user_groups("stevedore", 1001).expect("Error looking up groups") { /// println!("User is a member of group #{group}"); /// } /// ``` #[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "android")))] pub fn get_user_groups(username: &str, gid: Gid) -> Option<Vec<Gid>> { use nix::libc::{c_int, gid_t}; use std::ffi::CString; // MacOS uses i32 instead of gid_t in getgrouplist for unknown reasons #[cfg(target_os = "macos")] let mut buff: Vec<i32> = vec![0; 1024]; #[cfg(not(target_os = "macos"))] let mut buff: Vec<gid_t> = vec![0; 1024]; let name = CString::new(username).ok()?; let mut count = buff.len() as c_int; // MacOS uses i32 instead of gid_t in getgrouplist for unknown reasons // SAFETY: // int getgrouplist(const char *user, gid_t group, gid_t *groups, int *ngroups); // // `name` is valid CStr to be `const char*` for `user` // every valid value will be accepted for `group` // The capacity for `*groups` is passed in as `*ngroups` which is the buffer max length/capacity (as we initialize with 0) // Following reads from `*groups`/`buff` will only happen after `buff.truncate(*ngroups)` #[cfg(target_os = "macos")] let res = unsafe { nix::libc::getgrouplist( name.as_ptr(), gid.as_raw() as i32, buff.as_mut_ptr(), &mut count, ) }; #[cfg(not(target_os = "macos"))] let res = unsafe { nix::libc::getgrouplist(name.as_ptr(), gid.as_raw(), buff.as_mut_ptr(), &mut count) }; if res < 0 { None } else { buff.truncate(count as usize); buff.sort_unstable(); buff.dedup(); // allow trivial cast: on macos i is i32, on linux it's already gid_t #[allow(trivial_numeric_casts)] Some( buff.into_iter() .map(|id| Gid::from_raw(id as gid_t)) .filter_map(get_group_by_gid) .map(|group| group.gid) .collect(), ) } } } impl<T, E> From<Result<T, E>> for PermissionResult { fn from(value: Result<T, E>) -> Self { match value { Ok(_) => Self::PermissionOk, Err(_) => Self::PermissionDenied, } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-utils/src/nu_cow.rs
crates/nu-utils/src/nu_cow.rs
use std::fmt::Debug; use serde::{Deserialize, Serialize}; #[derive(Serialize)] #[serde(untagged)] #[allow(dead_code)] pub enum NuCow<B, O> { Borrowed(B), Owned(O), } impl<B, O> PartialEq for NuCow<B, O> where O: std::cmp::PartialEq<O>, B: std::cmp::PartialEq<B>, O: std::cmp::PartialEq<B>, { fn eq(&self, other: &Self) -> bool { match (&self, &other) { (NuCow::Owned(o), NuCow::Borrowed(b)) | (NuCow::Borrowed(b), NuCow::Owned(o)) => o == b, (NuCow::Borrowed(lhs), NuCow::Borrowed(rhs)) => lhs == rhs, (NuCow::Owned(lhs), NuCow::Owned(rhs)) => lhs == rhs, } } } impl<B, O> Debug for NuCow<B, O> where B: Debug, O: Debug, { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if f.alternate() { match self { Self::Borrowed(b) => f.debug_tuple("Borrowed").field(b).finish(), Self::Owned(o) => f.debug_tuple("Owned").field(o).finish(), } } else { match self { Self::Borrowed(b) => <B as Debug>::fmt(b, f), Self::Owned(o) => <O as Debug>::fmt(o, f), } } } } impl<B, O> Clone for NuCow<B, O> where B: Clone, O: Clone, { fn clone(&self) -> Self { match self { Self::Borrowed(b) => Self::Borrowed(b.clone()), Self::Owned(o) => Self::Owned(o.clone()), } } } impl<'de, B, O> Deserialize<'de> for NuCow<B, O> where O: Deserialize<'de>, { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { <O as Deserialize>::deserialize(deserializer).map(Self::Owned) } } #[cfg(test)] mod tests { use super::*; #[test] fn static_to_dynamic_roundtrip() { type Strings = NuCow<&'static [&'static str], Vec<String>>; let src = ["hello", "world", "!"].as_slice(); let json = serde_json::to_string(&Strings::Borrowed(src)).unwrap(); let dst: Strings = serde_json::from_str(&json).unwrap(); let Strings::Owned(dst) = dst else { panic!("Expected Owned variant"); }; for (&s, d) in src.iter().zip(&dst) { assert_eq!(s, d.as_str()) } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-utils/src/utils.rs
crates/nu-utils/src/utils.rs
#[cfg(windows)] use crossterm_winapi::{ConsoleMode, Handle}; use lscolors::LsColors; use std::{ fmt::Display, io::{self, Result, Write}, }; pub fn enable_vt_processing() -> Result<()> { #[cfg(windows)] { let console_out_mode = ConsoleMode::from(Handle::current_out_handle()?); let old_out_mode = console_out_mode.mode()?; let console_in_mode = ConsoleMode::from(Handle::current_in_handle()?); let old_in_mode = console_in_mode.mode()?; enable_vt_processing_input(console_in_mode, old_in_mode)?; enable_vt_processing_output(console_out_mode, old_out_mode)?; } Ok(()) } #[cfg(windows)] fn enable_vt_processing_input(console_in_mode: ConsoleMode, mode: u32) -> Result<()> { // // Input Mode flags: // // #define ENABLE_PROCESSED_INPUT 0x0001 // #define ENABLE_LINE_INPUT 0x0002 // #define ENABLE_ECHO_INPUT 0x0004 // #define ENABLE_WINDOW_INPUT 0x0008 // #define ENABLE_MOUSE_INPUT 0x0010 // #define ENABLE_INSERT_MODE 0x0020 // #define ENABLE_QUICK_EDIT_MODE 0x0040 // #define ENABLE_EXTENDED_FLAGS 0x0080 // #define ENABLE_AUTO_POSITION 0x0100 // #define ENABLE_VIRTUAL_TERMINAL_INPUT 0x0200 const ENABLE_PROCESSED_INPUT: u32 = 0x0001; const ENABLE_LINE_INPUT: u32 = 0x0002; const ENABLE_ECHO_INPUT: u32 = 0x0004; const ENABLE_VIRTUAL_TERMINAL_INPUT: u32 = 0x0200; console_in_mode.set_mode( mode | ENABLE_VIRTUAL_TERMINAL_INPUT & ENABLE_ECHO_INPUT & ENABLE_LINE_INPUT & ENABLE_PROCESSED_INPUT, ) } #[cfg(windows)] fn enable_vt_processing_output(console_out_mode: ConsoleMode, mode: u32) -> Result<()> { // // Output Mode flags: // // #define ENABLE_PROCESSED_OUTPUT 0x0001 // #define ENABLE_WRAP_AT_EOL_OUTPUT 0x0002 // #define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004 // #define DISABLE_NEWLINE_AUTO_RETURN 0x0008 // #define ENABLE_LVB_GRID_WORLDWIDE 0x0010 pub const ENABLE_PROCESSED_OUTPUT: u32 = 0x0001; pub const ENABLE_VIRTUAL_TERMINAL_PROCESSING: u32 = 0x0004; console_out_mode.set_mode(mode | ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING) } pub fn stdout_write_all_and_flush<T>(output: T) -> Result<()> where T: AsRef<[u8]>, { let stdout = std::io::stdout(); stdout.lock().write_all(output.as_ref())?; stdout.lock().flush() } pub fn stderr_write_all_and_flush<T>(output: T) -> Result<()> where T: AsRef<[u8]>, { let stderr = std::io::stderr(); match stderr.lock().write_all(output.as_ref()) { Ok(_) => Ok(stderr.lock().flush()?), Err(err) => Err(err), } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ConfigFileKind { Config, Env, } // See default_files/README.md for a description of these files impl ConfigFileKind { pub const fn default(self) -> &'static str { match self { Self::Config => include_str!("default_files/default_config.nu"), Self::Env => include_str!("default_files/default_env.nu"), } } pub const fn scaffold(self) -> &'static str { match self { Self::Config => include_str!("default_files/scaffold_config.nu"), Self::Env => include_str!("default_files/scaffold_env.nu"), } } pub const fn doc(self) -> &'static str { match self { Self::Config => include_str!("default_files/doc_config.nu"), Self::Env => include_str!("default_files/doc_env.nu"), } } pub const fn name(self) -> &'static str { match self { ConfigFileKind::Config => "Config", ConfigFileKind::Env => "Environment config", } } pub const fn path(self) -> &'static str { match self { ConfigFileKind::Config => "config.nu", ConfigFileKind::Env => "env.nu", } } pub const fn default_path(self) -> &'static str { match self { ConfigFileKind::Config => "default_config.nu", ConfigFileKind::Env => "default_env.nu", } } pub const fn nu_const_path(self) -> &'static str { match self { ConfigFileKind::Config => "config-path", ConfigFileKind::Env => "env-path", } } } impl Display for ConfigFileKind { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.name()) } } pub fn get_ls_colors(lscolors_env_string: Option<String>) -> LsColors { if let Some(s) = lscolors_env_string { LsColors::from_string(&s) } else { LsColors::from_string( &[ "st=0", "di=0;38;5;81", "so=0;38;5;16;48;5;203", "ln=0;38;5;203", "cd=0;38;5;203;48;5;236", "ex=1;38;5;203", "or=0;38;5;16;48;5;203", "fi=0", "bd=0;38;5;81;48;5;236", "ow=0", "mi=0;38;5;16;48;5;203", "*~=0;38;5;243", "no=0", "tw=0", "pi=0;38;5;16;48;5;81", "*.z=4;38;5;203", "*.t=0;38;5;48", "*.o=0;38;5;243", "*.d=0;38;5;48", "*.a=1;38;5;203", "*.c=0;38;5;48", "*.m=0;38;5;48", "*.p=0;38;5;48", "*.r=0;38;5;48", "*.h=0;38;5;48", "*.ml=0;38;5;48", "*.ll=0;38;5;48", "*.gv=0;38;5;48", "*.cp=0;38;5;48", "*.xz=4;38;5;203", "*.hs=0;38;5;48", "*css=0;38;5;48", "*.ui=0;38;5;149", "*.pl=0;38;5;48", "*.ts=0;38;5;48", "*.gz=4;38;5;203", "*.so=1;38;5;203", "*.cr=0;38;5;48", "*.fs=0;38;5;48", "*.bz=4;38;5;203", "*.ko=1;38;5;203", "*.as=0;38;5;48", "*.sh=0;38;5;48", "*.pp=0;38;5;48", "*.el=0;38;5;48", "*.py=0;38;5;48", "*.lo=0;38;5;243", "*.bc=0;38;5;243", "*.cc=0;38;5;48", "*.pm=0;38;5;48", "*.rs=0;38;5;48", "*.di=0;38;5;48", "*.jl=0;38;5;48", "*.rb=0;38;5;48", "*.md=0;38;5;185", "*.js=0;38;5;48", "*.cjs=0;38;5;48", "*.mjs=0;38;5;48", "*.go=0;38;5;48", "*.vb=0;38;5;48", "*.hi=0;38;5;243", "*.kt=0;38;5;48", "*.hh=0;38;5;48", "*.cs=0;38;5;48", "*.mn=0;38;5;48", "*.nb=0;38;5;48", "*.7z=4;38;5;203", "*.ex=0;38;5;48", "*.rm=0;38;5;208", "*.ps=0;38;5;186", "*.td=0;38;5;48", "*.la=0;38;5;243", "*.aux=0;38;5;243", "*.xmp=0;38;5;149", "*.mp4=0;38;5;208", "*.rpm=4;38;5;203", "*.m4a=0;38;5;208", "*.zip=4;38;5;203", "*.dll=1;38;5;203", "*.bcf=0;38;5;243", "*.awk=0;38;5;48", "*.aif=0;38;5;208", "*.zst=4;38;5;203", "*.bak=0;38;5;243", "*.tgz=4;38;5;203", "*.com=1;38;5;203", "*.clj=0;38;5;48", "*.sxw=0;38;5;186", "*.vob=0;38;5;208", "*.fsx=0;38;5;48", "*.doc=0;38;5;186", "*.mkv=0;38;5;208", "*.tbz=4;38;5;203", "*.ogg=0;38;5;208", "*.wma=0;38;5;208", "*.mid=0;38;5;208", "*.kex=0;38;5;186", "*.out=0;38;5;243", "*.ltx=0;38;5;48", "*.sql=0;38;5;48", "*.ppt=0;38;5;186", "*.tex=0;38;5;48", "*.odp=0;38;5;186", "*.log=0;38;5;243", "*.arj=4;38;5;203", "*.ipp=0;38;5;48", "*.sbt=0;38;5;48", "*.jpg=0;38;5;208", "*.yml=0;38;5;149", "*.txt=0;38;5;185", "*.csv=0;38;5;185", "*.dox=0;38;5;149", "*.pro=0;38;5;149", "*.bst=0;38;5;149", "*TODO=1", "*.mir=0;38;5;48", "*.bat=1;38;5;203", "*.m4v=0;38;5;208", "*.pod=0;38;5;48", "*.cfg=0;38;5;149", "*.pas=0;38;5;48", "*.tml=0;38;5;149", "*.bib=0;38;5;149", "*.ini=0;38;5;149", "*.apk=4;38;5;203", "*.h++=0;38;5;48", "*.pyc=0;38;5;243", "*.img=4;38;5;203", "*.rst=0;38;5;185", "*.swf=0;38;5;208", "*.htm=0;38;5;185", "*.ttf=0;38;5;208", "*.elm=0;38;5;48", "*hgrc=0;38;5;149", "*.bmp=0;38;5;208", "*.fsi=0;38;5;48", "*.pgm=0;38;5;208", "*.dpr=0;38;5;48", "*.xls=0;38;5;186", "*.tcl=0;38;5;48", "*.mli=0;38;5;48", "*.ppm=0;38;5;208", "*.bbl=0;38;5;243", "*.lua=0;38;5;48", "*.asa=0;38;5;48", "*.pbm=0;38;5;208", "*.avi=0;38;5;208", "*.def=0;38;5;48", "*.mov=0;38;5;208", "*.hxx=0;38;5;48", "*.tif=0;38;5;208", "*.fon=0;38;5;208", "*.zsh=0;38;5;48", "*.png=0;38;5;208", "*.inc=0;38;5;48", "*.jar=4;38;5;203", "*.swp=0;38;5;243", "*.pid=0;38;5;243", "*.gif=0;38;5;208", "*.ind=0;38;5;243", "*.erl=0;38;5;48", "*.ilg=0;38;5;243", "*.eps=0;38;5;208", "*.tsx=0;38;5;48", "*.git=0;38;5;243", "*.inl=0;38;5;48", "*.rtf=0;38;5;186", "*.hpp=0;38;5;48", "*.kts=0;38;5;48", "*.deb=4;38;5;203", "*.svg=0;38;5;208", "*.pps=0;38;5;186", "*.ps1=0;38;5;48", "*.c++=0;38;5;48", "*.cpp=0;38;5;48", "*.bsh=0;38;5;48", "*.php=0;38;5;48", "*.exs=0;38;5;48", "*.toc=0;38;5;243", "*.mp3=0;38;5;208", "*.epp=0;38;5;48", "*.rar=4;38;5;203", "*.wav=0;38;5;208", "*.xlr=0;38;5;186", "*.tmp=0;38;5;243", "*.cxx=0;38;5;48", "*.iso=4;38;5;203", "*.dmg=4;38;5;203", "*.gvy=0;38;5;48", "*.bin=4;38;5;203", "*.wmv=0;38;5;208", "*.blg=0;38;5;243", "*.ods=0;38;5;186", "*.psd=0;38;5;208", "*.mpg=0;38;5;208", "*.dot=0;38;5;48", "*.cgi=0;38;5;48", "*.xml=0;38;5;185", "*.htc=0;38;5;48", "*.ics=0;38;5;186", "*.bz2=4;38;5;203", "*.tar=4;38;5;203", "*.csx=0;38;5;48", "*.ico=0;38;5;208", "*.sxi=0;38;5;186", "*.nix=0;38;5;149", "*.pkg=4;38;5;203", "*.bag=4;38;5;203", "*.fnt=0;38;5;208", "*.idx=0;38;5;243", "*.xcf=0;38;5;208", "*.exe=1;38;5;203", "*.flv=0;38;5;208", "*.fls=0;38;5;243", "*.otf=0;38;5;208", "*.vcd=4;38;5;203", "*.vim=0;38;5;48", "*.sty=0;38;5;243", "*.pdf=0;38;5;186", "*.odt=0;38;5;186", "*.purs=0;38;5;48", "*.h264=0;38;5;208", "*.jpeg=0;38;5;208", "*.dart=0;38;5;48", "*.pptx=0;38;5;186", "*.lock=0;38;5;243", "*.bash=0;38;5;48", "*.rlib=0;38;5;243", "*.hgrc=0;38;5;149", "*.psm1=0;38;5;48", "*.toml=0;38;5;149", "*.tbz2=4;38;5;203", "*.yaml=0;38;5;149", "*.make=0;38;5;149", "*.orig=0;38;5;243", "*.html=0;38;5;185", "*.fish=0;38;5;48", "*.diff=0;38;5;48", "*.xlsx=0;38;5;186", "*.docx=0;38;5;186", "*.json=0;38;5;149", "*.psd1=0;38;5;48", "*.tiff=0;38;5;208", "*.flac=0;38;5;208", "*.java=0;38;5;48", "*.less=0;38;5;48", "*.mpeg=0;38;5;208", "*.conf=0;38;5;149", "*.lisp=0;38;5;48", "*.epub=0;38;5;186", "*.cabal=0;38;5;48", "*.patch=0;38;5;48", "*.shtml=0;38;5;185", "*.class=0;38;5;243", "*.xhtml=0;38;5;185", "*.mdown=0;38;5;185", "*.dyn_o=0;38;5;243", "*.cache=0;38;5;243", "*.swift=0;38;5;48", "*README=0;38;5;16;48;5;186", "*passwd=0;38;5;149", "*.ipynb=0;38;5;48", "*shadow=0;38;5;149", "*.toast=4;38;5;203", "*.cmake=0;38;5;149", "*.scala=0;38;5;48", "*.dyn_hi=0;38;5;243", "*.matlab=0;38;5;48", "*.config=0;38;5;149", "*.gradle=0;38;5;48", "*.groovy=0;38;5;48", "*.ignore=0;38;5;149", "*LICENSE=0;38;5;249", "*TODO.md=1", "*COPYING=0;38;5;249", "*.flake8=0;38;5;149", "*INSTALL=0;38;5;16;48;5;186", "*setup.py=0;38;5;149", "*.gemspec=0;38;5;149", "*.desktop=0;38;5;149", "*Makefile=0;38;5;149", "*Doxyfile=0;38;5;149", "*TODO.txt=1", "*README.md=0;38;5;16;48;5;186", "*.kdevelop=0;38;5;149", "*.rgignore=0;38;5;149", "*configure=0;38;5;149", "*.DS_Store=0;38;5;243", "*.fdignore=0;38;5;149", "*COPYRIGHT=0;38;5;249", "*.markdown=0;38;5;185", "*.cmake.in=0;38;5;149", "*.gitconfig=0;38;5;149", "*INSTALL.md=0;38;5;16;48;5;186", "*CODEOWNERS=0;38;5;149", "*.gitignore=0;38;5;149", "*Dockerfile=0;38;5;149", "*SConstruct=0;38;5;149", "*.scons_opt=0;38;5;243", "*README.txt=0;38;5;16;48;5;186", "*SConscript=0;38;5;149", "*.localized=0;38;5;243", "*.travis.yml=0;38;5;186", "*Makefile.in=0;38;5;243", "*.gitmodules=0;38;5;149", "*LICENSE-MIT=0;38;5;249", "*Makefile.am=0;38;5;149", "*INSTALL.txt=0;38;5;16;48;5;186", "*MANIFEST.in=0;38;5;149", "*.synctex.gz=0;38;5;243", "*.fdb_latexmk=0;38;5;243", "*CONTRIBUTORS=0;38;5;16;48;5;186", "*configure.ac=0;38;5;149", "*.applescript=0;38;5;48", "*appveyor.yml=0;38;5;186", "*.clang-format=0;38;5;149", "*.gitattributes=0;38;5;149", "*LICENSE-APACHE=0;38;5;249", "*CMakeCache.txt=0;38;5;243", "*CMakeLists.txt=0;38;5;149", "*CONTRIBUTORS.md=0;38;5;16;48;5;186", "*requirements.txt=0;38;5;149", "*CONTRIBUTORS.txt=0;38;5;16;48;5;186", "*.sconsign.dblite=0;38;5;243", "*package-lock.json=0;38;5;243", "*.CFUserTextEncoding=0;38;5;243", "*.fb2=0;38;5;186", ] .join(":"), ) } } // Log some performance metrics (green text with yellow timings) #[macro_export] macro_rules! perf { ($msg:expr, $dur:expr, $use_color:expr) => { if $use_color { log::info!( "perf: {}:{}:{} \x1b[32m{}\x1b[0m took \x1b[33m{:?}\x1b[0m", file!(), line!(), column!(), $msg, $dur.elapsed(), ); } else { log::info!( "perf: {}:{}:{} {} took {:?}", file!(), line!(), column!(), $msg, $dur.elapsed(), ); } }; } /// Returns the terminal size (columns, rows). /// /// This utility variant allows getting a fallback value when compiling for wasm32 without having /// to rearrange other bits of the codebase. /// /// See [`crossterm::terminal::size`]. pub fn terminal_size() -> io::Result<(u16, u16)> { #[cfg(feature = "os")] return crossterm::terminal::size(); #[cfg(not(feature = "os"))] return Err(io::Error::from(io::ErrorKind::Unsupported)); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-utils/src/emoji.rs
crates/nu-utils/src/emoji.rs
pub fn contains_emoji(val: &str) -> bool { // Let's do some special handling for emojis const ZERO_WIDTH_JOINER: &str = "\u{200d}"; const VARIATION_SELECTOR_16: &str = "\u{fe0f}"; const SKIN_TONES: [&str; 5] = [ "\u{1f3fb}", // Light Skin Tone "\u{1f3fc}", // Medium-Light Skin Tone "\u{1f3fd}", // Medium Skin Tone "\u{1f3fe}", // Medium-Dark Skin Tone "\u{1f3ff}", // Dark Skin Tone ]; val.contains(ZERO_WIDTH_JOINER) || val.contains(VARIATION_SELECTOR_16) || SKIN_TONES.iter().any(|skin_tone| val.contains(skin_tone)) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-utils/src/shared_cow.rs
crates/nu-utils/src/shared_cow.rs
use serde::{Deserialize, Serialize}; use std::{fmt, ops, sync::Arc}; /// A container that transparently shares a value when possible, but clones on mutate. /// /// Unlike `Arc`, this is only intended to help save memory usage and reduce the amount of effort /// required to clone unmodified values with easy to use copy-on-write. /// /// This should more or less reflect the API of [`std::borrow::Cow`] as much as is sensible. #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] #[repr(transparent)] pub struct SharedCow<T: Clone>(Arc<T>); impl<T: Clone> SharedCow<T> { /// Create a new `Shared` value. pub fn new(value: T) -> SharedCow<T> { SharedCow(Arc::new(value)) } /// Take an exclusive clone of the shared value, or move and take ownership if it wasn't shared. pub fn into_owned(self: SharedCow<T>) -> T { // Optimized: if the Arc is not shared, just unwraps the Arc match Arc::try_unwrap(self.0) { Ok(value) => value, Err(arc) => (*arc).clone(), } } /// Get a mutable reference to the value inside the [`SharedCow`]. This will result in a clone /// being created only if the value was shared with multiple references. pub fn to_mut(&mut self) -> &mut T { Arc::make_mut(&mut self.0) } /// Convert the `Shared` value into an `Arc` pub fn into_arc(value: SharedCow<T>) -> Arc<T> { value.0 } /// Return the number of references to the shared value. pub fn ref_count(value: &SharedCow<T>) -> usize { Arc::strong_count(&value.0) } } impl<T> From<T> for SharedCow<T> where T: Clone, { fn from(value: T) -> Self { SharedCow::new(value) } } impl<T> From<Arc<T>> for SharedCow<T> where T: Clone, { fn from(value: Arc<T>) -> Self { SharedCow(value) } } impl<T> fmt::Debug for SharedCow<T> where T: fmt::Debug + Clone, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // Appears transparent (*self.0).fmt(f) } } impl<T> fmt::Display for SharedCow<T> where T: fmt::Display + Clone, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { (*self.0).fmt(f) } } impl<T: Clone> Serialize for SharedCow<T> where T: Serialize, { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { self.0.serialize(serializer) } } impl<'de, T: Clone> Deserialize<'de> for SharedCow<T> where T: Deserialize<'de>, { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { T::deserialize(deserializer).map(Arc::new).map(SharedCow) } } impl<T: Clone> ops::Deref for SharedCow<T> { type Target = T; fn deref(&self) -> &Self::Target { &self.0 } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-utils/src/float.rs
crates/nu-utils/src/float.rs
use std::fmt::{Display, LowerExp}; /// A f64 wrapper that formats whole numbers with a decimal point. pub struct ObviousFloat(pub f64); impl Display for ObviousFloat { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let val = self.0; if val.fract() == 0.0 { write!(f, "{val:.1}") } else { Display::fmt(&val, f) } } } impl LowerExp for ObviousFloat { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { LowerExp::fmt(&self.0, f) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-utils/src/casing.rs
crates/nu-utils/src/casing.rs
use std::cmp::Ordering; use unicase::UniCase; pub trait IgnoreCaseExt { /// Returns a [case folded] equivalent of this string, as a new String. /// /// Case folding is primarily based on lowercase mapping, but includes /// additional changes to the source text to help make case folding /// language-invariant and consistent. Case folded text should be used /// solely for processing and generally should not be stored or displayed. /// /// [case folded]: <https://unicode.org/faq/casemap_charprop.html#2> fn to_folded_case(&self) -> String; /// Checks that two strings are a case-insensitive match. /// /// Essentially `to_folded_case(a) == to_folded_case(b)`, but without /// allocating and copying string temporaries. Because case folding involves /// Unicode table lookups, it can sometimes be more efficient to use /// `to_folded_case` to case fold once and then compare those strings. fn eq_ignore_case(&self, other: &str) -> bool; /// Compares two strings case-insensitively. /// /// Essentially `to_folded_case(a) == to_folded_case(b)`, but without /// allocating and copying string temporaries. Because case folding involves /// Unicode table lookups, it can sometimes be more efficient to use /// `to_folded_case` to case fold once and then compare those strings. /// /// Note that this *only* ignores case, comparing the folded strings without /// any other collation data or locale, so the sort order may be surprising /// outside of ASCII characters. fn cmp_ignore_case(&self, other: &str) -> Ordering; } impl IgnoreCaseExt for str { fn to_folded_case(&self) -> String { UniCase::new(self).to_folded_case() } fn eq_ignore_case(&self, other: &str) -> bool { UniCase::new(self) == UniCase::new(other) } fn cmp_ignore_case(&self, other: &str) -> Ordering { UniCase::new(self).cmp(&UniCase::new(other)) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-utils/src/split_read.rs
crates/nu-utils/src/split_read.rs
use std::io::{BufRead, ErrorKind}; use memchr::memmem::Finder; pub struct SplitRead<R> { reader: Option<R>, buf: Option<Vec<u8>>, finder: Finder<'static>, } impl<R: BufRead> SplitRead<R> { pub fn new(reader: R, delim: impl AsRef<[u8]>) -> Self { // empty delimiter results in an infinite stream of empty items debug_assert!(!delim.as_ref().is_empty(), "delimiter can't be empty"); Self { reader: Some(reader), buf: Some(Vec::new()), finder: Finder::new(delim.as_ref()).into_owned(), } } } impl<R: BufRead> Iterator for SplitRead<R> { type Item = Result<Vec<u8>, std::io::Error>; fn next(&mut self) -> Option<Self::Item> { let buf = self.buf.as_mut()?; let mut search_start = 0usize; loop { if let Some(i) = self.finder.find(&buf[search_start..]) { let needle_idx = search_start + i; let right = buf.split_off(needle_idx + self.finder.needle().len()); buf.truncate(needle_idx); let left = std::mem::replace(buf, right); return Some(Ok(left)); } if let Some(mut r) = self.reader.take() { search_start = buf.len().saturating_sub(self.finder.needle().len() + 1); let available = match r.fill_buf() { Ok(n) => n, Err(ref e) if e.kind() == ErrorKind::Interrupted => continue, Err(e) => return Some(Err(e)), }; buf.extend_from_slice(available); let used = available.len(); r.consume(used); if used != 0 { self.reader = Some(r); } continue; } else { return self.buf.take().map(Ok); } } } } #[cfg(test)] mod tests { use super::*; use std::io::{self, Cursor, Read}; #[test] fn simple() { let s = "foo-bar-baz"; let cursor = Cursor::new(String::from(s)); let mut split = SplitRead::new(cursor, "-").map(|r| String::from_utf8(r.unwrap()).unwrap()); assert_eq!(split.next().as_deref(), Some("foo")); assert_eq!(split.next().as_deref(), Some("bar")); assert_eq!(split.next().as_deref(), Some("baz")); assert_eq!(split.next(), None); } #[test] fn with_empty_fields() -> Result<(), io::Error> { let s = "\0\0foo\0\0bar\0\0\0\0baz\0\0"; let cursor = Cursor::new(String::from(s)); let mut split = SplitRead::new(cursor, "\0\0").map(|r| String::from_utf8(r.unwrap()).unwrap()); assert_eq!(split.next().as_deref(), Some("")); assert_eq!(split.next().as_deref(), Some("foo")); assert_eq!(split.next().as_deref(), Some("bar")); assert_eq!(split.next().as_deref(), Some("")); assert_eq!(split.next().as_deref(), Some("baz")); assert_eq!(split.next().as_deref(), Some("")); assert_eq!(split.next().as_deref(), None); Ok(()) } #[test] fn complex_delimiter() -> Result<(), io::Error> { let s = "<|>foo<|>bar<|><|>baz<|>"; let cursor = Cursor::new(String::from(s)); let mut split = SplitRead::new(cursor, "<|>").map(|r| String::from_utf8(r.unwrap()).unwrap()); assert_eq!(split.next().as_deref(), Some("")); assert_eq!(split.next().as_deref(), Some("foo")); assert_eq!(split.next().as_deref(), Some("bar")); assert_eq!(split.next().as_deref(), Some("")); assert_eq!(split.next().as_deref(), Some("baz")); assert_eq!(split.next().as_deref(), Some("")); assert_eq!(split.next().as_deref(), None); Ok(()) } #[test] fn all_empty() -> Result<(), io::Error> { let s = "<><>"; let cursor = Cursor::new(String::from(s)); let mut split = SplitRead::new(cursor, "<>").map(|r| String::from_utf8(r.unwrap()).unwrap()); assert_eq!(split.next().as_deref(), Some("")); assert_eq!(split.next().as_deref(), Some("")); assert_eq!(split.next().as_deref(), Some("")); assert_eq!(split.next(), None); Ok(()) } #[should_panic = "delimiter can't be empty"] #[test] fn empty_delimiter() { let s = "abc"; let cursor = Cursor::new(String::from(s)); let _split = SplitRead::new(cursor, "").map(|e| e.unwrap()); } #[test] fn delimiter_spread_across_reads() { let reader = Cursor::new("<|>foo<|") .chain(Cursor::new(">bar<|><")) .chain(Cursor::new("|>baz<|>")); let mut split = SplitRead::new(reader, "<|>").map(|r| String::from_utf8(r.unwrap()).unwrap()); assert_eq!(split.next().unwrap(), ""); assert_eq!(split.next().unwrap(), "foo"); assert_eq!(split.next().unwrap(), "bar"); assert_eq!(split.next().unwrap(), ""); assert_eq!(split.next().unwrap(), "baz"); assert_eq!(split.next().unwrap(), ""); assert_eq!(split.next(), None); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-utils/src/flatten_json.rs
crates/nu-utils/src/flatten_json.rs
use serde_json::{Map, Value as SerdeValue, json}; /// JsonFlattener is the main driver when flattening JSON /// # Examples /// ``` /// use nu_utils; /// /// let flattener = nu_utils::JsonFlattener { ..Default::default() }; /// ``` pub struct JsonFlattener<'a> { /// Alternate separator used between keys when flattening /// # Examples /// ``` /// use nu_utils; /// let flattener = nu_utils::JsonFlattener { separator: "_", ..Default::default()}; /// ``` pub separator: &'a str, /// Opinionated flattening format that places values in an array if the object is nested inside an array /// # Examples /// ``` /// use nu_utils; /// let flattener = nu_utils::JsonFlattener { alt_array_flattening: true, ..Default::default()}; /// ``` pub alt_array_flattening: bool, /// Completely flatten JSON and keep array structure in the key when flattening /// # Examples /// ``` /// use nu_utils; /// let flattener = nu_utils::JsonFlattener { preserve_arrays: true, ..Default::default()}; /// ``` pub preserve_arrays: bool, } impl Default for JsonFlattener<'_> { fn default() -> Self { JsonFlattener { separator: ".", alt_array_flattening: false, preserve_arrays: false, } } } /// This implementation defines the core usage for the `JsonFlattener` structure. /// # Examples /// ``` /// use nu_utils; /// use serde_json::json; /// /// let flattener = nu_utils::JsonFlattener::new(); /// let example = json!({ /// "a": { /// "b": "c" /// } /// }); /// /// let flattened_example = flattener.flatten(&example); /// ``` impl JsonFlattener<'_> { /// Returns a flattener with the default arguments /// # Examples /// ``` /// use nu_utils; /// /// let flattener = nu_utils::JsonFlattener::new(); /// ``` pub fn new() -> Self { JsonFlattener { ..Default::default() } } /// Flattens JSON variants into a JSON object /// /// # Arguments /// /// * `json` - A serde_json Value to flatten /// /// # Examples /// ``` /// use nu_utils; /// use serde_json::json; /// /// let flattener = nu_utils::JsonFlattener::new(); /// let example = json!({ /// "name": "John Doe", /// "age": 43, /// "address": { /// "street": "10 Downing Street", /// "city": "London" /// }, /// "phones": [ /// "+44 1234567", /// "+44 2345678" /// ] /// }); /// /// let flattened_example = flattener.flatten(&example); /// ``` pub fn flatten(&self, json: &SerdeValue) -> SerdeValue { let mut flattened_val = Map::<String, SerdeValue>::new(); match json { SerdeValue::Array(obj_arr) => { self.flatten_array(&mut flattened_val, &"".to_string(), obj_arr) } SerdeValue::Object(obj_val) => { self.flatten_object(&mut flattened_val, None, obj_val, false) } _ => self.flatten_value(&mut flattened_val, &"".to_string(), json, false), } SerdeValue::Object(flattened_val) } fn flatten_object( &self, builder: &mut Map<String, SerdeValue>, identifier: Option<&String>, obj: &Map<String, SerdeValue>, arr: bool, ) { for (k, v) in obj { let expanded_identifier = identifier.map_or_else( || k.clone(), |identifier| format!("{identifier}{}{k}", self.separator), ); if expanded_identifier.contains("span.start") || expanded_identifier.contains("span.end") { continue; } let expanded_identifier = self.filter_known_keys(&expanded_identifier); match v { SerdeValue::Object(obj_val) => { self.flatten_object(builder, Some(&expanded_identifier), obj_val, arr) } SerdeValue::Array(obj_arr) => { self.flatten_array(builder, &expanded_identifier, obj_arr) } _ => self.flatten_value(builder, &expanded_identifier, v, arr), } } } fn flatten_array( &self, builder: &mut Map<String, SerdeValue>, identifier: &String, obj: &[SerdeValue], ) { for (k, v) in obj.iter().enumerate() { let with_key = format!("{identifier}{}{k}", self.separator); if with_key.contains("span.start") || with_key.contains("span.end") { continue; } let with_key = self.filter_known_keys(&with_key); match v { SerdeValue::Object(obj_val) => self.flatten_object( builder, Some(if self.preserve_arrays { &with_key } else { identifier }), obj_val, self.alt_array_flattening, ), SerdeValue::Array(obj_arr) => self.flatten_array( builder, if self.preserve_arrays { &with_key } else { identifier }, obj_arr, ), _ => self.flatten_value( builder, if self.preserve_arrays { &with_key } else { identifier }, v, self.alt_array_flattening, ), } } } fn flatten_value( &self, builder: &mut Map<String, SerdeValue>, identifier: &String, obj: &SerdeValue, arr: bool, ) { if let Some(v) = builder.get_mut(identifier) { if let Some(arr) = v.as_array_mut() { arr.push(obj.clone()); } else { let new_val = json!(vec![v, obj]); builder.remove(identifier); builder.insert(identifier.to_string(), new_val); } } else { builder.insert( identifier.to_string(), if arr { json!(vec![obj.clone()]) } else { obj.clone() }, ); } } fn filter_known_keys(&self, key: &str) -> String { let mut filtered_key = key.to_string(); if filtered_key.contains(".String.val") { filtered_key = filtered_key.replace(".String.val", ""); } if filtered_key.contains(".Record.val") { filtered_key = filtered_key.replace(".Record.val", ""); } if filtered_key.contains(".List.vals") { filtered_key = filtered_key.replace(".List.vals", ""); } if filtered_key.contains(".Int.val") { filtered_key = filtered_key.replace(".Int.val", ""); } if filtered_key.contains(".Bool.val") { filtered_key = filtered_key.replace(".Bool.val", ""); } if filtered_key.contains(".Truncate.suffix") { filtered_key = filtered_key.replace(".Truncate.suffix", ".truncating_suffix"); } if filtered_key.contains(".RowCount") { filtered_key = filtered_key.replace(".RowCount", ""); } if filtered_key.contains(".Wrap.try_to_keep_words") { filtered_key = filtered_key.replace(".Wrap.try_to_keep_words", ".wrapping_try_keep_words"); } // For now, let's skip replacing these because they tell us which // numbers are closures and blocks which is useful for extracting the content // if filtered_key.contains(".Closure.val") { // filtered_key = filtered_key.replace(".Closure.val", ""); // } // if filtered_key.contains(".block_id") { // filtered_key = filtered_key.replace(".block_id", ""); // } filtered_key } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-utils/src/main.rs
crates/nu-utils/src/main.rs
#[cfg(windows)] use nu_utils::utils::enable_vt_processing; fn main() { // reset vt processing, aka ansi because illbehaved externals can break it #[cfg(windows)] { let _ = enable_vt_processing(); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-utils/src/deansi.rs
crates/nu-utils/src/deansi.rs
use std::borrow::Cow; /// Removes ANSI escape codes and some ASCII control characters /// /// Optimized for strings that rarely contain ANSI control chars. /// Uses fast search to avoid reallocations. /// /// Keeps `\n` removes `\r`, `\t` etc. /// /// If parsing fails silently returns the input string pub fn strip_ansi_unlikely(string: &str) -> Cow<'_, str> { // Check if any ascii control character except LF(0x0A = 10) is present, // which will be stripped. Includes the primary start of ANSI sequences ESC // (0x1B = decimal 27) if string.bytes().any(|x| matches!(x, 0..=9 | 11..=31)) && let Ok(stripped) = String::from_utf8(strip_ansi_escapes::strip(string)) { return Cow::Owned(stripped); } // Else case includes failures to parse! Cow::Borrowed(string) } /// Removes ANSI escape codes and some ASCII control characters /// /// Optimized for strings that likely contain ANSI control chars. /// /// Keeps `\n` removes `\r`, `\t` etc. /// /// If parsing fails silently returns the input string pub fn strip_ansi_likely(string: &str) -> Cow<'_, str> { // Check if any ascii control character except LF(0x0A = 10) is present, // which will be stripped. Includes the primary start of ANSI sequences ESC // (0x1B = decimal 27) if let Ok(stripped) = String::from_utf8(strip_ansi_escapes::strip(string)) { return Cow::Owned(stripped); } // Else case includes failures to parse! Cow::Borrowed(string) } /// Removes ANSI escape codes and some ASCII control characters /// /// Optimized for strings that rarely contain ANSI control chars. /// Uses fast search to avoid reallocations. /// /// Keeps `\n` removes `\r`, `\t` etc. /// /// If parsing fails silently returns the input string pub fn strip_ansi_string_unlikely(string: String) -> String { // Check if any ascii control character except LF(0x0A = 10) is present, // which will be stripped. Includes the primary start of ANSI sequences ESC // (0x1B = decimal 27) if string .as_str() .bytes() .any(|x| matches!(x, 0..=8 | 11..=31)) && let Ok(stripped) = String::from_utf8(strip_ansi_escapes::strip(&string)) { return stripped; } // Else case includes failures to parse! string } /// Removes ANSI escape codes and some ASCII control characters /// /// Optimized for strings that likely contain ANSI control chars. /// /// Keeps `\n` removes `\r`, `\t` etc. /// /// If parsing fails silently returns the input string pub fn strip_ansi_string_likely(string: String) -> String { // Check if any ascii control character except LF(0x0A = 10) is present, // which will be stripped. Includes the primary start of ANSI sequences ESC // (0x1B = decimal 27) if let Ok(stripped) = String::from_utf8(strip_ansi_escapes::strip(&string)) { return stripped; } // Else case includes failures to parse! string }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-utils/src/quoting.rs
crates/nu-utils/src/quoting.rs
use fancy_regex::Regex; use std::sync::LazyLock; // This hits, in order: // • Any character of []:`{}#'";()|$,.!?= // • Any digit (\d) // • Any whitespace (\s) // • Case-insensitive sign-insensitive float "keywords" inf, infinity and nan. static NEEDS_QUOTING_REGEX: LazyLock<Regex> = LazyLock::new(|| { Regex::new(r#"[\[\]:`\{\}#'";\(\)\|\$,\.\d\s!?=]|(?i)^[+\-]?(inf(inity)?|nan)$"#) .expect("internal error: NEEDS_QUOTING_REGEX didn't compile") }); pub fn needs_quoting(string: &str) -> bool { if string.is_empty() { return true; } // These are case-sensitive keywords match string { // `true`/`false`/`null` are active keywords in JSON and NUON // `&&` is denied by the nu parser for diagnostics reasons // (https://github.com/nushell/nushell/pull/7241) "true" | "false" | "null" | "&&" => return true, _ => (), }; // All other cases are handled here NEEDS_QUOTING_REGEX.is_match(string).unwrap_or(false) } pub fn escape_quote_string(string: &str) -> String { let mut output = String::with_capacity(string.len() + 2); output.push('"'); for c in string.chars() { if c == '"' || c == '\\' { output.push('\\'); } output.push(c); } output.push('"'); output }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-utils/src/locale.rs
crates/nu-utils/src/locale.rs
use num_format::Locale; pub const LOCALE_OVERRIDE_ENV_VAR: &str = "NU_TEST_LOCALE_OVERRIDE"; pub fn get_system_locale() -> Locale { let locale_string = get_system_locale_string().unwrap_or_else(|| String::from("en-US")); // Since get_locale() and Locale::from_name() don't always return the same items // we need to try and parse it to match. For instance, a valid locale is de_DE // however Locale::from_name() wants only de so we split and parse it out. let locale_string = locale_string.replace('_', "-"); // en_AU -> en-AU Locale::from_name(&locale_string).unwrap_or_else(|_| { let all = num_format::Locale::available_names(); let locale_prefix = &locale_string.split('-').collect::<Vec<&str>>(); if all.contains(&locale_prefix[0]) { Locale::from_name(locale_prefix[0]).unwrap_or(Locale::en) } else { Locale::en } }) } #[cfg(debug_assertions)] pub fn get_system_locale_string() -> Option<String> { std::env::var(LOCALE_OVERRIDE_ENV_VAR).ok().or_else( #[cfg(not(test))] { sys_locale::get_locale }, #[cfg(test)] { // For tests, we use the same locale on all systems. // To override this, set `LOCALE_OVERRIDE_ENV_VAR`. || Some(Locale::en_US_POSIX.name().to_owned()) }, ) } #[cfg(not(debug_assertions))] pub fn get_system_locale_string() -> Option<String> { sys_locale::get_locale() }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-utils/src/strings/unique.rs
crates/nu-utils/src/strings/unique.rs
use std::{ borrow::Borrow, fmt::{Arguments, Debug, Display}, hash::Hash, ops::Deref, }; use serde::{Deserialize, Serialize}; /// An owned, immutable string with compact storage. /// /// `UniqueString` is designed for immutable strings that are not frequently cloned and hold ownership. /// It offers similar characteristics to `Box<str>` but with several key /// optimizations for improved efficiency and memory usage: /// /// - **Efficient for Unique Strings:** /// When strings are not frequently cloned, `UniqueString` can be more performant than /// reference-counted alternatives like [`SharedString`](super::SharedString) as it avoids the /// overhead of atomic reference counting. /// /// - **Small String Optimization (SSO):** /// For shorter strings, the data is stored directly within the `UniqueString` struct, keeping /// the data on the stack and avoiding indirection. /// /// - **Static String Re-use:** /// Strings with a `'static` lifetime are directly referenced, avoiding unnecessary copies or /// allocations. /// /// - **Niche Optimization:** /// `UniqueString` allows niche-optimization, meaning that [`Option<UniqueString>`] has the same /// memory footprint as `UniqueString`. /// /// - **Compact Size:** /// On 64-bit systems, `UniqueString` is 16 bytes. /// This is achieved by disregarding the capacity of a `String` since we only hold the string as /// immutable. /// /// Internally, `UniqueString` is powered by [`byteyarn::Yarn`], which provides the /// underlying implementation for these optimizations. pub struct UniqueString(byteyarn::Yarn); const _: () = const { assert!(size_of::<UniqueString>() == size_of::<[usize; 2]>()); assert!(size_of::<UniqueString>() == size_of::<Option<UniqueString>>()); }; impl UniqueString { /// Returns a string slice containing the entire `UniqueString`. #[inline] pub fn as_str(&self) -> &str { self.0.as_str() } /// Returns a byte slice of this `UniqueString`'s contents. #[inline] pub fn as_bytes(&self) -> &[u8] { self.0.as_bytes() } /// Returns the length of this `UniqueString`, in bytes. #[inline] pub fn len(&self) -> usize { self.0.len() } /// Returns `true` if the `UniqueString` has a length of 0, `false` otherwise. #[inline] pub fn is_empty(&self) -> bool { self.0.is_empty() } /// Returns a `UniqueString` by taking ownership of an allocation. #[inline] pub fn from_string(string: String) -> Self { Self(byteyarn::Yarn::from_string(string)) } /// Returns a `UniqueString` pointing to the given slice, without copying. /// /// By using this function instead of [`from_string`](Self::from_string), we can avoid any /// copying and always refer to the provided static string slice. #[inline] pub fn from_static_str(string: &'static str) -> Self { Self(byteyarn::Yarn::from_static(string)) } /// Builds a new `UniqueString` from the given formatting arguments. /// /// You can get an [`Arguments`] instance by calling [`format_args!`]. /// This function is used when using [`uformat!`](crate::uformat) instead of [`format!`] to /// create a `UniqueString`. #[inline] pub fn from_fmt(arguments: Arguments) -> Self { Self(byteyarn::Yarn::from_fmt(arguments)) } } impl AsRef<str> for UniqueString { #[inline] fn as_ref(&self) -> &str { self.as_str() } } impl Borrow<str> for UniqueString { #[inline] fn borrow(&self) -> &str { self.as_str() } } impl Clone for UniqueString { #[inline] fn clone(&self) -> Self { Self(self.0.clone()) } } impl Debug for UniqueString { #[inline] fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { Debug::fmt(&self.0, f) } } impl Default for UniqueString { #[inline] fn default() -> Self { Self(Default::default()) } } impl Deref for UniqueString { type Target = str; #[inline] fn deref(&self) -> &Self::Target { self.as_str() } } impl Display for UniqueString { #[inline] fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { Display::fmt(&self.0, f) } } impl Eq for UniqueString {} impl From<String> for UniqueString { #[inline] fn from(string: String) -> Self { Self::from_string(string) } } impl From<&'static str> for UniqueString { #[inline] fn from(string: &'static str) -> Self { Self::from_static_str(string) } } impl Hash for UniqueString { #[inline] fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.0.hash(state); } } impl Ord for UniqueString { #[inline] fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.0.cmp(&other.0) } } impl PartialEq for UniqueString { #[inline] fn eq(&self, other: &Self) -> bool { self.0 == other.0 } } impl PartialOrd for UniqueString { #[inline] fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl Serialize for UniqueString { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { self.0.serialize(serializer) } } impl<'de> Deserialize<'de> for UniqueString { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let s = String::deserialize(deserializer)?; Ok(Self::from_string(s)) } } /// A macro for creating [`UniqueString`] instances from format arguments. /// /// This macro works similarly to [`format!`] but returns a [`UniqueString`] instead of a [`String`]. /// It attempts to optimize for `'static` string literals. #[macro_export] macro_rules! uformat { ($fmt:expr) => { $crate::strings::UniqueString::from_fmt(::std::format_args!($fmt)) }; ($fmt:expr, $($args:tt)*) => { $crate::strings::UniqueString::from_fmt(::std::format_args!($fmt, $($args)*)) }; } #[cfg(test)] mod tests { use super::*; #[test] fn macro_works() { assert!(uformat!("").is_empty()); assert_eq!( uformat!("Hello World"), UniqueString::from_static_str("Hello World") ); assert_eq!( uformat!("Hello {}", "World"), UniqueString::from_static_str("Hello World") ); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-utils/src/strings/mod.rs
crates/nu-utils/src/strings/mod.rs
//! String utility types with specific semantics. //! //! This module provides additional string types optimized for certain use-cases, offering //! alternatives to standard [`String`] or [`&str`](str) when specific performance characteristics //! are desired. //! //! The pipeline-based, functional programming model, we use, leads to frequent string operations //! that involve immutability and often copying. //! These specialized string types can provide performance and memory benefits for these cases. //! //! ## Choosing a String Type: `SharedString` vs. `UniqueString` //! //! ### Use [`SharedString`] when: //! //! `SharedString` is an owned, immutable string type optimized for **frequent cloning and sharing**. //! Cloning it is very inexpensive (a pointer copy and atomic reference count increment), avoiding //! deep copies of the string data. //! It also benefits from Small String Optimization (SSO) and static string re-use. //! //! **Ideal for:** Strings that need to be duplicated or passed by value frequently across //! pipeline stages or within complex data structures, where many references to the same string //! data are expected. //! //! ### Use [`UniqueString`] when: //! //! `UniqueString` is an owned, immutable string type optimized for //! **strings that are primarily unique** or rarely cloned. //! Cloning a `UniqueString` always involves copying the underlying string data. //! Its advantage lies in avoiding the overhead of atomic reference counting. //! It also benefits from Small String Optimization (SSO) and static string re-use. //! //! **Ideal for:** Strings that are created and consumed locally, or represent unique identifiers //! that are not expected to be duplicated across many ownership boundaries. //! When the cost of copying upon infrequent clones is acceptable. mod shared; mod unique; pub use shared::SharedString; pub use unique::UniqueString;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-utils/src/strings/shared.rs
crates/nu-utils/src/strings/shared.rs
use std::{ borrow::Borrow, fmt::{Arguments, Debug, Display}, hash::Hash, ops::Deref, }; use serde::{Deserialize, Serialize}; /// An owned, immutable string with compact storage and efficient cloning. /// /// `SharedString` is designed for immutable strings that are frequently cloned and hold ownership. /// It offers similar characteristics to [`Arc<str>`](std::sync::Arc) but with several key /// optimizations for improved efficiency and memory usage: /// /// - **Efficient Cloning:** /// Cloning a `SharedString` is very inexpensive. /// It typically involves just a pointer copy and an atomic reference count increment, without /// copying the actual string data. /// /// - **Small String Optimization (SSO):** /// For shorter strings, the data is stored directly within the `SharedString` struct, keeping /// the data on the stack and avoiding indirection. /// /// - **Static String Re-use:** /// Strings with a `'static` lifetime are directly referenced, avoiding unnecessary copies or /// allocations. /// /// - **Niche Optimization:** /// `SharedString` allows niche-optimization, meaning that [`Option<SharedString>`] has the same /// memory footprint as `SharedString`. /// /// - **Compact Size:** /// On 64-bit systems, `SharedString` is 16 bytes. /// This is achieved by disregarding the capacity of a `String` since we only hold the string as /// immutable. /// /// Internally, `SharedString` is powered by [`lean_string::LeanString`], which provides the /// underlying implementation for these optimizations. pub struct SharedString(lean_string::LeanString); const _: () = const { assert!(size_of::<SharedString>() == size_of::<[usize; 2]>()); assert!(size_of::<SharedString>() == size_of::<Option<SharedString>>()); }; impl SharedString { /// Returns a string slice containing the entire `SharedString`. #[inline] pub fn as_str(&self) -> &str { self.0.as_str() } /// Returns a byte slice of this `SharedString`'s contents. #[inline] pub fn as_bytes(&self) -> &[u8] { self.0.as_bytes() } /// Returns the length of this `SharedString`, in bytes. #[inline] pub fn len(&self) -> usize { self.0.len() } /// Returns `true` if the `SharedString` has a length of 0, `false` otherwise. #[inline] pub fn is_empty(&self) -> bool { self.0.is_empty() } /// Returns a `SharedString` by taking ownership of an allocation. #[inline] pub fn from_string(string: String) -> Self { Self(lean_string::LeanString::from(string)) } /// Returns a `SharedString` pointing to the given slice, without copying. /// /// By using this function instead of [`from_string`](Self::from_string), we can avoid any /// copying and always refer to the provided static string slice. #[inline] pub fn from_static_str(string: &'static str) -> Self { Self(lean_string::LeanString::from_static_str(string)) } /// Builds a new `SharedString` from the given formatting arguments. /// /// You can get an [`Arguments`] instance by calling [`format_args!`]. /// This function is used when using [`sformat!`](crate::sformat) instead of [`format!`] to /// create a `SharedString`. #[inline] pub fn from_fmt(arguments: Arguments) -> Self { match arguments.as_str() { Some(static_str) => Self::from_static_str(static_str), None => Self::from_string(std::fmt::format(arguments)), } } } impl AsRef<str> for SharedString { #[inline] fn as_ref(&self) -> &str { self.as_str() } } impl Borrow<str> for SharedString { #[inline] fn borrow(&self) -> &str { self.as_str() } } impl Clone for SharedString { #[inline] fn clone(&self) -> Self { Self(self.0.clone()) } } impl Debug for SharedString { #[inline] fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { Debug::fmt(&self.0, f) } } impl Default for SharedString { #[inline] fn default() -> Self { Self(Default::default()) } } impl Deref for SharedString { type Target = str; #[inline] fn deref(&self) -> &Self::Target { self.as_str() } } impl Display for SharedString { #[inline] fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { Display::fmt(&self.0, f) } } impl Eq for SharedString {} impl From<String> for SharedString { #[inline] fn from(string: String) -> Self { Self::from_string(string) } } impl From<&'static str> for SharedString { #[inline] fn from(string: &'static str) -> Self { Self::from_static_str(string) } } impl Hash for SharedString { #[inline] fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.0.hash(state); } } impl Ord for SharedString { #[inline] fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.0.cmp(&other.0) } } impl PartialEq for SharedString { #[inline] fn eq(&self, other: &Self) -> bool { self.0 == other.0 } } impl PartialOrd for SharedString { #[inline] fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl Serialize for SharedString { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { self.0.serialize(serializer) } } impl<'de> Deserialize<'de> for SharedString { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { Ok(Self(lean_string::LeanString::deserialize(deserializer)?)) } } /// A macro for creating [`SharedString`] instances from format arguments. /// /// This macro works similarly to [`format!`] but returns a [`SharedString`] instead of a [`String`]. /// It attempts to optimize for `'static` string literals. #[macro_export] macro_rules! sformat { ($fmt:expr) => { $crate::strings::SharedString::from_fmt(::std::format_args!($fmt)) }; ($fmt:expr, $($args:tt)*) => { $crate::strings::SharedString::from_fmt(::std::format_args!($fmt, $($args)*)) }; } #[cfg(test)] mod tests { use super::*; #[test] fn macro_works() { assert!(sformat!("").is_empty()); assert_eq!( sformat!("Hello World"), SharedString::from_static_str("Hello World") ); assert_eq!( sformat!("Hello {}", "World"), SharedString::from_static_str("Hello World") ); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-experimental/src/lib.rs
crates/nu-experimental/src/lib.rs
//! Experimental Options for the Nu codebase. //! //! This crate defines all experimental options used in Nushell. //! //! An [`ExperimentalOption`] is basically a fancy global boolean. //! It should be set very early during initialization and lets us switch between old and new //! behavior for parts of the system. //! //! The goal is to have a consistent way to handle experimental flags across the codebase, and to //! make it easy to find all available options. //! //! # Usage //! //! Using an option is simple: //! //! ```rust //! if nu_experimental::EXAMPLE.get() { //! // new behavior //! } else { //! // old behavior //! } //! ``` //! //! # Adding New Options //! //! 1. Create a new module in `options.rs`. //! 2. Define a marker struct and implement `ExperimentalOptionMarker` for it. //! 3. Add a new static using `ExperimentalOption::new`. //! 4. Add the static to [`ALL`]. //! //! That's it. See [`EXAMPLE`] in `options/example.rs` for a complete example. //! //! # For Users //! //! Users can view enabled options using either `version` or `debug experimental-options`. //! //! To enable or disable options, use either the `NU_EXPERIMENTAL_OPTIONS` environment variable //! (see [`ENV`]), or pass them via CLI using `--experimental-options`, e.g.: //! //! ```sh //! nu --experimental-options=[example] //! ``` //! //! # For Embedders //! //! If you're embedding Nushell, prefer using [`parse_env`] or [`parse_iter`] to load options. //! //! `parse_iter` is useful if you want to feed in values from other sources. //! Since options are expected to stay stable during runtime, make sure to do this early. //! //! You can also call [`ExperimentalOption::set`] manually, but be careful with that. use crate::util::AtomicMaybe; use std::{fmt::Debug, sync::atomic::Ordering}; mod options; mod parse; mod util; pub use options::*; pub use parse::*; /// The status of an experimental option. /// /// An option can either be disabled by default ([`OptIn`](Self::OptIn)) or enabled by default /// ([`OptOut`](Self::OptOut)), depending on its expected stability. /// /// Experimental options can be deprecated in two ways: /// - If the feature becomes default behavior, it's marked as /// [`DeprecatedDefault`](Self::DeprecatedDefault). /// - If the feature is being fully removed, it's marked as /// [`DeprecatedDiscard`](Self::DeprecatedDiscard) and triggers a warning. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Status { /// Disabled by default. OptIn, /// Enabled by default. OptOut, /// Deprecated as an experimental option; now default behavior. DeprecatedDefault, /// Deprecated; the feature will be removed and triggers a warning. DeprecatedDiscard, } /// Experimental option (aka feature flag). /// /// This struct holds one experimental option that can change some part of Nushell's behavior. /// These options let users opt in or out of experimental changes while keeping the rest stable. /// They're useful for testing new ideas and giving users a way to go back to older behavior if needed. /// /// You can find all options in the statics of [`nu_experimental`](crate). /// Everything there, except [`ALL`], is a toggleable option. /// `ALL` gives a full list and can be used to check which options are set. /// /// The [`Debug`] implementation shows the option's identifier, stability, and current value. /// To also include the description in the output, use the /// [plus sign](std::fmt::Formatter::sign_plus), e.g. `format!("{OPTION:+#?}")`. pub struct ExperimentalOption { value: AtomicMaybe, marker: &'static (dyn DynExperimentalOptionMarker + Send + Sync), } impl ExperimentalOption { /// Construct a new `ExperimentalOption`. /// /// This should only be used to define a single static for a marker. pub(crate) const fn new( marker: &'static (dyn DynExperimentalOptionMarker + Send + Sync), ) -> Self { Self { value: AtomicMaybe::new(None), marker, } } pub fn identifier(&self) -> &'static str { self.marker.identifier() } pub fn description(&self) -> &'static str { self.marker.description() } pub fn status(&self) -> Status { self.marker.status() } pub fn since(&self) -> Version { self.marker.since() } pub fn issue_id(&self) -> u32 { self.marker.issue() } pub fn issue_url(&self) -> String { format!( "https://github.com/nushell/nushell/issues/{}", self.marker.issue() ) } pub fn get(&self) -> bool { self.value .load(Ordering::Relaxed) .unwrap_or_else(|| match self.marker.status() { Status::OptIn => false, Status::OptOut => true, Status::DeprecatedDiscard => false, Status::DeprecatedDefault => false, }) } /// Sets the state of an experimental option. /// /// # Safety /// This method is unsafe to emphasize that experimental options are not designed to change /// dynamically at runtime. /// Changing their state at arbitrary points can lead to inconsistent behavior. /// You should set experimental options only during initialization, before the application fully /// starts. pub unsafe fn set(&self, value: bool) { self.value.store(value, Ordering::Relaxed); } /// Unsets an experimental option, resetting it to an uninitialized state. /// /// # Safety /// Like [`set`](Self::set), this method is unsafe to highlight that experimental options should /// remain stable during runtime. /// Only unset options in controlled, initialization contexts to avoid unpredictable behavior. pub unsafe fn unset(&self) { self.value.store(None, Ordering::Relaxed); } } impl Debug for ExperimentalOption { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let add_description = f.sign_plus(); let mut debug_struct = f.debug_struct("ExperimentalOption"); debug_struct.field("identifier", &self.identifier()); debug_struct.field("value", &self.get()); debug_struct.field("stability", &self.status()); if add_description { debug_struct.field("description", &self.description()); } debug_struct.finish() } } impl PartialEq for ExperimentalOption { fn eq(&self, other: &Self) -> bool { // if both underlying atomics point to the same value, we talk about the same option self.value.as_ptr() == other.value.as_ptr() } } impl Eq for ExperimentalOption {} /// Sets the state of all experimental option that aren't deprecated. /// /// # Safety /// This method is unsafe to emphasize that experimental options are not designed to change /// dynamically at runtime. /// Changing their state at arbitrary points can lead to inconsistent behavior. /// You should set experimental options only during initialization, before the application fully /// starts. pub unsafe fn set_all(value: bool) { for option in ALL { match option.status() { // SAFETY: The safety bounds for `ExperimentalOption.set` are the same as this function. Status::OptIn | Status::OptOut => unsafe { option.set(value) }, Status::DeprecatedDefault | Status::DeprecatedDiscard => {} } } } pub(crate) trait DynExperimentalOptionMarker { fn identifier(&self) -> &'static str; fn description(&self) -> &'static str; fn status(&self) -> Status; fn since(&self) -> Version; fn issue(&self) -> u32; } impl<M: options::ExperimentalOptionMarker> DynExperimentalOptionMarker for M { fn identifier(&self) -> &'static str { M::IDENTIFIER } fn description(&self) -> &'static str { M::DESCRIPTION } fn status(&self) -> Status { M::STATUS } fn since(&self) -> Version { M::SINCE } fn issue(&self) -> u32 { M::ISSUE } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-experimental/src/parse.rs
crates/nu-experimental/src/parse.rs
use crate::{ALL, ExperimentalOption, Status}; use itertools::Itertools; use std::{borrow::Cow, env, ops::Range, sync::atomic::Ordering}; use thiserror::Error; /// Environment variable used to load experimental options from. /// /// May be used like this: `NU_EXPERIMENTAL_OPTIONS=example nu`. pub const ENV: &str = "NU_EXPERIMENTAL_OPTIONS"; /// Warnings that can happen while parsing experimental options. #[derive(Debug, Clone, Error, Eq, PartialEq)] pub enum ParseWarning { /// The given identifier doesn't match any known experimental option. #[error("Unknown experimental option `{0}`")] Unknown(String), /// The assignment wasn't valid. Only `true` or `false` is accepted. #[error("Invalid assignment for `{identifier}`, expected `true` or `false`, got `{1}`", identifier = .0.identifier())] InvalidAssignment(&'static ExperimentalOption, String), /// The assignment for "all" wasn't valid. Only `true` or `false` is accepted. #[error("Invalid assignment for `all`, expected `true` or `false`, got `{0}`")] InvalidAssignmentAll(String), /// This experimental option is deprecated as this is now the default behavior. #[error("The experimental option `{identifier}` is deprecated as this is now the default behavior.", identifier = .0.identifier())] DeprecatedDefault(&'static ExperimentalOption), /// This experimental option is deprecated and will be removed in the future. #[error("The experimental option `{identifier}` is deprecated and will be removed in a future release", identifier = .0.identifier())] DeprecatedDiscard(&'static ExperimentalOption), } /// Parse and activate experimental options. /// /// This is the recommended way to activate options, as it handles [`ParseWarning`]s properly /// and is easy to hook into. /// /// When the key `"all"` is encountered, [`set_all`](super::set_all) is used to set all /// experimental options that aren't deprecated. /// This allows opting (or opting out of) all experimental options that are currently available for /// testing. /// /// The `iter` argument should yield: /// - the identifier of the option /// - an optional assignment value (`true`/`false`) /// - a context value, which is returned with any warning /// /// This way you don't need to manually track which input caused which warning. pub fn parse_iter<'i, Ctx: Clone>( iter: impl Iterator<Item = (Cow<'i, str>, Option<Cow<'i, str>>, Ctx)>, ) -> Vec<(ParseWarning, Ctx)> { let mut warnings = Vec::new(); for (key, val, ctx) in iter { if key == "all" { let val = match parse_val(val.as_deref()) { Ok(val) => val, Err(s) => { warnings.push((ParseWarning::InvalidAssignmentAll(s.to_owned()), ctx)); continue; } }; // SAFETY: This is part of the expected parse function to be called at initialization. unsafe { super::set_all(val) }; continue; } let Some(option) = ALL.iter().find(|option| option.identifier() == key.trim()) else { warnings.push((ParseWarning::Unknown(key.to_string()), ctx)); continue; }; match option.status() { Status::DeprecatedDiscard => { warnings.push((ParseWarning::DeprecatedDiscard(option), ctx.clone())); } Status::DeprecatedDefault => { warnings.push((ParseWarning::DeprecatedDefault(option), ctx.clone())); } _ => {} } let val = match parse_val(val.as_deref()) { Ok(val) => val, Err(s) => { warnings.push((ParseWarning::InvalidAssignment(option, s.to_owned()), ctx)); continue; } }; option.value.store(val, Ordering::Relaxed); } warnings } fn parse_val(val: Option<&str>) -> Result<bool, &str> { match val.map(str::trim) { None => Ok(true), Some("true") => Ok(true), Some("false") => Ok(false), Some(s) => Err(s), } } /// Parse experimental options from the [`ENV`] environment variable. /// /// Uses [`parse_iter`] internally. Each warning includes a `Range<usize>` pointing to the /// part of the environment variable that triggered it. pub fn parse_env() -> Vec<(ParseWarning, Range<usize>)> { let Ok(env) = env::var(ENV) else { return vec![]; }; let mut entries = Vec::new(); let mut start = 0; for (idx, c) in env.char_indices() { if c == ',' { entries.push((&env[start..idx], start..idx)); start = idx + 1; } } entries.push((&env[start..], start..env.len())); parse_iter(entries.into_iter().map(|(entry, span)| { entry .split_once("=") .map(|(key, val)| (key.into(), Some(val.into()), span.clone())) .unwrap_or((entry.into(), None, span)) })) } impl ParseWarning { /// A code to represent the variant. /// /// This may be used with crates like [`miette`](https://docs.rs/miette) to provide error codes. pub fn code(&self) -> &'static str { match self { Self::Unknown(_) => "nu::experimental_option::unknown", Self::InvalidAssignment(_, _) => "nu::experimental_option::invalid_assignment", Self::InvalidAssignmentAll(_) => "nu::experimental_option::invalid_assignment_all", Self::DeprecatedDefault(_) => "nu::experimental_option::deprecated_default", Self::DeprecatedDiscard(_) => "nu::experimental_option::deprecated_discard", } } /// Provide some help depending on the variant. /// /// This may be used with crates like [`miette`](https://docs.rs/miette) to provide a help /// message. pub fn help(&self) -> Option<String> { match self { Self::Unknown(_) => Some(format!( "Known experimental options are: {}", ALL.iter().map(|option| option.identifier()).join(", ") )), Self::InvalidAssignment(_, _) => None, Self::InvalidAssignmentAll(_) => None, Self::DeprecatedDiscard(_) => None, Self::DeprecatedDefault(_) => { Some(String::from("You can safely remove this option now.")) } } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-experimental/src/util.rs
crates/nu-experimental/src/util.rs
use std::sync::atomic::{AtomicU8, Ordering}; /// Store an `Option<bool>` as an atomic. /// /// # Implementation Detail /// This stores the `Option<bool>` via its three states as `u8` representing: /// - `None` as `0` /// - `Some(true)` as `1` /// - `Some(false)` as `2` pub struct AtomicMaybe(AtomicU8); impl AtomicMaybe { pub const fn new(initial: Option<bool>) -> Self { Self(AtomicU8::new(match initial { None => 0, Some(true) => 1, Some(false) => 2, })) } pub fn store(&self, value: impl Into<Option<bool>>, order: Ordering) { self.0.store( match value.into() { None => 0, Some(true) => 1, Some(false) => 2, }, order, ); } pub fn load(&self, order: Ordering) -> Option<bool> { match self.0.load(order) { 0 => None, 1 => Some(true), 2 => Some(false), _ => unreachable!("inner atomic is not exposed and can only set 0 to 2"), } } pub fn as_ptr(&self) -> *mut u8 { self.0.as_ptr() } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-experimental/src/options/pipefail.rs
crates/nu-experimental/src/options/pipefail.rs
use crate::*; /// Enable pipefail feature to ensure that the exit status of a pipeline /// accurately reflects the success or failure of all commands within that pipeline, not just /// the last one. /// /// So it helps user writing more rubost nushell script. pub static PIPE_FAIL: ExperimentalOption = ExperimentalOption::new(&PipeFail); // No documentation needed here since this type isn't public. // The static above provides all necessary details. struct PipeFail; impl ExperimentalOptionMarker for PipeFail { const IDENTIFIER: &'static str = "pipefail"; const DESCRIPTION: &'static str = "\ If an external command fails within a pipeline, $env.LAST_EXIT_CODE is set \ to the exit code of rightmost command which failed."; const STATUS: Status = Status::OptIn; const SINCE: Version = (0, 107, 1); const ISSUE: u32 = 16760; }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-experimental/src/options/enforce_runtime_annotations.rs
crates/nu-experimental/src/options/enforce_runtime_annotations.rs
use crate::*; /// Enable runtime type annotation feature to ensure that type annotations /// are checked against the type that binds to them, returning conversion errors /// if the types are incompatible. pub static ENFORCE_RUNTIME_ANNOTATIONS: ExperimentalOption = ExperimentalOption::new(&EnforceRuntimeAnnotations); struct EnforceRuntimeAnnotations; impl ExperimentalOptionMarker for EnforceRuntimeAnnotations { const IDENTIFIER: &'static str = "enforce-runtime-annotations"; const DESCRIPTION: &'static str = "\ Enforce type checking of let assignments at runtime such that \ invalid type conversion errors propagate the same way they would for predefined values."; const STATUS: Status = Status::OptIn; const SINCE: Version = (0, 107, 1); const ISSUE: u32 = 16832; }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-experimental/src/options/example.rs
crates/nu-experimental/src/options/example.rs
use crate::*; /// Example experimental option. /// /// This shows how experimental options should be implemented and documented. /// Reading this static's documentation alone should clearly explain what the /// option changes and how it interacts with the rest of the codebase. /// /// Use this pattern when adding real experimental options. pub static EXAMPLE: ExperimentalOption = ExperimentalOption::new(&Example); // No documentation needed here since this type isn't public. // The static above provides all necessary details. struct Example; impl ExperimentalOptionMarker for Example { const IDENTIFIER: &'static str = "example"; const DESCRIPTION: &'static str = "This is an example of an experimental option."; const STATUS: Status = Status::DeprecatedDiscard; const SINCE: Version = (0, 105, 2); const ISSUE: u32 = 0; }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-experimental/src/options/mod.rs
crates/nu-experimental/src/options/mod.rs
#![allow( private_interfaces, reason = "The marker structs don't need to be exposed, only the static values." )] use crate::*; mod enforce_runtime_annotations; mod example; mod pipefail; mod reorder_cell_paths; pub(crate) type Version = (u16, u16, u16); /// Marker trait for defining experimental options. /// /// Implement this trait to mark a struct as metadata for an [`ExperimentalOption`]. /// It provides all necessary information about an experimental feature directly in code, /// without needing external documentation. /// /// The `STATUS` field is especially important as it controls whether the feature is enabled /// by default and how users should interpret its reliability. pub(crate) trait ExperimentalOptionMarker { /// Unique identifier for this experimental option. /// /// Must be a valid Rust identifier. /// Used when parsing to toggle specific experimental options, /// and may also serve as a user-facing label. const IDENTIFIER: &'static str; /// Brief description explaining what this option changes. /// /// Displayed to users in help messages or summaries without needing to visit external docs. const DESCRIPTION: &'static str; /// Indicates the status of an experimental status. /// /// Options marked [`Status::OptIn`] are disabled by default while options marked with /// [`Status::OptOut`] are enabled by default. /// Experimental options that stabilize should be marked as [`Status::DeprecatedDefault`] while /// options that will be removed should be [`Status::DeprecatedDiscard`]. const STATUS: Status; /// Nushell version since this experimental option is available. /// /// These three values represent major.minor.patch version. /// Don't use some macro to generate this dynamically as this would defeat the purpose of having /// a historic record. const SINCE: Version; /// Github issue that tracks this experimental option. /// /// Experimental options are expected to end their lifetime by either getting a default feature /// or by getting removed. /// To track this we want to have a respective issue on Github that tracks the status. const ISSUE: u32; } // Export only the static values. // The marker structs are not relevant and needlessly clutter the generated docs. pub use enforce_runtime_annotations::ENFORCE_RUNTIME_ANNOTATIONS; pub use example::EXAMPLE; pub use pipefail::PIPE_FAIL; pub use reorder_cell_paths::REORDER_CELL_PATHS; // Include all experimental option statics in here. // This will test them and add them to the parsing list. /// A list of all available experimental options. /// /// Use this to show users every experimental option, including their descriptions, /// identifiers, and current state. pub static ALL: &[&ExperimentalOption] = &[ &EXAMPLE, &REORDER_CELL_PATHS, &PIPE_FAIL, &ENFORCE_RUNTIME_ANNOTATIONS, ]; #[cfg(test)] mod tests { use std::collections::HashSet; use super::*; #[test] fn assert_identifiers_are_unique() { let list: Vec<_> = ALL.iter().map(|opt| opt.identifier()).collect(); let set: HashSet<_> = HashSet::from_iter(&list); assert_eq!(list.len(), set.len()); } #[test] fn assert_identifiers_are_valid() { for option in ALL { let identifier = option.identifier(); assert!(!identifier.is_empty()); let mut chars = identifier.chars(); let first = chars.next().expect("not empty"); assert!(first.is_alphabetic()); assert!(first.is_lowercase()); for char in chars { assert!(char.is_alphanumeric() || char == '-'); if char.is_alphabetic() { assert!(char.is_lowercase()); } } } } #[test] fn assert_description_not_empty() { for option in ALL { assert!(!option.description().is_empty()); } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-experimental/src/options/reorder_cell_paths.rs
crates/nu-experimental/src/options/reorder_cell_paths.rs
use crate::*; /// Reorder cell-path members in `Value::follow_cell_path` to decrease memory usage. /// /// - Accessing a field in a record is cheap, just a simple search and you get a reference to the /// value. /// - Accessing an row in a list is even cheaper, just an array access and you get a reference to /// the value. /// - Accessing a **column** in a table is expensive, it requires accessing the relevant field in /// all rows, and creating a new list to store those value. This uses more computation and more /// memory than the previous two operations. /// /// Thus, accessing a column first, and then immediately accessing a row of that column is very /// wasteful. By simply prioritizing row accesses over column accesses whenever possible we can /// significantly reduce time and memory use. pub static REORDER_CELL_PATHS: ExperimentalOption = ExperimentalOption::new(&ReorderCellPaths); // No documentation needed here since this type isn't public. // The static above provides all necessary details. struct ReorderCellPaths; impl ExperimentalOptionMarker for ReorderCellPaths { const IDENTIFIER: &'static str = "reorder-cell-paths"; const DESCRIPTION: &'static str = "\ Reorder the steps in accessing nested value to decrease memory usage. \ Reorder the parts of cell-path when accessing a cell in a table, always select the row before selecting the column."; const STATUS: Status = Status::OptOut; const SINCE: Version = (0, 105, 2); const ISSUE: u32 = 16766; }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/build.rs
build.rs
use std::fs; use clap_complete::{generate_to, Shell}; include!("src/cli.rs"); fn main() { let var = std::env::var_os("SHELL_COMPLETIONS_DIR").or_else(|| std::env::var_os("OUT_DIR")); let outdir = match var { None => return, Some(outdir) => outdir, }; fs::create_dir_all(&outdir).unwrap(); let mut command = build_command(); for shell in [ Shell::Bash, Shell::Fish, Shell::Zsh, Shell::PowerShell, Shell::Elvish, ] { generate_to(shell, &mut command, "hyperfine", &outdir).unwrap(); } }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/command.rs
src/command.rs
use std::collections::BTreeMap; use std::fmt; use std::str::FromStr; use crate::parameter::tokenize::tokenize; use crate::parameter::ParameterValue; use crate::{ error::{OptionsError, ParameterScanError}, parameter::{ range_step::{Numeric, RangeStep}, ParameterNameAndValue, }, }; use clap::{parser::ValuesRef, ArgMatches}; use anyhow::{bail, Context, Result}; use rust_decimal::Decimal; /// A command that should be benchmarked. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Command<'a> { /// The command name (without parameter substitution) name: Option<&'a str>, /// The command that should be executed (without parameter substitution) expression: &'a str, /// Zero or more parameter values. parameters: Vec<ParameterNameAndValue<'a>>, } impl<'a> Command<'a> { pub fn new(name: Option<&'a str>, expression: &'a str) -> Command<'a> { Command { name, expression, parameters: Vec::new(), } } pub fn new_parametrized( name: Option<&'a str>, expression: &'a str, parameters: impl IntoIterator<Item = ParameterNameAndValue<'a>>, ) -> Command<'a> { Command { name, expression, parameters: parameters.into_iter().collect(), } } pub fn get_name(&self) -> String { self.name.map_or_else( || self.get_command_line(), |name| self.replace_parameters_in(name), ) } pub fn get_name_with_unused_parameters(&self) -> String { let parameters = self .get_unused_parameters() .fold(String::new(), |output, (parameter, value)| { output + &format!("{parameter} = {value}, ") }); let parameters = parameters.trim_end_matches(", "); let parameters = if parameters.is_empty() { "".into() } else { format!(" ({parameters})") }; format!("{}{}", self.get_name(), parameters) } pub fn get_command_line(&self) -> String { self.replace_parameters_in(self.expression) } pub fn get_command(&self) -> Result<std::process::Command> { let command_line = self.get_command_line(); let mut tokens = shell_words::split(&command_line) .with_context(|| format!("Failed to parse command '{command_line}'"))? .into_iter(); if let Some(program_name) = tokens.next() { let mut command_builder = std::process::Command::new(program_name); command_builder.args(tokens); Ok(command_builder) } else { bail!("Can not execute empty command") } } pub fn get_parameters(&self) -> &[(&'a str, ParameterValue)] { &self.parameters } pub fn get_unused_parameters(&self) -> impl Iterator<Item = &(&'a str, ParameterValue)> { self.parameters .iter() .filter(move |(parameter, _)| !self.expression.contains(&format!("{{{parameter}}}"))) } fn replace_parameters_in(&self, original: &str) -> String { let mut result = String::new(); let mut replacements = BTreeMap::<String, String>::new(); for (param_name, param_value) in &self.parameters { replacements.insert(format!("{{{param_name}}}"), param_value.to_string()); } let mut remaining = original; // Manually replace consecutive occurrences to avoid double-replacing: e.g., // // hyperfine -L foo 'a,{bar}' -L bar 'baz,quux' 'echo {foo} {bar}' // // should not ever run 'echo baz baz'. See `test_get_command_line_nonoverlapping`. 'outer: while let Some(head) = remaining.chars().next() { for (k, v) in &replacements { if remaining.starts_with(k.as_str()) { result.push_str(v); remaining = &remaining[k.len()..]; continue 'outer; } } result.push(head); remaining = &remaining[head.len_utf8()..]; } result } } /// A collection of commands that should be benchmarked pub struct Commands<'a>(Vec<Command<'a>>); impl<'a> Commands<'a> { pub fn from_cli_arguments(matches: &'a ArgMatches) -> Result<Commands<'a>> { let command_names = matches.get_many::<String>("command-name"); let command_strings = matches .get_many::<String>("command") .unwrap_or_default() .map(|v| v.as_str()) .collect::<Vec<_>>(); if let Some(args) = matches.get_many::<String>("parameter-scan") { let step_size = matches .get_one::<String>("parameter-step-size") .map(|s| s.as_str()); Ok(Self(Self::get_parameter_scan_commands( command_names, command_strings, args, step_size, )?)) } else if let Some(args) = matches.get_many::<String>("parameter-list") { let command_names = command_names.map_or(vec![], |names| { names.map(|v| v.as_str()).collect::<Vec<_>>() }); let args: Vec<_> = args.map(|v| v.as_str()).collect::<Vec<_>>(); let param_names_and_values: Vec<(&str, Vec<String>)> = args .chunks_exact(2) .map(|pair| { let name = pair[0]; let list_str = pair[1]; (name, tokenize(list_str)) }) .collect(); { let duplicates = Self::find_duplicates(param_names_and_values.iter().map(|(name, _)| *name)); if !duplicates.is_empty() { bail!("Duplicate parameter names: {}", &duplicates.join(", ")); } } let dimensions: Vec<usize> = std::iter::once(command_strings.len()) .chain( param_names_and_values .iter() .map(|(_, values)| values.len()), ) .collect(); let param_space_size = dimensions.iter().product(); if param_space_size == 0 { return Ok(Self(Vec::new())); } // `--command-name` should appear exactly once or exactly B times, // where B is the total number of benchmarks. let command_name_count = command_names.len(); if command_name_count > 1 && command_name_count != param_space_size { return Err(OptionsError::UnexpectedCommandNameCount( command_name_count, param_space_size, ) .into()); } let mut i = 0; let mut commands = Vec::with_capacity(param_space_size); let mut index = vec![0usize; dimensions.len()]; 'outer: loop { let name = command_names .get(i) .or_else(|| command_names.first()) .copied(); i += 1; let (command_index, params_indices) = index.split_first().unwrap(); let parameters: Vec<_> = param_names_and_values .iter() .zip(params_indices) .map(|((name, values), i)| (*name, ParameterValue::Text(values[*i].clone()))) .collect(); commands.push(Command::new_parametrized( name, command_strings[*command_index], parameters, )); // Increment index, exiting loop on overflow. for (i, n) in index.iter_mut().zip(dimensions.iter()) { *i += 1; if *i < *n { continue 'outer; } else { *i = 0; } } break 'outer; } Ok(Self(commands)) } else { let command_names = command_names.map_or(vec![], |names| { names.map(|v| v.as_str()).collect::<Vec<_>>() }); if command_names.len() > command_strings.len() { return Err(OptionsError::TooManyCommandNames(command_strings.len()).into()); } let mut commands = Vec::with_capacity(command_strings.len()); for (i, s) in command_strings.iter().enumerate() { commands.push(Command::new(command_names.get(i).copied(), s)); } Ok(Self(commands)) } } pub fn iter(&self) -> impl Iterator<Item = &Command<'a>> { self.0.iter() } pub fn num_commands(&self, has_reference_command: bool) -> usize { self.0.len() + if has_reference_command { 1 } else { 0 } } /// Finds all the strings that appear multiple times in the input iterator, returning them in /// sorted order. If no string appears more than once, the result is an empty vector. fn find_duplicates<'b, I: IntoIterator<Item = &'b str>>(i: I) -> Vec<&'b str> { let mut counts = BTreeMap::<&'b str, usize>::new(); for s in i { *counts.entry(s).or_default() += 1; } counts .into_iter() .filter_map(|(k, n)| if n > 1 { Some(k) } else { None }) .collect() } fn build_parameter_scan_commands<'b, T: Numeric>( param_name: &'b str, param_min: T, param_max: T, step: T, command_names: Vec<&'b str>, command_strings: Vec<&'b str>, ) -> Result<Vec<Command<'b>>, ParameterScanError> { let param_range = RangeStep::new(param_min, param_max, step)?; let command_name_count = command_names.len(); let mut i = 0; let mut commands = vec![]; for value in param_range { for cmd in &command_strings { let name = command_names .get(i) .or_else(|| command_names.first()) .copied(); commands.push(Command::new_parametrized( name, cmd, vec![(param_name, ParameterValue::Numeric(value.into()))], )); i += 1; } } // `--command-name` should appear exactly once or exactly B times, // where B is the total number of benchmarks. let command_count = commands.len(); if command_name_count > 1 && command_name_count != command_count { return Err(ParameterScanError::UnexpectedCommandNameCount( command_name_count, command_count, )); } Ok(commands) } fn get_parameter_scan_commands<'b>( command_names: Option<ValuesRef<'b, String>>, command_strings: Vec<&'b str>, mut vals: ValuesRef<'b, String>, step: Option<&str>, ) -> Result<Vec<Command<'b>>, ParameterScanError> { let command_names = command_names.map_or(vec![], |names| { names.map(|v| v.as_str()).collect::<Vec<_>>() }); let param_name = vals.next().unwrap().as_str(); let param_min = vals.next().unwrap().as_str(); let param_max = vals.next().unwrap().as_str(); // attempt to parse as integers if let (Ok(param_min), Ok(param_max), Ok(step)) = ( param_min.parse::<i32>(), param_max.parse::<i32>(), step.unwrap_or("1").parse::<i32>(), ) { return Self::build_parameter_scan_commands( param_name, param_min, param_max, step, command_names, command_strings, ); } // try parsing them as decimals let param_min = Decimal::from_str(param_min)?; let param_max = Decimal::from_str(param_max)?; if step.is_none() { return Err(ParameterScanError::StepRequired); } let step = Decimal::from_str(step.unwrap())?; Self::build_parameter_scan_commands( param_name, param_min, param_max, step, command_names, command_strings, ) } } #[test] fn test_get_command_line_nonoverlapping() { let cmd = Command::new_parametrized( None, "echo {foo} {bar}", vec![ ("foo", ParameterValue::Text("{bar} baz".into())), ("bar", ParameterValue::Text("quux".into())), ], ); assert_eq!(cmd.get_command_line(), "echo {bar} baz quux"); } #[test] fn test_get_parameterized_command_name() { let cmd = Command::new_parametrized( Some("name-{bar}-{foo}"), "echo {foo} {bar}", vec![ ("foo", ParameterValue::Text("baz".into())), ("bar", ParameterValue::Text("quux".into())), ], ); assert_eq!(cmd.get_name(), "name-quux-baz"); } impl fmt::Display for Command<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.get_command_line()) } } #[test] fn test_build_commands_cross_product() { use crate::cli::get_cli_arguments; let matches = get_cli_arguments(vec![ "hyperfine", "-L", "par1", "a,b", "-L", "par2", "z,y", "echo {par1} {par2}", "printf '%s\n' {par1} {par2}", ]); let result = Commands::from_cli_arguments(&matches).unwrap().0; // Iteration order: command list first, then parameters in listed order (here, "par1" before // "par2", which is distinct from their sorted order), with parameter values in listed order. let pv = |s: &str| ParameterValue::Text(s.to_string()); let cmd = |cmd: usize, par1: &str, par2: &str| { let expression = ["echo {par1} {par2}", "printf '%s\n' {par1} {par2}"][cmd]; let params = vec![("par1", pv(par1)), ("par2", pv(par2))]; Command::new_parametrized(None, expression, params) }; let expected = vec![ cmd(0, "a", "z"), cmd(1, "a", "z"), cmd(0, "b", "z"), cmd(1, "b", "z"), cmd(0, "a", "y"), cmd(1, "a", "y"), cmd(0, "b", "y"), cmd(1, "b", "y"), ]; assert_eq!(result, expected); } #[test] fn test_build_parameter_list_commands() { use crate::cli::get_cli_arguments; let matches = get_cli_arguments(vec![ "hyperfine", "echo {foo}", "--parameter-list", "foo", "1,2", "--command-name", "name-{foo}", ]); let commands = Commands::from_cli_arguments(&matches).unwrap().0; assert_eq!(commands.len(), 2); assert_eq!(commands[0].get_name(), "name-1"); assert_eq!(commands[1].get_name(), "name-2"); assert_eq!(commands[0].get_command_line(), "echo 1"); assert_eq!(commands[1].get_command_line(), "echo 2"); } #[test] fn test_build_parameter_scan_commands() { use crate::cli::get_cli_arguments; let matches = get_cli_arguments(vec![ "hyperfine", "echo {val}", "--parameter-scan", "val", "1", "2", "--parameter-step-size", "1", "--command-name", "name-{val}", ]); let commands = Commands::from_cli_arguments(&matches).unwrap().0; assert_eq!(commands.len(), 2); assert_eq!(commands[0].get_name(), "name-1"); assert_eq!(commands[1].get_name(), "name-2"); assert_eq!(commands[0].get_command_line(), "echo 1"); assert_eq!(commands[1].get_command_line(), "echo 2"); } #[test] fn test_build_parameter_scan_commands_named() { use crate::cli::get_cli_arguments; let matches = get_cli_arguments(vec![ "hyperfine", "echo {val}", "sleep {val}", "--parameter-scan", "val", "1", "2", "--parameter-step-size", "1", "--command-name", "echo-1", "--command-name", "sleep-1", "--command-name", "echo-2", "--command-name", "sleep-2", ]); let commands = Commands::from_cli_arguments(&matches).unwrap().0; assert_eq!(commands.len(), 4); assert_eq!(commands[0].get_name(), "echo-1"); assert_eq!(commands[0].get_command_line(), "echo 1"); assert_eq!(commands[1].get_name(), "sleep-1"); assert_eq!(commands[1].get_command_line(), "sleep 1"); assert_eq!(commands[2].get_name(), "echo-2"); assert_eq!(commands[2].get_command_line(), "echo 2"); assert_eq!(commands[3].get_name(), "sleep-2"); assert_eq!(commands[3].get_command_line(), "sleep 2"); } #[test] fn test_parameter_scan_commands_int() { let commands = Commands::build_parameter_scan_commands( "val", 1i32, 7i32, 3i32, vec![], vec!["echo {val}"], ) .unwrap(); assert_eq!(commands.len(), 3); assert_eq!(commands[2].get_name(), "echo 7"); assert_eq!(commands[2].get_command_line(), "echo 7"); } #[test] fn test_parameter_scan_commands_decimal() { let param_min = Decimal::from_str("0").unwrap(); let param_max = Decimal::from_str("1").unwrap(); let step = Decimal::from_str("0.33").unwrap(); let commands = Commands::build_parameter_scan_commands( "val", param_min, param_max, step, vec![], vec!["echo {val}"], ) .unwrap(); assert_eq!(commands.len(), 4); assert_eq!(commands[3].get_name(), "echo 0.99"); assert_eq!(commands[3].get_command_line(), "echo 0.99"); } #[test] fn test_parameter_scan_commands_names() { let commands = Commands::build_parameter_scan_commands( "val", 1i32, 3i32, 1i32, vec!["name-{val}"], vec!["echo {val}"], ) .unwrap(); assert_eq!(commands.len(), 3); let command_names = commands .iter() .map(|c| c.get_name()) .collect::<Vec<String>>(); assert_eq!(command_names, vec!["name-1", "name-2", "name-3"]); } #[test] fn test_get_specified_command_names() { let commands = Commands::build_parameter_scan_commands( "val", 1i32, 3i32, 1i32, vec!["name-a", "name-b", "name-c"], vec!["echo {val}"], ) .unwrap(); assert_eq!(commands.len(), 3); let command_names = commands .iter() .map(|c| c.get_name()) .collect::<Vec<String>>(); assert_eq!(command_names, vec!["name-a", "name-b", "name-c"]); } #[test] fn test_different_command_name_count_with_parameters() { let result = Commands::build_parameter_scan_commands( "val", 1i32, 3i32, 1i32, vec!["name-1", "name-2"], vec!["echo {val}"], ); assert!(matches!( result.unwrap_err(), ParameterScanError::UnexpectedCommandNameCount(2, 3) )); }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/cli.rs
src/cli.rs
use std::ffi::OsString; use clap::{ builder::NonEmptyStringValueParser, crate_version, Arg, ArgAction, ArgMatches, Command, ValueHint, }; pub fn get_cli_arguments<'a, I, T>(args: I) -> ArgMatches where I: IntoIterator<Item = T>, T: Into<OsString> + Clone + 'a, { let command = build_command(); command.get_matches_from(args) } /// Build the clap command for parsing command line arguments fn build_command() -> Command { Command::new("hyperfine") .version(crate_version!()) .next_line_help(true) .hide_possible_values(true) .about("A command-line benchmarking tool.") .help_expected(true) .max_term_width(80) .arg( Arg::new("command") .help("The command to benchmark. This can be the name of an executable, a command \ line like \"grep -i todo\" or a shell command like \"sleep 0.5 && echo test\". \ The latter is only available if the shell is not explicitly disabled via \ '--shell=none'. If multiple commands are given, hyperfine will show a \ comparison of the respective runtimes.") .required(true) .action(ArgAction::Append) .value_hint(ValueHint::CommandString) .value_parser(NonEmptyStringValueParser::new()), ) .arg( Arg::new("warmup") .long("warmup") .short('w') .value_name("NUM") .action(ArgAction::Set) .help( "Perform NUM warmup runs before the actual benchmark. This can be used \ to fill (disk) caches for I/O-heavy programs.", ), ) .arg( Arg::new("min-runs") .long("min-runs") .short('m') .action(ArgAction::Set) .value_name("NUM") .help("Perform at least NUM runs for each command (default: 10)."), ) .arg( Arg::new("max-runs") .long("max-runs") .short('M') .action(ArgAction::Set) .value_name("NUM") .help("Perform at most NUM runs for each command. By default, there is no limit."), ) .arg( Arg::new("runs") .long("runs") .conflicts_with_all(["max-runs", "min-runs"]) .short('r') .action(ArgAction::Set) .value_name("NUM") .help("Perform exactly NUM runs for each command. If this option is not specified, \ hyperfine automatically determines the number of runs."), ) .arg( Arg::new("setup") .long("setup") .short('s') .action(ArgAction::Set) .value_name("CMD") .value_hint(ValueHint::CommandString) .help( "Execute CMD before each set of timing runs. This is useful for \ compiling your software with the provided parameters, or to do any \ other work that should happen once before a series of benchmark runs, \ not every time as would happen with the --prepare option." ), ) .arg( Arg::new("reference") .long("reference") .action(ArgAction::Set) .value_name("CMD") .help( "The reference command for the relative comparison of results. \ If this is unset, results are compared with the fastest command as reference." ) ) .arg( Arg::new("reference-name") .long("reference-name") .action(ArgAction::Set) .value_name("CMD") .help("Give a meaningful name to the reference command.") .requires("reference") ) .arg( Arg::new("prepare") .long("prepare") .short('p') .action(ArgAction::Append) .num_args(1) .value_name("CMD") .value_hint(ValueHint::CommandString) .help( "Execute CMD before each timing run. This is useful for \ clearing disk caches, for example.\nThe --prepare option can \ be specified once for all commands or multiple times, once for \ each command. In the latter case, each preparation command will \ be run prior to the corresponding benchmark command.", ), ) .arg( Arg::new("conclude") .long("conclude") .short('C') .action(ArgAction::Append) .num_args(1) .value_name("CMD") .value_hint(ValueHint::CommandString) .help( "Execute CMD after each timing run. This is useful for killing \ long-running processes started (e.g. a web server started in --prepare), \ for example.\nThe --conclude option can be specified once for all \ commands or multiple times, once for each command. In the latter case, \ each conclude command will be run after the corresponding benchmark \ command.", ), ) .arg( Arg::new("cleanup") .long("cleanup") .short('c') .action(ArgAction::Set) .value_name("CMD") .value_hint(ValueHint::CommandString) .help( "Execute CMD after the completion of all benchmarking \ runs for each individual command to be benchmarked. \ This is useful if the commands to be benchmarked produce \ artifacts that need to be cleaned up." ), ) .arg( Arg::new("parameter-scan") .long("parameter-scan") .short('P') .action(ArgAction::Set) .allow_hyphen_values(true) .value_names(["VAR", "MIN", "MAX"]) .help( "Perform benchmark runs for each value in the range MIN..MAX. Replaces the \ string '{VAR}' in each command by the current parameter value.\n\n \ Example: hyperfine -P threads 1 8 'make -j {threads}'\n\n\ This performs benchmarks for 'make -j 1', 'make -j 2', …, 'make -j 8'.\n\n\ To have the value increase following different patterns, use shell arithmetics.\n\n \ Example: hyperfine -P size 0 3 'sleep $((2**{size}))'\n\n\ This performs benchmarks with power of 2 increases: 'sleep 1', 'sleep 2', 'sleep 4', …\n\ The exact syntax may vary depending on your shell and OS." ), ) .arg( Arg::new("parameter-step-size") .long("parameter-step-size") .short('D') .action(ArgAction::Set) .value_names(["DELTA"]) .requires("parameter-scan") .help( "This argument requires --parameter-scan to be specified as well. \ Traverse the range MIN..MAX in steps of DELTA.\n\n \ Example: hyperfine -P delay 0.3 0.7 -D 0.2 'sleep {delay}'\n\n\ This performs benchmarks for 'sleep 0.3', 'sleep 0.5' and 'sleep 0.7'.", ), ) .arg( Arg::new("parameter-list") .long("parameter-list") .short('L') .action(ArgAction::Append) .allow_hyphen_values(true) .value_names(["VAR", "VALUES"]) .conflicts_with_all(["parameter-scan", "parameter-step-size"]) .help( "Perform benchmark runs for each value in the comma-separated list VALUES. \ Replaces the string '{VAR}' in each command by the current parameter value\ .\n\nExample: hyperfine -L compiler gcc,clang '{compiler} -O2 main.cpp'\n\n\ This performs benchmarks for 'gcc -O2 main.cpp' and 'clang -O2 main.cpp'.\n\n\ The option can be specified multiple times to run benchmarks for all \ possible parameter combinations.\n" ), ) .arg( Arg::new("shell") .long("shell") .short('S') .action(ArgAction::Set) .value_name("SHELL") .overrides_with("shell") .value_hint(ValueHint::CommandString) .help("Set the shell to use for executing benchmarked commands. This can be the \ name or the path to the shell executable, or a full command line \ like \"bash --norc\". It can also be set to \"default\" to explicitly select \ the default shell on this platform. Finally, this can also be set to \ \"none\" to disable the shell. In this case, commands will be executed \ directly. They can still have arguments, but more complex things like \ \"sleep 0.1; sleep 0.2\" are not possible without a shell.") ) .arg( Arg::new("no-shell") .short('N') .action(ArgAction::SetTrue) .conflicts_with_all(["shell", "debug-mode"]) .help("An alias for '--shell=none'.") ) .arg( Arg::new("ignore-failure") .long("ignore-failure") .action(ArgAction::Set) .value_name("MODE") .num_args(0..=1) .default_missing_value("all-non-zero") .require_equals(true) .short('i') .help("Ignore failures of the benchmarked programs. Without a value or with \ 'all-non-zero', all non-zero exit codes are ignored. You can also provide \ a comma-separated list of exit codes to ignore (e.g., --ignore-failure=1,2)."), ) .arg( Arg::new("style") .long("style") .action(ArgAction::Set) .value_name("TYPE") .value_parser(["auto", "basic", "full", "nocolor", "color", "none"]) .help( "Set output style type (default: auto). Set this to 'basic' to disable output \ coloring and interactive elements. Set it to 'full' to enable all effects \ even if no interactive terminal was detected. Set this to 'nocolor' to \ keep the interactive output without any colors. Set this to 'color' to keep \ the colors without any interactive output. Set this to 'none' to disable all \ the output of the tool.", ), ) .arg( Arg::new("sort") .long("sort") .action(ArgAction::Set) .value_name("METHOD") .value_parser(["auto", "command", "mean-time"]) .default_value("auto") .hide_default_value(true) .help( "Specify the sort order of the speed comparison summary and the exported tables for \ markup formats (Markdown, AsciiDoc, org-mode):\n \ * 'auto' (default): the speed comparison will be ordered by time and\n \ the markup tables will be ordered by command (input order).\n \ * 'command': order benchmarks in the way they were specified\n \ * 'mean-time': order benchmarks by mean runtime\n" ), ) .arg( Arg::new("time-unit") .long("time-unit") .short('u') .action(ArgAction::Set) .value_name("UNIT") .value_parser(["microsecond", "millisecond", "second"]) .help("Set the time unit to be used. Possible values: microsecond, millisecond, second. \ If the option is not given, the time unit is determined automatically. \ This option affects the standard output as well as all export formats except for CSV and JSON."), ) .arg( Arg::new("export-asciidoc") .long("export-asciidoc") .action(ArgAction::Set) .value_name("FILE") .value_hint(ValueHint::FilePath) .help("Export the timing summary statistics as an AsciiDoc table to the given FILE. \ The output time unit can be changed using the --time-unit option."), ) .arg( Arg::new("export-csv") .long("export-csv") .action(ArgAction::Set) .value_name("FILE") .value_hint(ValueHint::FilePath) .help("Export the timing summary statistics as CSV to the given FILE. If you need \ the timing results for each individual run, use the JSON export format. \ The output time unit is always seconds."), ) .arg( Arg::new("export-json") .long("export-json") .action(ArgAction::Set) .value_name("FILE") .value_hint(ValueHint::FilePath) .help("Export the timing summary statistics and timings of individual runs as JSON to the given FILE. \ The output time unit is always seconds"), ) .arg( Arg::new("export-markdown") .long("export-markdown") .action(ArgAction::Set) .value_name("FILE") .value_hint(ValueHint::FilePath) .help("Export the timing summary statistics as a Markdown table to the given FILE. \ The output time unit can be changed using the --time-unit option."), ) .arg( Arg::new("export-orgmode") .long("export-orgmode") .action(ArgAction::Set) .value_name("FILE") .value_hint(ValueHint::FilePath) .help("Export the timing summary statistics as an Emacs org-mode table to the given FILE. \ The output time unit can be changed using the --time-unit option."), ) .arg( Arg::new("show-output") .long("show-output") .action(ArgAction::SetTrue) .conflicts_with("style") .help( "Print the stdout and stderr of the benchmark instead of suppressing it. \ This will increase the time it takes for benchmarks to run, \ so it should only be used for debugging purposes or \ when trying to benchmark output speed.", ), ) .arg( Arg::new("output") .long("output") .conflicts_with("show-output") .action(ArgAction::Append) .value_name("WHERE") .help( "Control where the output of the benchmark is redirected. Note \ that some programs like 'grep' detect when standard output is \ /dev/null and apply certain optimizations. To avoid that, consider \ using '--output=pipe'.\n\ \n\ <WHERE> can be:\n\ \n \ null: Redirect output to /dev/null (the default).\n\ \n \ pipe: Feed the output through a pipe before discarding it.\n\ \n \ inherit: Don't redirect the output at all (same as '--show-output').\n\ \n \ <FILE>: Write the output to the given file.\n\n\ This option can be specified once for all commands or multiple times, once for \ each command. Note: If you want to log the output of each and every iteration, \ you can use a shell redirection and the '$HYPERFINE_ITERATION' environment variable:\n \ hyperfine 'my-command > output-${HYPERFINE_ITERATION}.log'\n\n", ), ) .arg( Arg::new("input") .long("input") .action(ArgAction::Set) .num_args(1) .value_name("WHERE") .help("Control where the input of the benchmark comes from.\n\ \n\ <WHERE> can be:\n\ \n \ null: Read from /dev/null (the default).\n\ \n \ <FILE>: Read the input from the given file."), ) .arg( Arg::new("command-name") .long("command-name") .short('n') .action(ArgAction::Append) .num_args(1) .value_name("NAME") .help("Give a meaningful name to a command. This can be specified multiple times \ if several commands are benchmarked."), ) // This option is hidden for now, as it is not yet clear yet if we want to 'stabilize' this, // see discussion in https://github.com/sharkdp/hyperfine/issues/527 .arg( Arg::new("min-benchmarking-time") .long("min-benchmarking-time") .action(ArgAction::Set) .hide(true) .help("Set the minimum time (in seconds) to run benchmarks. Note that the number of \ benchmark runs is additionally influenced by the `--min-runs`, `--max-runs`, and \ `--runs` option.") ) .arg( Arg::new("debug-mode") .long("debug-mode") .action(ArgAction::SetTrue) .hide(true) .help("Enable debug mode which does not actually run commands, but returns fake times when the command is 'sleep <time>'.") ) } #[test] fn verify_app() { build_command().debug_assert(); }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/error.rs
src/error.rs
use std::num::{self, ParseFloatError, ParseIntError}; use rust_decimal::Error as DecimalError; use thiserror::Error; #[derive(Debug, Error)] pub enum ParameterScanError { #[error("Error while parsing parameter scan arguments ({0})")] ParseIntError(num::ParseIntError), #[error("Error while parsing parameter scan arguments ({0})")] ParseDecimalError(DecimalError), #[error("Empty parameter range")] EmptyRange, #[error("Parameter range is too large")] TooLarge, #[error("Zero is not a valid parameter step")] ZeroStep, #[error("A step size is required when the range bounds are floating point numbers. The step size can be specified with the '-D/--parameter-step-size <DELTA>' parameter")] StepRequired, #[error("'--command-name' has been specified {0} times. It has to appear exactly once, or exactly {1} times (number of benchmarks)")] UnexpectedCommandNameCount(usize, usize), } impl From<num::ParseIntError> for ParameterScanError { fn from(e: num::ParseIntError) -> ParameterScanError { ParameterScanError::ParseIntError(e) } } impl From<DecimalError> for ParameterScanError { fn from(e: DecimalError) -> ParameterScanError { ParameterScanError::ParseDecimalError(e) } } #[derive(Debug, Error)] pub enum OptionsError<'a> { #[error( "Conflicting requirements for the number of runs (empty range, min is larger than max)" )] EmptyRunsRange, #[error("Too many --command-name options: Expected {0} at most")] TooManyCommandNames(usize), #[error("'--command-name' has been specified {0} times. It has to appear exactly once, or exactly {1} times (number of benchmarks)")] UnexpectedCommandNameCount(usize, usize), #[error("Could not read numeric integer argument to '--{0}': {1}")] IntParsingError(&'a str, ParseIntError), #[error("Could not read numeric floating point argument to '--{0}': {1}")] FloatParsingError(&'a str, ParseFloatError), #[error("An empty command has been specified for the '--shell <command>' option")] EmptyShell, #[error("Failed to parse '--shell <command>' expression as command line: {0}")] ShellParseError(shell_words::ParseError), #[error("Unknown output policy '{0}'. Use './{0}' to output to a file named '{0}'.")] UnknownOutputPolicy(String), #[error("The file '{0}' specified as '--input' does not exist")] StdinDataFileDoesNotExist(String), }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/options.rs
src/options.rs
use std::fs::File; use std::io::IsTerminal; use std::path::PathBuf; use std::process::{Command, Stdio}; use std::{cmp, env, fmt, io}; use anyhow::ensure; use clap::ArgMatches; use crate::command::Commands; use crate::error::OptionsError; use crate::util::units::{Second, Unit}; use anyhow::Result; #[cfg(not(windows))] pub const DEFAULT_SHELL: &str = "sh"; #[cfg(windows)] pub const DEFAULT_SHELL: &str = "cmd.exe"; /// Shell to use for executing benchmarked commands #[derive(Debug, PartialEq)] pub enum Shell { /// Default shell command Default(&'static str), /// Custom shell command specified via --shell Custom(Vec<String>), } impl Default for Shell { fn default() -> Self { Shell::Default(DEFAULT_SHELL) } } impl fmt::Display for Shell { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Shell::Default(cmd) => write!(f, "{cmd}"), Shell::Custom(cmdline) => write!(f, "{}", shell_words::join(cmdline)), } } } impl Shell { /// Parse given string as shell command line pub fn parse_from_str<'a>(s: &str) -> Result<Self, OptionsError<'a>> { let v = shell_words::split(s).map_err(OptionsError::ShellParseError)?; if v.is_empty() || v[0].is_empty() { return Err(OptionsError::EmptyShell); } Ok(Shell::Custom(v)) } pub fn command(&self) -> Command { match self { Shell::Default(cmd) => Command::new(cmd), Shell::Custom(cmdline) => { let mut c = Command::new(&cmdline[0]); c.args(&cmdline[1..]); c } } } } /// Action to take when an executed command fails. #[derive(Debug, Clone, PartialEq, Eq)] pub enum CmdFailureAction { /// Exit with an error message RaiseError, /// Ignore all non-zero exit codes IgnoreAllFailures, /// Ignore specific exit codes IgnoreSpecificFailures(Vec<i32>), } /// Output style type option #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum OutputStyleOption { /// Do not output with colors or any special formatting Basic, /// Output with full color and formatting Full, /// Keep elements such as progress bar, but use no coloring NoColor, /// Keep coloring, but use no progress bar Color, /// Disable all the output Disabled, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SortOrder { Command, MeanTime, } /// Bounds for the number of benchmark runs pub struct RunBounds { /// Minimum number of benchmark runs pub min: u64, /// Maximum number of benchmark runs pub max: Option<u64>, } impl Default for RunBounds { fn default() -> Self { RunBounds { min: 10, max: None } } } #[derive(Debug, Default, Clone, PartialEq)] pub enum CommandInputPolicy { /// Read from the null device #[default] Null, /// Read input from a file File(PathBuf), } impl CommandInputPolicy { pub fn get_stdin(&self) -> io::Result<Stdio> { let stream: Stdio = match self { CommandInputPolicy::Null => Stdio::null(), CommandInputPolicy::File(path) => { let file: File = File::open(path)?; Stdio::from(file) } }; Ok(stream) } } /// How to handle the output of benchmarked commands #[derive(Debug, Clone, PartialEq, Eq, Default)] pub enum CommandOutputPolicy { /// Redirect output to the null device #[default] Null, /// Feed output through a pipe before discarding it Pipe, /// Redirect output to a file File(PathBuf), /// Show command output on the terminal Inherit, } impl CommandOutputPolicy { pub fn get_stdout_stderr(&self) -> io::Result<(Stdio, Stdio)> { let streams = match self { CommandOutputPolicy::Null => (Stdio::null(), Stdio::null()), // Typically only stdout is performance-relevant, so just pipe that CommandOutputPolicy::Pipe => (Stdio::piped(), Stdio::null()), CommandOutputPolicy::File(path) => { let file = File::create(path)?; (file.into(), Stdio::null()) } CommandOutputPolicy::Inherit => (Stdio::inherit(), Stdio::inherit()), }; Ok(streams) } } #[derive(Debug, PartialEq)] pub enum ExecutorKind { Raw, Shell(Shell), Mock(Option<String>), } impl Default for ExecutorKind { fn default() -> Self { ExecutorKind::Shell(Shell::default()) } } /// The main settings for a hyperfine benchmark session pub struct Options { /// Upper and lower bound for the number of benchmark runs pub run_bounds: RunBounds, /// Number of warmup runs pub warmup_count: u64, /// Minimum benchmarking time pub min_benchmarking_time: Second, /// Whether or not to ignore non-zero exit codes pub command_failure_action: CmdFailureAction, // Command to use as a reference for relative speed comparison pub reference_command: Option<String>, // Name of the reference command pub reference_name: Option<String>, /// Command(s) to run before each timing run pub preparation_command: Option<Vec<String>>, /// Command(s) to run after each timing run pub conclusion_command: Option<Vec<String>>, /// Command to run before each *batch* of timing runs, i.e. before each individual benchmark pub setup_command: Option<String>, /// Command to run after each *batch* of timing runs, i.e. after each individual benchmark pub cleanup_command: Option<String>, /// What color mode to use for the terminal output pub output_style: OutputStyleOption, /// How to order benchmarks in the relative speed comparison pub sort_order_speed_comparison: SortOrder, /// How to order benchmarks in the markup format exports pub sort_order_exports: SortOrder, /// Determines how we run commands pub executor_kind: ExecutorKind, /// Where input to the benchmarked command comes from pub command_input_policy: CommandInputPolicy, /// What to do with the output of the benchmarked commands pub command_output_policies: Vec<CommandOutputPolicy>, /// Which time unit to use when displaying results pub time_unit: Option<Unit>, } impl Default for Options { fn default() -> Options { Options { run_bounds: RunBounds::default(), warmup_count: 0, min_benchmarking_time: 3.0, command_failure_action: CmdFailureAction::RaiseError, reference_command: None, reference_name: None, preparation_command: None, conclusion_command: None, setup_command: None, cleanup_command: None, output_style: OutputStyleOption::Full, sort_order_speed_comparison: SortOrder::MeanTime, sort_order_exports: SortOrder::Command, executor_kind: ExecutorKind::default(), command_output_policies: vec![CommandOutputPolicy::Null], time_unit: None, command_input_policy: CommandInputPolicy::Null, } } } impl Options { pub fn from_cli_arguments<'a>(matches: &ArgMatches) -> Result<Self, OptionsError<'a>> { let mut options = Self::default(); let param_to_u64 = |param| { matches .get_one::<String>(param) .map(|n| { n.parse::<u64>() .map_err(|e| OptionsError::IntParsingError(param, e)) }) .transpose() }; options.warmup_count = param_to_u64("warmup")?.unwrap_or(options.warmup_count); let mut min_runs = param_to_u64("min-runs")?; let mut max_runs = param_to_u64("max-runs")?; if let Some(runs) = param_to_u64("runs")? { min_runs = Some(runs); max_runs = Some(runs); } match (min_runs, max_runs) { (Some(min), None) => { options.run_bounds.min = min; } (None, Some(max)) => { // Since the minimum was not explicit we lower it if max is below the default min. options.run_bounds.min = cmp::min(options.run_bounds.min, max); options.run_bounds.max = Some(max); } (Some(min), Some(max)) if min > max => { return Err(OptionsError::EmptyRunsRange); } (Some(min), Some(max)) => { options.run_bounds.min = min; options.run_bounds.max = Some(max); } (None, None) => {} }; options.setup_command = matches.get_one::<String>("setup").map(String::from); options.reference_command = matches.get_one::<String>("reference").map(String::from); options.reference_name = matches .get_one::<String>("reference-name") .map(String::from); options.preparation_command = matches .get_many::<String>("prepare") .map(|values| values.map(String::from).collect::<Vec<String>>()); options.conclusion_command = matches .get_many::<String>("conclude") .map(|values| values.map(String::from).collect::<Vec<String>>()); options.cleanup_command = matches.get_one::<String>("cleanup").map(String::from); options.command_output_policies = if matches.get_flag("show-output") { vec![CommandOutputPolicy::Inherit] } else if let Some(output_values) = matches.get_many::<String>("output") { let mut policies = vec![]; for value in output_values { let policy = match value.as_str() { "null" => CommandOutputPolicy::Null, "pipe" => CommandOutputPolicy::Pipe, "inherit" => CommandOutputPolicy::Inherit, arg => { let path = PathBuf::from(arg); if path.components().count() <= 1 { return Err(OptionsError::UnknownOutputPolicy(arg.to_string())); } CommandOutputPolicy::File(path) } }; policies.push(policy); } policies } else { vec![CommandOutputPolicy::Null] }; options.output_style = match matches.get_one::<String>("style").map(|s| s.as_str()) { Some("full") => OutputStyleOption::Full, Some("basic") => OutputStyleOption::Basic, Some("nocolor") => OutputStyleOption::NoColor, Some("color") => OutputStyleOption::Color, Some("none") => OutputStyleOption::Disabled, _ => { if options .command_output_policies .contains(&CommandOutputPolicy::Inherit) || !io::stdout().is_terminal() { OutputStyleOption::Basic } else if env::var_os("TERM") .map(|t| t == "unknown" || t == "dumb") .unwrap_or(!cfg!(target_os = "windows")) || env::var_os("NO_COLOR") .map(|t| !t.is_empty()) .unwrap_or(false) { OutputStyleOption::NoColor } else { OutputStyleOption::Full } } }; match options.output_style { OutputStyleOption::Basic | OutputStyleOption::NoColor => { colored::control::set_override(false) } OutputStyleOption::Full | OutputStyleOption::Color => { colored::control::set_override(true) } OutputStyleOption::Disabled => {} }; ( options.sort_order_speed_comparison, options.sort_order_exports, ) = match matches.get_one::<String>("sort").map(|s| s.as_str()) { None | Some("auto") => (SortOrder::MeanTime, SortOrder::Command), Some("command") => (SortOrder::Command, SortOrder::Command), Some("mean-time") => (SortOrder::MeanTime, SortOrder::MeanTime), Some(_) => unreachable!("Unknown sort order"), }; options.executor_kind = if matches.get_flag("no-shell") { ExecutorKind::Raw } else { match ( matches.get_flag("debug-mode"), matches.get_one::<String>("shell"), ) { (false, Some(shell)) if shell == "default" => ExecutorKind::Shell(Shell::default()), (false, Some(shell)) if shell == "none" => ExecutorKind::Raw, (false, Some(shell)) => ExecutorKind::Shell(Shell::parse_from_str(shell)?), (false, None) => ExecutorKind::Shell(Shell::default()), (true, Some(shell)) => ExecutorKind::Mock(Some(shell.into())), (true, None) => ExecutorKind::Mock(None), } }; if let Some(mode) = matches.get_one::<String>("ignore-failure") { options.command_failure_action = match mode.as_str() { "all-non-zero" | "" => CmdFailureAction::IgnoreAllFailures, codes => { let exit_codes: Result<Vec<i32>, _> = codes .split(',') .map(|s| { s.trim() .parse::<i32>() .map_err(|e| OptionsError::IntParsingError("ignore-failure", e)) }) .collect(); CmdFailureAction::IgnoreSpecificFailures(exit_codes?) } }; } options.time_unit = match matches.get_one::<String>("time-unit").map(|s| s.as_str()) { Some("microsecond") => Some(Unit::MicroSecond), Some("millisecond") => Some(Unit::MilliSecond), Some("second") => Some(Unit::Second), _ => None, }; if let Some(time) = matches.get_one::<String>("min-benchmarking-time") { options.min_benchmarking_time = time .parse::<f64>() .map_err(|e| OptionsError::FloatParsingError("min-benchmarking-time", e))?; } options.command_input_policy = if let Some(path_str) = matches.get_one::<String>("input") { if path_str == "null" { CommandInputPolicy::Null } else { let path = PathBuf::from(path_str); if !path.exists() { return Err(OptionsError::StdinDataFileDoesNotExist( path_str.to_string(), )); } CommandInputPolicy::File(path) } } else { CommandInputPolicy::Null }; Ok(options) } pub fn validate_against_command_list(&mut self, commands: &Commands) -> Result<()> { let has_reference_command = self.reference_command.is_some(); let num_commands = commands.num_commands(has_reference_command); if let Some(preparation_command) = &self.preparation_command { ensure!( preparation_command.len() <= 1 || num_commands == preparation_command.len(), "The '--prepare' option has to be provided just once or N times, where N={num_commands} is the \ number of benchmark commands (including a potential reference)." ); } if let Some(conclusion_command) = &self.conclusion_command { ensure!( conclusion_command.len() <= 1 || num_commands == conclusion_command.len(), "The '--conclude' option has to be provided just once or N times, where N={num_commands} is the \ number of benchmark commands (including a potential reference)." ); } if self.command_output_policies.len() == 1 { self.command_output_policies = vec![self.command_output_policies[0].clone(); num_commands]; } else { ensure!( self.command_output_policies.len() == num_commands, "The '--output' option has to be provided just once or N times, where N={num_commands} is the \ number of benchmark commands (including a potential reference)." ); } Ok(()) } } #[test] fn test_default_shell() { let shell = Shell::default(); let s = format!("{shell}"); assert_eq!(&s, DEFAULT_SHELL); let cmd = shell.command(); assert_eq!(cmd.get_program(), DEFAULT_SHELL); } #[test] fn test_can_parse_shell_command_line_from_str() { let shell = Shell::parse_from_str("shell -x 'aaa bbb'").unwrap(); let s = format!("{shell}"); assert_eq!(&s, "shell -x 'aaa bbb'"); let cmd = shell.command(); assert_eq!(cmd.get_program().to_string_lossy(), "shell"); assert_eq!( cmd.get_args() .map(|a| a.to_string_lossy()) .collect::<Vec<_>>(), vec!["-x", "aaa bbb"] ); // Error cases assert!(matches!( Shell::parse_from_str("shell 'foo").unwrap_err(), OptionsError::ShellParseError(_) )); assert!(matches!( Shell::parse_from_str("").unwrap_err(), OptionsError::EmptyShell )); assert!(matches!( Shell::parse_from_str("''").unwrap_err(), OptionsError::EmptyShell )); }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/outlier_detection.rs
src/outlier_detection.rs
//! A module for statistical outlier detection. //! //! References: //! - Boris Iglewicz and David Hoaglin (1993), "Volume 16: How to Detect and Handle Outliers", //! The ASQC Basic References in Quality Control: Statistical Techniques, Edward F. Mykytka, //! Ph.D., Editor. use statistical::median; /// Minimum modified Z-score for a datapoint to be an outlier. Here, 1.4826 is a factor that /// converts the MAD to an estimator for the standard deviation. The second factor is the number /// of standard deviations. pub const OUTLIER_THRESHOLD: f64 = 1.4826 * 10.0; /// Compute modifized Z-scores for a given sample. A (unmodified) Z-score is defined by /// `(x_i - x_mean)/x_stddev` whereas the modified Z-score is defined by `(x_i - x_median)/MAD` /// where MAD is the median absolute deviation. /// /// References: /// - <https://en.wikipedia.org/wiki/Median_absolute_deviation> pub fn modified_zscores(xs: &[f64]) -> Vec<f64> { assert!(!xs.is_empty()); // Compute sample median: let x_median = median(xs); // Compute the absolute deviations from the median: let deviations: Vec<f64> = xs.iter().map(|x| (x - x_median).abs()).collect(); // Compute median absolute deviation: let mad = median(&deviations); // Handle MAD == 0 case let mad = if mad > 0.0 { mad } else { f64::EPSILON }; // Compute modified Z-scores (x_i - x_median) / MAD xs.iter().map(|&x| (x - x_median) / mad).collect() } /// Return the number of outliers in a given sample. Outliers are defined as data points with a /// modified Z-score that is larger than `OUTLIER_THRESHOLD`. #[cfg(test)] pub fn num_outliers(xs: &[f64]) -> usize { if xs.is_empty() { return 0; } let scores = modified_zscores(xs); scores .iter() .filter(|&&s| s.abs() > OUTLIER_THRESHOLD) .count() } #[test] fn test_detect_outliers() { // Should not detect outliers in small samples assert_eq!(0, num_outliers(&[])); assert_eq!(0, num_outliers(&[50.0])); assert_eq!(0, num_outliers(&[1000.0, 0.0])); // Should not detect outliers in low-variance samples let xs = [-0.2, 0.0, 0.2]; assert_eq!(0, num_outliers(&xs)); // Should detect a single outlier let xs = [-0.2, 0.0, 0.2, 4.0]; assert_eq!(1, num_outliers(&xs)); // Should detect a single outlier let xs = [0.5, 0.30, 0.29, 0.31, 0.30]; assert_eq!(1, num_outliers(&xs)); // Should detect no outliers in sample drawn from normal distribution let xs = [ 2.33269488, 1.42195907, -0.57527698, -0.31293437, 2.2948158, 0.75813273, -1.0712388, -0.96394741, -1.15897446, 1.10976285, ]; assert_eq!(0, num_outliers(&xs)); // Should detect two outliers that were manually added let xs = [ 2.33269488, 1.42195907, -0.57527698, -0.31293437, 2.2948158, 0.75813273, -1.0712388, -0.96394741, -1.15897446, 1.10976285, 20.0, -500.0, ]; assert_eq!(2, num_outliers(&xs)); } #[test] fn test_detect_outliers_if_mad_becomes_0() { // See https://stats.stackexchange.com/q/339932 let xs = [10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 100.0]; assert_eq!(1, num_outliers(&xs)); let xs = [10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 100.0, 100.0]; assert_eq!(2, num_outliers(&xs)); }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/main.rs
src/main.rs
#![cfg_attr( all(windows, feature = "windows_process_extensions_main_thread_handle"), feature(windows_process_extensions_main_thread_handle) )] use std::env; use benchmark::scheduler::Scheduler; use cli::get_cli_arguments; use command::Commands; use export::ExportManager; use options::Options; use anyhow::Result; use colored::*; pub mod benchmark; pub mod cli; pub mod command; pub mod error; pub mod export; pub mod options; pub mod outlier_detection; pub mod output; pub mod parameter; pub mod timer; pub mod util; fn run() -> Result<()> { // Enabled ANSI colors on Windows 10 #[cfg(windows)] colored::control::set_virtual_terminal(true).unwrap(); let cli_arguments = get_cli_arguments(env::args_os()); let mut options = Options::from_cli_arguments(&cli_arguments)?; let commands = Commands::from_cli_arguments(&cli_arguments)?; let export_manager = ExportManager::from_cli_arguments( &cli_arguments, options.time_unit, options.sort_order_exports, )?; options.validate_against_command_list(&commands)?; let mut scheduler = Scheduler::new(&commands, &options, &export_manager); scheduler.run_benchmarks()?; scheduler.print_relative_speed_comparison(); scheduler.final_export()?; Ok(()) } fn main() { match run() { Ok(_) => {} Err(e) => { eprintln!("{} {:#}", "Error:".red(), e); std::process::exit(1); } } }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/util/number.rs
src/util/number.rs
use std::convert::TryFrom; use std::fmt; use rust_decimal::prelude::ToPrimitive; use rust_decimal::Decimal; use serde::Serialize; #[derive(Debug, Clone, Serialize, Copy, PartialEq, Eq)] #[serde(untagged)] pub enum Number { Int(i32), Decimal(Decimal), } impl fmt::Display for Number { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { Number::Int(i) => fmt::Display::fmt(&i, f), Number::Decimal(i) => fmt::Display::fmt(&i, f), } } } impl From<i32> for Number { fn from(x: i32) -> Number { Number::Int(x) } } impl From<Decimal> for Number { fn from(x: Decimal) -> Number { Number::Decimal(x) } } impl TryFrom<Number> for usize { type Error = (); fn try_from(numeric: Number) -> Result<Self, Self::Error> { match numeric { Number::Int(i) => usize::try_from(i).map_err(|_| ()), Number::Decimal(d) => match d.to_u64() { Some(u) => usize::try_from(u).map_err(|_| ()), None => Err(()), }, } } }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/util/units.rs
src/util/units.rs
//! This module contains common units. pub type Scalar = f64; /// Type alias for unit of time pub type Second = Scalar; /// Supported time units #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Unit { Second, MilliSecond, MicroSecond, } impl Unit { /// The abbreviation of the Unit. pub fn short_name(self) -> String { match self { Unit::Second => String::from("s"), Unit::MilliSecond => String::from("ms"), Unit::MicroSecond => String::from("µs"), } } /// Returns the Second value formatted for the Unit. pub fn format(self, value: Second) -> String { match self { Unit::Second => format!("{value:.3}"), Unit::MilliSecond => format!("{:.1}", value * 1e3), Unit::MicroSecond => format!("{:.1}", value * 1e6), } } } #[test] fn test_unit_short_name() { assert_eq!("s", Unit::Second.short_name()); assert_eq!("ms", Unit::MilliSecond.short_name()); assert_eq!("µs", Unit::MicroSecond.short_name()); } // Note - the values are rounded when formatted. #[test] fn test_unit_format() { let value: Second = 123.456789; assert_eq!("123.457", Unit::Second.format(value)); assert_eq!("123456.8", Unit::MilliSecond.format(value)); assert_eq!("1234.6", Unit::MicroSecond.format(0.00123456)); }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/util/exit_code.rs
src/util/exit_code.rs
use std::process::ExitStatus; #[cfg(unix)] pub fn extract_exit_code(status: ExitStatus) -> Option<i32> { use std::os::unix::process::ExitStatusExt; // From the ExitStatus::code documentation: // // "On Unix, this will return None if the process was terminated by a signal." // // In that case, ExitStatusExt::signal should never return None. // // To differentiate between "normal" exit codes and signals, we are using a technique // similar to bash (https://tldp.org/LDP/abs/html/exitcodes.html) and add 128 to the // signal value. status.code().or_else(|| status.signal().map(|s| s + 128)) } #[cfg(not(unix))] pub fn extract_exit_code(status: ExitStatus) -> Option<i32> { status.code() }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/util/mod.rs
src/util/mod.rs
pub mod exit_code; pub mod min_max; pub mod number; pub mod randomized_environment_offset; pub mod units;
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/util/min_max.rs
src/util/min_max.rs
/// A max function for f64's without NaNs pub fn max(vals: &[f64]) -> f64 { *vals .iter() .max_by(|a, b| a.partial_cmp(b).unwrap()) .unwrap() } /// A min function for f64's without NaNs pub fn min(vals: &[f64]) -> f64 { *vals .iter() .min_by(|a, b| a.partial_cmp(b).unwrap()) .unwrap() } #[test] fn test_max() { let assert_float_eq = |a: f64, b: f64| { assert!((a - b).abs() < f64::EPSILON); }; assert_float_eq(1.0, max(&[1.0])); assert_float_eq(-1.0, max(&[-1.0])); assert_float_eq(-1.0, max(&[-2.0, -1.0])); assert_float_eq(1.0, max(&[-1.0, 1.0])); assert_float_eq(1.0, max(&[-1.0, 1.0, 0.0])); }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/util/randomized_environment_offset.rs
src/util/randomized_environment_offset.rs
/// Returns a string with a random length. This value will be set as an environment /// variable to account for offset effects. See [1] for more details. /// /// [1] Mytkowicz, 2009. Producing Wrong Data Without Doing Anything Obviously Wrong!. /// Sigplan Notices - SIGPLAN. 44. 265-276. 10.1145/1508284.1508275. pub fn value() -> String { "X".repeat(rand::random::<usize>() % 4096usize) }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/benchmark/relative_speed.rs
src/benchmark/relative_speed.rs
use std::cmp::Ordering; use super::benchmark_result::BenchmarkResult; use crate::{options::SortOrder, util::units::Scalar}; #[derive(Debug)] pub struct BenchmarkResultWithRelativeSpeed<'a> { pub result: &'a BenchmarkResult, pub relative_speed: Scalar, pub relative_speed_stddev: Option<Scalar>, pub is_reference: bool, // Less means faster pub relative_ordering: Ordering, } pub fn compare_mean_time(l: &BenchmarkResult, r: &BenchmarkResult) -> Ordering { l.mean.partial_cmp(&r.mean).unwrap_or(Ordering::Equal) } pub fn fastest_of(results: &[BenchmarkResult]) -> &BenchmarkResult { results .iter() .min_by(|&l, &r| compare_mean_time(l, r)) .expect("at least one benchmark result") } fn compute_relative_speeds<'a>( results: &'a [BenchmarkResult], reference: &'a BenchmarkResult, sort_order: SortOrder, ) -> Vec<BenchmarkResultWithRelativeSpeed<'a>> { let mut results: Vec<_> = results .iter() .map(|result| { let is_reference = result == reference; let relative_ordering = compare_mean_time(result, reference); if result.mean == 0.0 { return BenchmarkResultWithRelativeSpeed { result, relative_speed: if is_reference { 1.0 } else { f64::INFINITY }, relative_speed_stddev: None, is_reference, relative_ordering, }; } let ratio = match relative_ordering { Ordering::Less => reference.mean / result.mean, Ordering::Equal => 1.0, Ordering::Greater => result.mean / reference.mean, }; // https://en.wikipedia.org/wiki/Propagation_of_uncertainty#Example_formulas // Covariance asssumed to be 0, i.e. variables are assumed to be independent let ratio_stddev = match (result.stddev, reference.stddev) { (Some(result_stddev), Some(fastest_stddev)) => Some( ratio * ((result_stddev / result.mean).powi(2) + (fastest_stddev / reference.mean).powi(2)) .sqrt(), ), _ => None, }; BenchmarkResultWithRelativeSpeed { result, relative_speed: ratio, relative_speed_stddev: ratio_stddev, is_reference, relative_ordering, } }) .collect(); match sort_order { SortOrder::Command => {} SortOrder::MeanTime => { results.sort_unstable_by(|r1, r2| compare_mean_time(r1.result, r2.result)); } } results } pub fn compute_with_check_from_reference<'a>( results: &'a [BenchmarkResult], reference: &'a BenchmarkResult, sort_order: SortOrder, ) -> Option<Vec<BenchmarkResultWithRelativeSpeed<'a>>> { if fastest_of(results).mean == 0.0 || reference.mean == 0.0 { return None; } Some(compute_relative_speeds(results, reference, sort_order)) } pub fn compute_with_check( results: &[BenchmarkResult], sort_order: SortOrder, ) -> Option<Vec<BenchmarkResultWithRelativeSpeed<'_>>> { let fastest = fastest_of(results); if fastest.mean == 0.0 { return None; } Some(compute_relative_speeds(results, fastest, sort_order)) } /// Same as compute_with_check, potentially resulting in relative speeds of infinity pub fn compute( results: &[BenchmarkResult], sort_order: SortOrder, ) -> Vec<BenchmarkResultWithRelativeSpeed<'_>> { let fastest = fastest_of(results); compute_relative_speeds(results, fastest, sort_order) } #[cfg(test)] fn create_result(name: &str, mean: Scalar) -> BenchmarkResult { use std::collections::BTreeMap; BenchmarkResult { command: name.into(), command_with_unused_parameters: name.into(), mean, stddev: Some(1.0), median: mean, user: mean, system: 0.0, min: mean, max: mean, times: None, memory_usage_byte: None, exit_codes: Vec::new(), parameters: BTreeMap::new(), } } #[test] fn test_compute_relative_speed() { use approx::assert_relative_eq; let results = vec![ create_result("cmd1", 3.0), create_result("cmd2", 2.0), create_result("cmd3", 5.0), ]; let annotated_results = compute_with_check(&results, SortOrder::Command).unwrap(); assert_relative_eq!(1.5, annotated_results[0].relative_speed); assert_relative_eq!(1.0, annotated_results[1].relative_speed); assert_relative_eq!(2.5, annotated_results[2].relative_speed); } #[test] fn test_compute_relative_speed_with_reference() { use approx::assert_relative_eq; let results = vec![create_result("cmd2", 2.0), create_result("cmd3", 5.0)]; let reference = create_result("cmd2", 4.0); let annotated_results = compute_with_check_from_reference(&results, &reference, SortOrder::Command).unwrap(); assert_relative_eq!(2.0, annotated_results[0].relative_speed); assert_relative_eq!(1.25, annotated_results[1].relative_speed); } #[test] fn test_compute_relative_speed_for_zero_times() { let results = vec![create_result("cmd1", 1.0), create_result("cmd2", 0.0)]; let annotated_results = compute_with_check(&results, SortOrder::Command); assert!(annotated_results.is_none()); }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/benchmark/timing_result.rs
src/benchmark/timing_result.rs
use crate::util::units::Second; /// Results from timing a single command #[derive(Debug, Default, Copy, Clone)] pub struct TimingResult { /// Wall clock time pub time_real: Second, /// Time spent in user mode pub time_user: Second, /// Time spent in kernel mode pub time_system: Second, /// Maximum amount of memory used, in bytes pub memory_usage_byte: u64, }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/benchmark/executor.rs
src/benchmark/executor.rs
#[cfg(windows)] use std::os::windows::process::CommandExt; use std::process::ExitStatus; use crate::command::Command; use crate::options::{ CmdFailureAction, CommandInputPolicy, CommandOutputPolicy, Options, OutputStyleOption, Shell, }; use crate::output::progress_bar::get_progress_bar; use crate::timer::{execute_and_measure, TimerResult}; use crate::util::randomized_environment_offset; use crate::util::units::Second; use super::timing_result::TimingResult; use anyhow::{bail, Context, Result}; use statistical::mean; pub enum BenchmarkIteration { NonBenchmarkRun, Warmup(u64), Benchmark(u64), } impl BenchmarkIteration { pub fn to_env_var_value(&self) -> Option<String> { match self { BenchmarkIteration::NonBenchmarkRun => None, BenchmarkIteration::Warmup(i) => Some(format!("warmup-{}", i)), BenchmarkIteration::Benchmark(i) => Some(format!("{}", i)), } } } pub trait Executor { /// Run the given command and measure the execution time fn run_command_and_measure( &self, command: &Command<'_>, iteration: BenchmarkIteration, command_failure_action: Option<CmdFailureAction>, output_policy: &CommandOutputPolicy, ) -> Result<(TimingResult, ExitStatus)>; /// Perform a calibration of this executor. For example, /// when running commands through a shell, we need to /// measure the shell spawning time separately in order /// to subtract it from the full runtime later. fn calibrate(&mut self) -> Result<()>; /// Return the time overhead for this executor when /// performing a measurement. This should return the time /// that is being used in addition to the actual runtime /// of the command. fn time_overhead(&self) -> Second; } fn run_command_and_measure_common( mut command: std::process::Command, iteration: BenchmarkIteration, command_failure_action: CmdFailureAction, command_input_policy: &CommandInputPolicy, command_output_policy: &CommandOutputPolicy, command_name: &str, ) -> Result<TimerResult> { let stdin = command_input_policy.get_stdin()?; let (stdout, stderr) = command_output_policy.get_stdout_stderr()?; command.stdin(stdin).stdout(stdout).stderr(stderr); command.env( "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET", randomized_environment_offset::value(), ); if let Some(value) = iteration.to_env_var_value() { command.env("HYPERFINE_ITERATION", value); } let result = execute_and_measure(command) .with_context(|| format!("Failed to run command '{command_name}'"))?; if !result.status.success() { use crate::util::exit_code::extract_exit_code; let should_fail = match command_failure_action { CmdFailureAction::RaiseError => true, CmdFailureAction::IgnoreAllFailures => false, CmdFailureAction::IgnoreSpecificFailures(ref codes) => { // Only fail if the exit code is not in the list of codes to ignore if let Some(exit_code) = extract_exit_code(result.status) { !codes.contains(&exit_code) } else { // If we can't extract an exit code, treat it as a failure true } } }; if should_fail { let when = match iteration { BenchmarkIteration::NonBenchmarkRun => "a non-benchmark run".to_string(), BenchmarkIteration::Warmup(0) => "the first warmup run".to_string(), BenchmarkIteration::Warmup(i) => format!("warmup iteration {i}"), BenchmarkIteration::Benchmark(0) => "the first benchmark run".to_string(), BenchmarkIteration::Benchmark(i) => format!("benchmark iteration {i}"), }; bail!( "{cause} in {when}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \ Alternatively, use the '--show-output' option to debug what went wrong.", cause=result.status.code().map_or( "The process has been terminated by a signal".into(), |c| format!("Command terminated with non-zero exit code {c}") ), ); } } Ok(result) } pub struct RawExecutor<'a> { options: &'a Options, } impl<'a> RawExecutor<'a> { pub fn new(options: &'a Options) -> Self { RawExecutor { options } } } impl Executor for RawExecutor<'_> { fn run_command_and_measure( &self, command: &Command<'_>, iteration: BenchmarkIteration, command_failure_action: Option<CmdFailureAction>, output_policy: &CommandOutputPolicy, ) -> Result<(TimingResult, ExitStatus)> { let result = run_command_and_measure_common( command.get_command()?, iteration, command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()), &self.options.command_input_policy, output_policy, &command.get_command_line(), )?; Ok(( TimingResult { time_real: result.time_real, time_user: result.time_user, time_system: result.time_system, memory_usage_byte: result.memory_usage_byte, }, result.status, )) } fn calibrate(&mut self) -> Result<()> { Ok(()) } fn time_overhead(&self) -> Second { 0.0 } } pub struct ShellExecutor<'a> { options: &'a Options, shell: &'a Shell, shell_spawning_time: Option<TimingResult>, } impl<'a> ShellExecutor<'a> { pub fn new(shell: &'a Shell, options: &'a Options) -> Self { ShellExecutor { shell, options, shell_spawning_time: None, } } } impl Executor for ShellExecutor<'_> { fn run_command_and_measure( &self, command: &Command<'_>, iteration: BenchmarkIteration, command_failure_action: Option<CmdFailureAction>, output_policy: &CommandOutputPolicy, ) -> Result<(TimingResult, ExitStatus)> { let on_windows_cmd = cfg!(windows) && *self.shell == Shell::Default("cmd.exe"); let mut command_builder = self.shell.command(); command_builder.arg(if on_windows_cmd { "/C" } else { "-c" }); // Windows needs special treatment for its behavior on parsing cmd arguments if on_windows_cmd { #[cfg(windows)] command_builder.raw_arg(command.get_command_line()); } else { command_builder.arg(command.get_command_line()); } let mut result = run_command_and_measure_common( command_builder, iteration, command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()), &self.options.command_input_policy, output_policy, &command.get_command_line(), )?; // Subtract shell spawning time if let Some(spawning_time) = self.shell_spawning_time { result.time_real = (result.time_real - spawning_time.time_real).max(0.0); result.time_user = (result.time_user - spawning_time.time_user).max(0.0); result.time_system = (result.time_system - spawning_time.time_system).max(0.0); } Ok(( TimingResult { time_real: result.time_real, time_user: result.time_user, time_system: result.time_system, memory_usage_byte: result.memory_usage_byte, }, result.status, )) } /// Measure the average shell spawning time fn calibrate(&mut self) -> Result<()> { const COUNT: u64 = 50; let progress_bar = if self.options.output_style != OutputStyleOption::Disabled { Some(get_progress_bar( COUNT, "Measuring shell spawning time", self.options.output_style, )) } else { None }; let mut times_real: Vec<Second> = vec![]; let mut times_user: Vec<Second> = vec![]; let mut times_system: Vec<Second> = vec![]; for _ in 0..COUNT { // Just run the shell without any command let res = self.run_command_and_measure( &Command::new(None, ""), BenchmarkIteration::NonBenchmarkRun, None, &CommandOutputPolicy::Null, ); match res { Err(_) => { let shell_cmd = if cfg!(windows) { format!("{} /C \"\"", self.shell) } else { format!("{} -c \"\"", self.shell) }; bail!( "Could not measure shell execution time. Make sure you can run '{}'.", shell_cmd ); } Ok((r, _)) => { times_real.push(r.time_real); times_user.push(r.time_user); times_system.push(r.time_system); } } if let Some(bar) = progress_bar.as_ref() { bar.inc(1) } } if let Some(bar) = progress_bar.as_ref() { bar.finish_and_clear() } self.shell_spawning_time = Some(TimingResult { time_real: mean(&times_real), time_user: mean(&times_user), time_system: mean(&times_system), memory_usage_byte: 0, }); Ok(()) } fn time_overhead(&self) -> Second { self.shell_spawning_time.unwrap().time_real } } #[derive(Clone)] pub struct MockExecutor { shell: Option<String>, } impl MockExecutor { pub fn new(shell: Option<String>) -> Self { MockExecutor { shell } } fn extract_time<S: AsRef<str>>(sleep_command: S) -> Second { assert!(sleep_command.as_ref().starts_with("sleep ")); sleep_command .as_ref() .trim_start_matches("sleep ") .parse::<Second>() .unwrap() } } impl Executor for MockExecutor { fn run_command_and_measure( &self, command: &Command<'_>, _iteration: BenchmarkIteration, _command_failure_action: Option<CmdFailureAction>, _output_policy: &CommandOutputPolicy, ) -> Result<(TimingResult, ExitStatus)> { #[cfg(unix)] let status = { use std::os::unix::process::ExitStatusExt; ExitStatus::from_raw(0) }; #[cfg(windows)] let status = { use std::os::windows::process::ExitStatusExt; ExitStatus::from_raw(0) }; Ok(( TimingResult { time_real: Self::extract_time(command.get_command_line()), time_user: 0.0, time_system: 0.0, memory_usage_byte: 0, }, status, )) } fn calibrate(&mut self) -> Result<()> { Ok(()) } fn time_overhead(&self) -> Second { match &self.shell { None => 0.0, Some(shell) => Self::extract_time(shell), } } } #[test] fn test_mock_executor_extract_time() { assert_eq!(MockExecutor::extract_time("sleep 0.1"), 0.1); }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/benchmark/mod.rs
src/benchmark/mod.rs
pub mod benchmark_result; pub mod executor; pub mod relative_speed; pub mod scheduler; pub mod timing_result; use std::cmp; use crate::benchmark::executor::BenchmarkIteration; use crate::command::Command; use crate::options::{ CmdFailureAction, CommandOutputPolicy, ExecutorKind, Options, OutputStyleOption, }; use crate::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD}; use crate::output::format::{format_duration, format_duration_unit}; use crate::output::progress_bar::get_progress_bar; use crate::output::warnings::{OutlierWarningOptions, Warnings}; use crate::parameter::ParameterNameAndValue; use crate::util::exit_code::extract_exit_code; use crate::util::min_max::{max, min}; use crate::util::units::Second; use benchmark_result::BenchmarkResult; use timing_result::TimingResult; use anyhow::{anyhow, Result}; use colored::*; use statistical::{mean, median, standard_deviation}; use self::executor::Executor; /// Threshold for warning about fast execution time pub const MIN_EXECUTION_TIME: Second = 5e-3; pub struct Benchmark<'a> { number: usize, command: &'a Command<'a>, options: &'a Options, executor: &'a dyn Executor, } impl<'a> Benchmark<'a> { pub fn new( number: usize, command: &'a Command<'a>, options: &'a Options, executor: &'a dyn Executor, ) -> Self { Benchmark { number, command, options, executor, } } /// Run setup, cleanup, or preparation commands fn run_intermediate_command( &self, command: &Command<'_>, error_output: &'static str, output_policy: &CommandOutputPolicy, ) -> Result<TimingResult> { self.executor .run_command_and_measure( command, executor::BenchmarkIteration::NonBenchmarkRun, Some(CmdFailureAction::RaiseError), output_policy, ) .map(|r| r.0) .map_err(|_| anyhow!(error_output)) } /// Run the command specified by `--setup`. fn run_setup_command( &self, parameters: impl IntoIterator<Item = ParameterNameAndValue<'a>>, output_policy: &CommandOutputPolicy, ) -> Result<TimingResult> { let command = self .options .setup_command .as_ref() .map(|setup_command| Command::new_parametrized(None, setup_command, parameters)); let error_output = "The setup command terminated with a non-zero exit code. \ Append ' || true' to the command if you are sure that this can be ignored."; Ok(command .map(|cmd| self.run_intermediate_command(&cmd, error_output, output_policy)) .transpose()? .unwrap_or_default()) } /// Run the command specified by `--cleanup`. fn run_cleanup_command( &self, parameters: impl IntoIterator<Item = ParameterNameAndValue<'a>>, output_policy: &CommandOutputPolicy, ) -> Result<TimingResult> { let command = self .options .cleanup_command .as_ref() .map(|cleanup_command| Command::new_parametrized(None, cleanup_command, parameters)); let error_output = "The cleanup command terminated with a non-zero exit code. \ Append ' || true' to the command if you are sure that this can be ignored."; Ok(command .map(|cmd| self.run_intermediate_command(&cmd, error_output, output_policy)) .transpose()? .unwrap_or_default()) } /// Run the command specified by `--prepare`. fn run_preparation_command( &self, command: &Command<'_>, output_policy: &CommandOutputPolicy, ) -> Result<TimingResult> { let error_output = "The preparation command terminated with a non-zero exit code. \ Append ' || true' to the command if you are sure that this can be ignored."; self.run_intermediate_command(command, error_output, output_policy) } /// Run the command specified by `--conclude`. fn run_conclusion_command( &self, command: &Command<'_>, output_policy: &CommandOutputPolicy, ) -> Result<TimingResult> { let error_output = "The conclusion command terminated with a non-zero exit code. \ Append ' || true' to the command if you are sure that this can be ignored."; self.run_intermediate_command(command, error_output, output_policy) } /// Run the benchmark for a single command pub fn run(&self) -> Result<BenchmarkResult> { if self.options.output_style != OutputStyleOption::Disabled { println!( "{}{}: {}", "Benchmark ".bold(), (self.number + 1).to_string().bold(), self.command.get_name_with_unused_parameters(), ); } let mut times_real: Vec<Second> = vec![]; let mut times_user: Vec<Second> = vec![]; let mut times_system: Vec<Second> = vec![]; let mut memory_usage_byte: Vec<u64> = vec![]; let mut exit_codes: Vec<Option<i32>> = vec![]; let mut all_succeeded = true; let output_policy = &self.options.command_output_policies[self.number]; let preparation_command = self.options.preparation_command.as_ref().map(|values| { let preparation_command = if values.len() == 1 { &values[0] } else { &values[self.number] }; Command::new_parametrized( None, preparation_command, self.command.get_parameters().iter().cloned(), ) }); let run_preparation_command = || { preparation_command .as_ref() .map(|cmd| self.run_preparation_command(cmd, output_policy)) .transpose() }; let conclusion_command = self.options.conclusion_command.as_ref().map(|values| { let conclusion_command = if values.len() == 1 { &values[0] } else { &values[self.number] }; Command::new_parametrized( None, conclusion_command, self.command.get_parameters().iter().cloned(), ) }); let run_conclusion_command = || { conclusion_command .as_ref() .map(|cmd| self.run_conclusion_command(cmd, output_policy)) .transpose() }; self.run_setup_command(self.command.get_parameters().iter().cloned(), output_policy)?; // Warmup phase if self.options.warmup_count > 0 { let progress_bar = if self.options.output_style != OutputStyleOption::Disabled { Some(get_progress_bar( self.options.warmup_count, "Performing warmup runs", self.options.output_style, )) } else { None }; for i in 0..self.options.warmup_count { let _ = run_preparation_command()?; let _ = self.executor.run_command_and_measure( self.command, BenchmarkIteration::Warmup(i), None, output_policy, )?; let _ = run_conclusion_command()?; if let Some(bar) = progress_bar.as_ref() { bar.inc(1) } } if let Some(bar) = progress_bar.as_ref() { bar.finish_and_clear() } } // Set up progress bar (and spinner for initial measurement) let progress_bar = if self.options.output_style != OutputStyleOption::Disabled { Some(get_progress_bar( self.options.run_bounds.min, "Initial time measurement", self.options.output_style, )) } else { None }; let preparation_result = run_preparation_command()?; let preparation_overhead = preparation_result.map_or(0.0, |res| res.time_real + self.executor.time_overhead()); // Initial timing run let (res, status) = self.executor.run_command_and_measure( self.command, BenchmarkIteration::Benchmark(0), None, output_policy, )?; let success = status.success(); let conclusion_result = run_conclusion_command()?; let conclusion_overhead = conclusion_result.map_or(0.0, |res| res.time_real + self.executor.time_overhead()); // Determine number of benchmark runs let runs_in_min_time = (self.options.min_benchmarking_time / (res.time_real + self.executor.time_overhead() + preparation_overhead + conclusion_overhead)) as u64; let count = { let min = cmp::max(runs_in_min_time, self.options.run_bounds.min); self.options .run_bounds .max .as_ref() .map(|max| cmp::min(min, *max)) .unwrap_or(min) }; let count_remaining = count - 1; // Save the first result times_real.push(res.time_real); times_user.push(res.time_user); times_system.push(res.time_system); memory_usage_byte.push(res.memory_usage_byte); exit_codes.push(extract_exit_code(status)); all_succeeded = all_succeeded && success; // Re-configure the progress bar if let Some(bar) = progress_bar.as_ref() { bar.set_length(count) } if let Some(bar) = progress_bar.as_ref() { bar.inc(1) } // Gather statistics (perform the actual benchmark) for i in 0..count_remaining { run_preparation_command()?; let msg = { let mean = format_duration(mean(&times_real), self.options.time_unit); format!("Current estimate: {}", mean.to_string().green()) }; if let Some(bar) = progress_bar.as_ref() { bar.set_message(msg.to_owned()) } let (res, status) = self.executor.run_command_and_measure( self.command, BenchmarkIteration::Benchmark(i + 1), None, output_policy, )?; let success = status.success(); times_real.push(res.time_real); times_user.push(res.time_user); times_system.push(res.time_system); memory_usage_byte.push(res.memory_usage_byte); exit_codes.push(extract_exit_code(status)); all_succeeded = all_succeeded && success; if let Some(bar) = progress_bar.as_ref() { bar.inc(1) } run_conclusion_command()?; } if let Some(bar) = progress_bar.as_ref() { bar.finish_and_clear() } // Compute statistical quantities let t_num = times_real.len(); let t_mean = mean(&times_real); let t_stddev = if times_real.len() > 1 { Some(standard_deviation(&times_real, Some(t_mean))) } else { None }; let t_median = median(&times_real); let t_min = min(&times_real); let t_max = max(&times_real); let user_mean = mean(&times_user); let system_mean = mean(&times_system); // Formatting and console output let (mean_str, time_unit) = format_duration_unit(t_mean, self.options.time_unit); let min_str = format_duration(t_min, Some(time_unit)); let max_str = format_duration(t_max, Some(time_unit)); let num_str = format!("{t_num} runs"); let user_str = format_duration(user_mean, Some(time_unit)); let system_str = format_duration(system_mean, Some(time_unit)); if self.options.output_style != OutputStyleOption::Disabled { if times_real.len() == 1 { println!( " Time ({} ≡): {:>8} {:>8} [User: {}, System: {}]", "abs".green().bold(), mean_str.green().bold(), " ", // alignment user_str.blue(), system_str.blue() ); } else { let stddev_str = format_duration(t_stddev.unwrap(), Some(time_unit)); println!( " Time ({} ± {}): {:>8} ± {:>8} [User: {}, System: {}]", "mean".green().bold(), "σ".green(), mean_str.green().bold(), stddev_str.green(), user_str.blue(), system_str.blue() ); println!( " Range ({} … {}): {:>8} … {:>8} {}", "min".cyan(), "max".purple(), min_str.cyan(), max_str.purple(), num_str.dimmed() ); } } // Warnings let mut warnings = vec![]; // Check execution time if matches!(self.options.executor_kind, ExecutorKind::Shell(_)) && times_real.iter().any(|&t| t < MIN_EXECUTION_TIME) { warnings.push(Warnings::FastExecutionTime); } // Check program exit codes if !all_succeeded { warnings.push(Warnings::NonZeroExitCode); } // Run outlier detection let scores = modified_zscores(&times_real); let outlier_warning_options = OutlierWarningOptions { warmup_in_use: self.options.warmup_count > 0, prepare_in_use: self .options .preparation_command .as_ref() .map(|v| v.len()) .unwrap_or(0) > 0, }; if scores[0] > OUTLIER_THRESHOLD { warnings.push(Warnings::SlowInitialRun( times_real[0], outlier_warning_options, )); } else if scores.iter().any(|&s| s.abs() > OUTLIER_THRESHOLD) { warnings.push(Warnings::OutliersDetected(outlier_warning_options)); } if !warnings.is_empty() { eprintln!(" "); for warning in &warnings { eprintln!(" {}: {}", "Warning".yellow(), warning); } } if self.options.output_style != OutputStyleOption::Disabled { println!(" "); } self.run_cleanup_command(self.command.get_parameters().iter().cloned(), output_policy)?; Ok(BenchmarkResult { command: self.command.get_name(), command_with_unused_parameters: self.command.get_name_with_unused_parameters(), mean: t_mean, stddev: t_stddev, median: t_median, user: user_mean, system: system_mean, min: t_min, max: t_max, times: Some(times_real), memory_usage_byte: Some(memory_usage_byte), exit_codes, parameters: self .command .get_parameters() .iter() .map(|(name, value)| (name.to_string(), value.to_string())) .collect(), }) } }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/benchmark/benchmark_result.rs
src/benchmark/benchmark_result.rs
use std::collections::BTreeMap; use serde::Serialize; use crate::util::units::Second; /// Set of values that will be exported. // NOTE: `serde` is used for JSON serialization, but not for CSV serialization due to the // `parameters` map. Update `src/hyperfine/export/csv.rs` with new fields, as appropriate. #[derive(Debug, Default, Clone, Serialize, PartialEq)] pub struct BenchmarkResult { /// The full command line of the program that is being benchmarked pub command: String, /// The full command line of the program that is being benchmarked, possibly including a list of /// parameters that were not used in the command line template. #[serde(skip_serializing)] pub command_with_unused_parameters: String, /// The average run time pub mean: Second, /// The standard deviation of all run times. Not available if only one run has been performed pub stddev: Option<Second>, /// The median run time pub median: Second, /// Time spent in user mode pub user: Second, /// Time spent in kernel mode pub system: Second, /// Minimum of all measured times pub min: Second, /// Maximum of all measured times pub max: Second, /// All run time measurements #[serde(skip_serializing_if = "Option::is_none")] pub times: Option<Vec<Second>>, /// Maximum memory usage of the process, in bytes #[serde(skip_serializing_if = "Option::is_none")] pub memory_usage_byte: Option<Vec<u64>>, /// Exit codes of all command invocations pub exit_codes: Vec<Option<i32>>, /// Parameter values for this benchmark #[serde(skip_serializing_if = "BTreeMap::is_empty")] pub parameters: BTreeMap<String, String>, }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false
sharkdp/hyperfine
https://github.com/sharkdp/hyperfine/blob/975fe108c4ee7bd2600d10758207b44ca3dae738/src/benchmark/scheduler.rs
src/benchmark/scheduler.rs
use super::benchmark_result::BenchmarkResult; use super::executor::{Executor, MockExecutor, RawExecutor, ShellExecutor}; use super::{relative_speed, Benchmark}; use colored::*; use std::cmp::Ordering; use crate::command::{Command, Commands}; use crate::export::ExportManager; use crate::options::{ExecutorKind, Options, OutputStyleOption, SortOrder}; use anyhow::Result; pub struct Scheduler<'a> { commands: &'a Commands<'a>, options: &'a Options, export_manager: &'a ExportManager, results: Vec<BenchmarkResult>, } impl<'a> Scheduler<'a> { pub fn new( commands: &'a Commands, options: &'a Options, export_manager: &'a ExportManager, ) -> Self { Self { commands, options, export_manager, results: vec![], } } pub fn run_benchmarks(&mut self) -> Result<()> { let mut executor: Box<dyn Executor> = match self.options.executor_kind { ExecutorKind::Raw => Box::new(RawExecutor::new(self.options)), ExecutorKind::Mock(ref shell) => Box::new(MockExecutor::new(shell.clone())), ExecutorKind::Shell(ref shell) => Box::new(ShellExecutor::new(shell, self.options)), }; let reference = self .options .reference_command .as_ref() .map(|cmd| Command::new(self.options.reference_name.as_deref(), cmd)); executor.calibrate()?; for (number, cmd) in reference.iter().chain(self.commands.iter()).enumerate() { self.results .push(Benchmark::new(number, cmd, self.options, &*executor).run()?); // We export results after each individual benchmark, because // we would risk losing them if a later benchmark fails. self.export_manager.write_results(&self.results, true)?; } Ok(()) } pub fn print_relative_speed_comparison(&self) { if self.options.output_style == OutputStyleOption::Disabled { return; } if self.results.len() < 2 { return; } let reference = self .options .reference_command .as_ref() .map(|_| &self.results[0]) .unwrap_or_else(|| relative_speed::fastest_of(&self.results)); if let Some(annotated_results) = relative_speed::compute_with_check_from_reference( &self.results, reference, self.options.sort_order_speed_comparison, ) { match self.options.sort_order_speed_comparison { SortOrder::MeanTime => { println!("{}", "Summary".bold()); let reference = annotated_results.iter().find(|r| r.is_reference).unwrap(); let others = annotated_results.iter().filter(|r| !r.is_reference); println!( " {} ran", reference.result.command_with_unused_parameters.cyan() ); for item in others { let stddev = if let Some(stddev) = item.relative_speed_stddev { format!(" ± {}", format!("{:.2}", stddev).green()) } else { "".into() }; let comparator = match item.relative_ordering { Ordering::Less => format!( "{}{} times slower than", format!("{:8.2}", item.relative_speed).bold().green(), stddev ), Ordering::Greater => format!( "{}{} times faster than", format!("{:8.2}", item.relative_speed).bold().green(), stddev ), Ordering::Equal => format!( " As fast ({}{}) as", format!("{:.2}", item.relative_speed).bold().green(), stddev ), }; println!( "{} {}", comparator, &item.result.command_with_unused_parameters.magenta() ); } } SortOrder::Command => { println!("{}", "Relative speed comparison".bold()); for item in annotated_results { println!( " {}{} {}", format!("{:10.2}", item.relative_speed).bold().green(), if item.is_reference { " ".into() } else if let Some(stddev) = item.relative_speed_stddev { format!(" ± {}", format!("{stddev:5.2}").green()) } else { " ".into() }, &item.result.command_with_unused_parameters, ); } } } } else { eprintln!( "{}: The benchmark comparison could not be computed as some benchmark times are zero. \ This could be caused by background interference during the initial calibration phase \ of hyperfine, in combination with very fast commands (faster than a few milliseconds). \ Try to re-run the benchmark on a quiet system. If you did not do so already, try the \ --shell=none/-N option. If it does not help either, you command is most likely too fast \ to be accurately benchmarked by hyperfine.", "Note".bold().red() ); } } pub fn final_export(&self) -> Result<()> { self.export_manager.write_results(&self.results, false) } } #[cfg(test)] fn generate_results(args: &[&'static str]) -> Result<Vec<BenchmarkResult>> { use crate::cli::get_cli_arguments; let args = ["hyperfine", "--debug-mode", "--style=none"] .iter() .chain(args); let cli_arguments = get_cli_arguments(args); let mut options = Options::from_cli_arguments(&cli_arguments)?; assert_eq!(options.executor_kind, ExecutorKind::Mock(None)); let commands = Commands::from_cli_arguments(&cli_arguments)?; let export_manager = ExportManager::from_cli_arguments( &cli_arguments, options.time_unit, options.sort_order_exports, )?; options.validate_against_command_list(&commands)?; let mut scheduler = Scheduler::new(&commands, &options, &export_manager); scheduler.run_benchmarks()?; Ok(scheduler.results) } #[test] fn scheduler_basic() -> Result<()> { insta::assert_yaml_snapshot!(generate_results(&["--runs=2", "sleep 0.123", "sleep 0.456"])?, @r#" - command: sleep 0.123 mean: 0.123 stddev: 0 median: 0.123 user: 0 system: 0 min: 0.123 max: 0.123 times: - 0.123 - 0.123 memory_usage_byte: - 0 - 0 exit_codes: - 0 - 0 - command: sleep 0.456 mean: 0.456 stddev: 0 median: 0.456 user: 0 system: 0 min: 0.456 max: 0.456 times: - 0.456 - 0.456 memory_usage_byte: - 0 - 0 exit_codes: - 0 - 0 "#); Ok(()) }
rust
Apache-2.0
975fe108c4ee7bd2600d10758207b44ca3dae738
2026-01-04T15:36:39.863758Z
false