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/src/terminal.rs | src/terminal.rs | use std::{
io::IsTerminal,
sync::atomic::{AtomicI32, Ordering},
};
use nix::{
errno::Errno,
libc,
sys::signal::{SaFlags, SigAction, SigHandler, SigSet, Signal, killpg, raise, sigaction},
unistd::{self, Pid},
};
static INITIAL_PGID: AtomicI32 = AtomicI32::new(-1);
pub(crate) fn acquire(interactive: bool) {
if interactive && std::io::stdin().is_terminal() {
// see also: https://www.gnu.org/software/libc/manual/html_node/Initializing-the-Shell.html
if unsafe { libc::atexit(restore_terminal) } != 0 {
eprintln!("ERROR: failed to set exit function");
std::process::exit(1);
};
let initial_pgid = take_control();
INITIAL_PGID.store(initial_pgid.into(), Ordering::Relaxed);
unsafe {
// SIGINT has special handling
let ignore = SigAction::new(SigHandler::SigIgn, SaFlags::empty(), SigSet::empty());
sigaction(Signal::SIGQUIT, &ignore).expect("signal ignore");
sigaction(Signal::SIGTSTP, &ignore).expect("signal ignore");
sigaction(Signal::SIGTTIN, &ignore).expect("signal ignore");
sigaction(Signal::SIGTTOU, &ignore).expect("signal ignore");
sigaction(
Signal::SIGTERM,
&SigAction::new(
SigHandler::Handler(sigterm_handler),
SaFlags::empty(),
SigSet::empty(),
),
)
.expect("signal action");
}
// Put ourselves in our own process group, if not already
let shell_pgid = unistd::getpid();
match unistd::setpgid(shell_pgid, shell_pgid) {
// setpgid returns EPERM if we are the session leader (e.g., as a login shell).
// The other cases that return EPERM cannot happen, since we gave our own pid.
// See: setpgid(2)
// Therefore, it is safe to ignore EPERM.
Ok(()) | Err(Errno::EPERM) => (),
Err(_) => {
eprintln!("ERROR: failed to put nushell in its own process group");
std::process::exit(1);
}
}
// Set our possibly new pgid to be in control of terminal
let _ = unistd::tcsetpgrp(unsafe { nu_system::stdin_fd() }, shell_pgid);
}
}
// Inspired by fish's acquire_tty_or_exit
// Returns our original pgid
fn take_control() -> Pid {
let shell_pgid = unistd::getpgrp();
match unistd::tcgetpgrp(unsafe { nu_system::stdin_fd() }) {
Ok(owner_pgid) if owner_pgid == shell_pgid => {
// Common case, nothing to do
return owner_pgid;
}
Ok(owner_pgid) if owner_pgid == unistd::getpid() => {
// This can apparently happen with sudo: https://github.com/fish-shell/fish-shell/issues/7388
let _ = unistd::setpgid(owner_pgid, owner_pgid);
return owner_pgid;
}
_ => (),
}
// Reset all signal handlers to default
let default = SigAction::new(SigHandler::SigDfl, SaFlags::empty(), SigSet::empty());
for sig in Signal::iterator() {
if let Ok(old_act) = unsafe { sigaction(sig, &default) } {
// fish preserves ignored SIGHUP, presumably for nohup support, so let's do the same
if sig == Signal::SIGHUP && old_act.handler() == SigHandler::SigIgn {
let _ = unsafe { sigaction(sig, &old_act) };
}
}
}
for _ in 0..4096 {
match unistd::tcgetpgrp(unsafe { nu_system::stdin_fd() }) {
Ok(owner_pgid) if owner_pgid == shell_pgid => {
// success
return owner_pgid;
}
Ok(owner_pgid) if owner_pgid == Pid::from_raw(0) => {
// Zero basically means something like "not owned" and we can just take it
let _ = unistd::tcsetpgrp(unsafe { nu_system::stdin_fd() }, shell_pgid);
}
Err(Errno::ENOTTY) => {
eprintln!("ERROR: no TTY for interactive shell");
std::process::exit(1);
}
_ => {
// fish also has other heuristics than "too many attempts" for the orphan check, but they're optional
if killpg(shell_pgid, Signal::SIGTTIN).is_err() {
eprintln!("ERROR: failed to SIGTTIN ourselves");
std::process::exit(1);
}
}
}
}
eprintln!("ERROR: failed to take control of the terminal, we might be orphaned");
std::process::exit(1);
}
extern "C" fn restore_terminal() {
// Safety: can only call async-signal-safe functions here
// `tcsetpgrp` and `getpgrp` are async-signal-safe
let initial_pgid = Pid::from_raw(INITIAL_PGID.load(Ordering::Relaxed));
if initial_pgid.as_raw() > 0 && initial_pgid != unistd::getpgrp() {
let _ = unistd::tcsetpgrp(unsafe { nu_system::stdin_fd() }, initial_pgid);
}
}
extern "C" fn sigterm_handler(_signum: libc::c_int) {
// Safety: can only call async-signal-safe functions here
// `restore_terminal`, `sigaction`, `raise`, and `_exit` are all async-signal-safe
restore_terminal();
let default = SigAction::new(SigHandler::SigDfl, SaFlags::empty(), SigSet::empty());
if unsafe { sigaction(Signal::SIGTERM, &default) }.is_err() {
// Failed to set signal handler to default.
// This should not be possible, but if it does happen,
// then this could result in an infinite loop due to the raise below.
// So, we'll just exit immediately if this happens.
unsafe { libc::_exit(1) };
};
if raise(Signal::SIGTERM).is_err() {
unsafe { libc::_exit(1) };
};
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/src/run.rs | src/run.rs | use crate::{
command,
config_files::{self, setup_config},
};
use log::trace;
#[cfg(feature = "plugin")]
use nu_cli::read_plugin_file;
use nu_cli::{EvaluateCommandsOpts, evaluate_commands, evaluate_file, evaluate_repl};
use nu_protocol::{
PipelineData, Spanned,
engine::{EngineState, Stack},
report_shell_error,
};
use nu_utils::perf;
pub(crate) fn run_commands(
engine_state: &mut EngineState,
mut stack: Stack,
parsed_nu_cli_args: command::NushellCliArgs,
use_color: bool,
commands: &Spanned<String>,
input: PipelineData,
entire_start_time: std::time::Instant,
) {
trace!("run_commands");
let start_time = std::time::Instant::now();
let create_scaffold = nu_path::nu_config_dir().is_some_and(|p| !p.exists());
// if the --no-config-file(-n) option is NOT passed, load the plugin file,
// load the default env file or custom (depending on parsed_nu_cli_args.env_file),
// and maybe a custom config file (depending on parsed_nu_cli_args.config_file)
//
// if the --no-config-file(-n) flag is passed, do not load plugin, env, or config files
if parsed_nu_cli_args.no_config_file.is_none() {
#[cfg(feature = "plugin")]
read_plugin_file(engine_state, parsed_nu_cli_args.plugin_file);
perf!("read plugins", start_time, use_color);
let start_time = std::time::Instant::now();
// If we have a env file parameter *OR* we have a login shell parameter, read the env file
if parsed_nu_cli_args.env_file.is_some() || parsed_nu_cli_args.login_shell.is_some() {
config_files::read_config_file(
engine_state,
&mut stack,
parsed_nu_cli_args.env_file,
nu_utils::ConfigFileKind::Env,
create_scaffold,
true,
);
} else {
config_files::read_default_env_file(engine_state, &mut stack)
}
perf!("read env.nu", start_time, use_color);
let start_time = std::time::Instant::now();
let create_scaffold = nu_path::nu_config_dir().is_some_and(|p| !p.exists());
// If we have a config file parameter *OR* we have a login shell parameter, read the config file
if parsed_nu_cli_args.config_file.is_some() || parsed_nu_cli_args.login_shell.is_some() {
config_files::read_config_file(
engine_state,
&mut stack,
parsed_nu_cli_args.config_file,
nu_utils::ConfigFileKind::Config,
create_scaffold,
true,
);
}
perf!("read config.nu", start_time, use_color);
// If we have a login shell parameter, read the login file
let start_time = std::time::Instant::now();
if parsed_nu_cli_args.login_shell.is_some() {
config_files::read_loginshell_file(engine_state, &mut stack, false);
}
perf!("read login.nu", start_time, use_color);
}
// Before running commands, set up the startup time
engine_state.set_startup_time(entire_start_time.elapsed().as_nanos() as i64);
// Regenerate the $nu constant to contain the startup time and any other potential updates
engine_state.generate_nu_constant();
let start_time = std::time::Instant::now();
let result = evaluate_commands(
commands,
engine_state,
&mut stack,
input,
EvaluateCommandsOpts {
table_mode: parsed_nu_cli_args.table_mode,
error_style: parsed_nu_cli_args.error_style,
no_newline: parsed_nu_cli_args.no_newline.is_some(),
},
);
perf!("evaluate_commands", start_time, use_color);
if let Err(err) = result {
report_shell_error(Some(&stack), engine_state, &err);
std::process::exit(err.exit_code().unwrap_or(0));
}
}
pub(crate) fn run_file(
engine_state: &mut EngineState,
mut stack: Stack,
parsed_nu_cli_args: command::NushellCliArgs,
use_color: bool,
script_name: String,
args_to_script: Vec<String>,
input: PipelineData,
) {
trace!("run_file");
// if the --no-config-file(-n) option is NOT passed, load the plugin file,
// load the default env file or custom (depending on parsed_nu_cli_args.env_file),
// and maybe a custom config file (depending on parsed_nu_cli_args.config_file)
//
// if the --no-config-file(-n) flag is passed, do not load plugin, env, or config files
if parsed_nu_cli_args.no_config_file.is_none() {
let start_time = std::time::Instant::now();
let create_scaffold = nu_path::nu_config_dir().is_some_and(|p| !p.exists());
#[cfg(feature = "plugin")]
read_plugin_file(engine_state, parsed_nu_cli_args.plugin_file);
perf!("read plugins", start_time, use_color);
let start_time = std::time::Instant::now();
// only want to load config and env if relative argument is provided.
if parsed_nu_cli_args.env_file.is_some() {
config_files::read_config_file(
engine_state,
&mut stack,
parsed_nu_cli_args.env_file,
nu_utils::ConfigFileKind::Env,
create_scaffold,
true,
);
} else {
config_files::read_default_env_file(engine_state, &mut stack)
}
perf!("read env.nu", start_time, use_color);
let start_time = std::time::Instant::now();
if parsed_nu_cli_args.config_file.is_some() {
config_files::read_config_file(
engine_state,
&mut stack,
parsed_nu_cli_args.config_file,
nu_utils::ConfigFileKind::Config,
create_scaffold,
true,
);
}
perf!("read config.nu", start_time, use_color);
}
// Regenerate the $nu constant to contain the startup time and any other potential updates
engine_state.generate_nu_constant();
let start_time = std::time::Instant::now();
let result = evaluate_file(
script_name,
&args_to_script,
engine_state,
&mut stack,
input,
);
perf!("evaluate_file", start_time, use_color);
if let Err(err) = result {
report_shell_error(Some(&stack), engine_state, &err);
std::process::exit(err.exit_code().unwrap_or(0));
}
}
pub(crate) fn run_repl(
engine_state: &mut EngineState,
mut stack: Stack,
parsed_nu_cli_args: command::NushellCliArgs,
entire_start_time: std::time::Instant,
) -> Result<(), miette::ErrReport> {
trace!("run_repl");
let start_time = std::time::Instant::now();
if parsed_nu_cli_args.no_config_file.is_none() {
setup_config(
engine_state,
&mut stack,
#[cfg(feature = "plugin")]
parsed_nu_cli_args.plugin_file,
parsed_nu_cli_args.config_file,
parsed_nu_cli_args.env_file,
parsed_nu_cli_args.login_shell.is_some(),
);
}
// Reload use_color from config in case it's different from the default value
let use_color = engine_state
.get_config()
.use_ansi_coloring
.get(engine_state);
perf!("setup_config", start_time, use_color);
let start_time = std::time::Instant::now();
let ret_val = evaluate_repl(
engine_state,
stack,
parsed_nu_cli_args.execute,
parsed_nu_cli_args.no_std_lib,
entire_start_time,
);
perf!("evaluate_repl", start_time, use_color);
ret_val
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/src/main.rs | src/main.rs | mod command;
mod command_context;
mod config_files;
mod experimental_options;
mod ide;
mod logger;
mod run;
mod signals;
#[cfg(unix)]
mod terminal;
mod test_bins;
use crate::{
command::parse_commandline_args,
config_files::set_config_path,
logger::{configure, logger},
};
use command::gather_commandline_args;
use log::{Level, trace};
use miette::Result;
use nu_cli::gather_parent_env_vars;
use nu_engine::{convert_env_values, exit::cleanup_exit};
use nu_lsp::LanguageServer;
use nu_path::canonicalize_with;
use nu_protocol::{
ByteStream, Config, IntoValue, PipelineData, ShellError, Span, Spanned, Type, Value,
engine::{EngineState, Stack},
record, report_shell_error,
};
use nu_std::load_standard_library;
use nu_utils::perf;
use run::{run_commands, run_file, run_repl};
use signals::ctrlc_protection;
use std::{borrow::Cow, path::PathBuf, str::FromStr, sync::Arc};
/// Get the directory where the Nushell executable is located.
fn current_exe_directory() -> PathBuf {
let mut path = std::env::current_exe().expect("current_exe() should succeed");
path.pop();
path
}
/// Get the current working directory from the environment.
fn current_dir_from_environment() -> PathBuf {
if let Ok(cwd) = std::env::current_dir() {
return cwd;
}
if let Ok(cwd) = std::env::var("PWD") {
return cwd.into();
}
if let Some(home) = nu_path::home_dir() {
return home.into_std_path_buf();
}
current_exe_directory()
}
fn main() -> Result<()> {
let entire_start_time = std::time::Instant::now();
let mut start_time = std::time::Instant::now();
miette::set_panic_hook();
let miette_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |x| {
crossterm::terminal::disable_raw_mode().expect("unable to disable raw mode");
miette_hook(x);
}));
let mut engine_state = EngineState::new();
// Parse commandline args very early and load experimental options to allow loading different
// commands based on experimental options.
let (args_to_nushell, script_name, args_to_script) = gather_commandline_args();
let parsed_nu_cli_args = parse_commandline_args(&args_to_nushell.join(" "), &mut engine_state)
.unwrap_or_else(|err| {
report_shell_error(None, &engine_state, &err);
std::process::exit(1)
});
experimental_options::load(&engine_state, &parsed_nu_cli_args, !script_name.is_empty());
let mut engine_state = command_context::add_command_context(engine_state);
// Provide `version` the features of this nu binary
let cargo_features = env!("NU_FEATURES").split(",").map(Cow::Borrowed).collect();
nu_cmd_lang::VERSION_NU_FEATURES
.set(cargo_features)
.expect("unable to set VERSION_NU_FEATURES");
// Get the current working directory from the environment.
let init_cwd = current_dir_from_environment();
// Custom additions
let delta = {
let mut working_set = nu_protocol::engine::StateWorkingSet::new(&engine_state);
working_set.add_decl(Box::new(nu_cli::NuHighlight));
working_set.add_decl(Box::new(nu_cli::Print));
working_set.render()
};
if let Err(err) = engine_state.merge_delta(delta) {
report_shell_error(None, &engine_state, &err);
}
#[cfg(feature = "mcp")]
let handle_ctrlc = !parsed_nu_cli_args.mcp;
#[cfg(not(feature = "mcp"))]
let handle_ctrlc = true;
if handle_ctrlc {
ctrlc_protection(&mut engine_state);
}
#[cfg(all(feature = "rustls-tls", feature = "network"))]
nu_command::tls::CRYPTO_PROVIDER.default();
// Begin: Default NU_LIB_DIRS, NU_PLUGIN_DIRS
// Set default NU_LIB_DIRS and NU_PLUGIN_DIRS here before the env.nu is processed. If
// the env.nu file exists, these values will be overwritten, if it does not exist, or
// there is an error reading it, these values will be used.
let nushell_config_path: PathBuf = nu_path::nu_config_dir().map(Into::into).unwrap_or_default();
if let Ok(xdg_config_home) = std::env::var("XDG_CONFIG_HOME")
&& !xdg_config_home.is_empty()
{
if nushell_config_path
!= canonicalize_with(&xdg_config_home, &init_cwd)
.unwrap_or(PathBuf::from(&xdg_config_home))
.join("nushell")
{
report_shell_error(
None,
&engine_state,
&ShellError::InvalidXdgConfig {
xdg: xdg_config_home,
default: nushell_config_path.display().to_string(),
},
);
} else if let Some(old_config) = dirs::config_dir()
.and_then(|p| p.canonicalize().ok())
.map(|p| p.join("nushell"))
{
let xdg_config_empty = nushell_config_path
.read_dir()
.map_or(true, |mut dir| dir.next().is_none());
let old_config_empty = old_config
.read_dir()
.map_or(true, |mut dir| dir.next().is_none());
if !old_config_empty && xdg_config_empty {
eprintln!(
"WARNING: XDG_CONFIG_HOME has been set but {} is empty.\n",
nushell_config_path.display(),
);
eprintln!(
"Nushell will not move your configuration files from {}",
old_config.display()
);
}
}
}
let default_nushell_completions_path = if let Some(mut path) = nu_path::data_dir() {
path.push("nushell");
path.push("completions");
path.into()
} else {
std::path::PathBuf::new()
};
let mut default_nu_lib_dirs_path = nushell_config_path.clone();
default_nu_lib_dirs_path.push("scripts");
// env.NU_LIB_DIRS to be replaced by constant (below) - Eventual deprecation
// but an empty list for now to allow older code to work
engine_state.add_env_var("NU_LIB_DIRS".to_string(), Value::test_list(vec![]));
let mut working_set = nu_protocol::engine::StateWorkingSet::new(&engine_state);
let var_id = working_set.add_variable(
b"$NU_LIB_DIRS".into(),
Span::unknown(),
Type::List(Box::new(Type::String)),
false,
);
working_set.set_variable_const_val(
var_id,
Value::test_list(vec![
Value::test_string(default_nu_lib_dirs_path.to_string_lossy()),
Value::test_string(default_nushell_completions_path.to_string_lossy()),
]),
);
engine_state.merge_delta(working_set.render())?;
let mut default_nu_plugin_dirs_path = nushell_config_path;
default_nu_plugin_dirs_path.push("plugins");
engine_state.add_env_var("NU_PLUGIN_DIRS".to_string(), Value::test_list(vec![]));
let mut working_set = nu_protocol::engine::StateWorkingSet::new(&engine_state);
let var_id = working_set.add_variable(
b"$NU_PLUGIN_DIRS".into(),
Span::unknown(),
Type::List(Box::new(Type::String)),
false,
);
working_set.set_variable_const_val(
var_id,
Value::test_list(vec![
Value::test_string(default_nu_plugin_dirs_path.to_string_lossy()),
Value::test_string(current_exe_directory().to_string_lossy()),
]),
);
engine_state.merge_delta(working_set.render())?;
// End: Default NU_LIB_DIRS, NU_PLUGIN_DIRS
// This is the real secret sauce to having an in-memory sqlite db. You must
// start a connection to the memory database in main so it will exist for the
// lifetime of the program. If it's created with how MEMORY_DB is defined
// you'll be able to access this open connection from anywhere in the program
// by using the identical connection string.
#[cfg(feature = "sqlite")]
let db = nu_command::open_connection_in_memory_custom()?;
#[cfg(feature = "sqlite")]
db.last_insert_rowid();
// keep this condition in sync with the branches at the end
engine_state.is_interactive = parsed_nu_cli_args.interactive_shell.is_some()
|| (parsed_nu_cli_args.testbin.is_none()
&& parsed_nu_cli_args.commands.is_none()
&& script_name.is_empty()
&& !parsed_nu_cli_args.lsp);
engine_state.is_login = parsed_nu_cli_args.login_shell.is_some();
engine_state.history_enabled = parsed_nu_cli_args.no_history.is_none();
engine_state.is_lsp = parsed_nu_cli_args.lsp;
let use_color = engine_state
.get_config()
.use_ansi_coloring
.get(&engine_state);
// Set up logger
if let Some(level) = parsed_nu_cli_args
.log_level
.as_ref()
.map(|level| level.item.clone())
{
let level = if Level::from_str(&level).is_ok() {
level
} else {
eprintln!(
"ERROR: log library did not recognize log level '{level}', using default 'info'"
);
"info".to_string()
};
let target = parsed_nu_cli_args
.log_target
.as_ref()
.map(|target| target.item.clone())
.unwrap_or_else(|| "stderr".to_string());
let make_filters = |filters: &Option<Vec<Spanned<String>>>| {
filters.as_ref().map(|filters| {
filters
.iter()
.map(|filter| filter.item.clone())
.collect::<Vec<String>>()
})
};
let filters = logger::Filters {
include: make_filters(&parsed_nu_cli_args.log_include),
exclude: make_filters(&parsed_nu_cli_args.log_exclude),
};
logger(|builder| configure(&level, &target, filters, builder))?;
// info!("start logging {}:{}:{}", file!(), line!(), column!());
perf!("start logging", start_time, use_color);
}
start_time = std::time::Instant::now();
set_config_path(
&mut engine_state,
init_cwd.as_ref(),
"config.nu",
"config-path",
parsed_nu_cli_args.config_file.as_ref(),
);
set_config_path(
&mut engine_state,
init_cwd.as_ref(),
"env.nu",
"env-path",
parsed_nu_cli_args.env_file.as_ref(),
);
perf!("set_config_path", start_time, use_color);
#[cfg(unix)]
{
start_time = std::time::Instant::now();
terminal::acquire(engine_state.is_interactive);
perf!("acquire_terminal", start_time, use_color);
}
start_time = std::time::Instant::now();
engine_state.add_env_var(
"config".into(),
Config::default().into_value(Span::unknown()),
);
perf!("$env.config setup", start_time, use_color);
engine_state.add_env_var(
"ENV_CONVERSIONS".to_string(),
Value::test_record(record! {}),
);
start_time = std::time::Instant::now();
if let Some(include_path) = &parsed_nu_cli_args.include_path {
let span = include_path.span;
let vals: Vec<_> = include_path
.item
.split('\x1e') // \x1e is the record separator character (a character that is unlikely to appear in a path)
.map(|x| Value::string(x.trim().to_string(), span))
.collect();
let mut working_set = nu_protocol::engine::StateWorkingSet::new(&engine_state);
let var_id = working_set.add_variable(
b"$NU_LIB_DIRS".into(),
span,
Type::List(Box::new(Type::String)),
false,
);
working_set.set_variable_const_val(var_id, Value::list(vals, span));
engine_state.merge_delta(working_set.render())?;
}
perf!("NU_LIB_DIRS setup", start_time, use_color);
start_time = std::time::Instant::now();
// First, set up env vars as strings only
gather_parent_env_vars(&mut engine_state, init_cwd.as_ref());
perf!("gather env vars", start_time, use_color);
let mut stack = Stack::new();
start_time = std::time::Instant::now();
let config = engine_state.get_config();
let use_color = config.use_ansi_coloring.get(&engine_state);
// Translate environment variables from Strings to Values
if let Err(e) = convert_env_values(&mut engine_state, &mut stack) {
report_shell_error(None, &engine_state, &e);
}
perf!("Convert path to list", start_time, use_color);
engine_state.add_env_var(
"NU_VERSION".to_string(),
Value::string(env!("CARGO_PKG_VERSION"), Span::unknown()),
);
if parsed_nu_cli_args.no_std_lib.is_none() {
load_standard_library(&mut engine_state)?;
}
// IDE commands
if let Some(ide_goto_def) = parsed_nu_cli_args.ide_goto_def {
ide::goto_def(&mut engine_state, &script_name, &ide_goto_def);
return Ok(());
} else if let Some(ide_hover) = parsed_nu_cli_args.ide_hover {
ide::hover(&mut engine_state, &script_name, &ide_hover);
return Ok(());
} else if let Some(ide_complete) = parsed_nu_cli_args.ide_complete {
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()));
ide::complete(Arc::new(engine_state), &script_name, &ide_complete);
return Ok(());
} else if let Some(max_errors) = parsed_nu_cli_args.ide_check {
ide::check(&mut engine_state, &script_name, &max_errors);
return Ok(());
} else if parsed_nu_cli_args.ide_ast.is_some() {
ide::ast(&mut engine_state, &script_name);
return Ok(());
}
start_time = std::time::Instant::now();
if let Some(testbin) = &parsed_nu_cli_args.testbin {
let dispatcher = test_bins::new_testbin_dispatcher();
let test_bin = testbin.item.as_str();
match dispatcher.get(test_bin) {
Some(test_bin) => test_bin.run(),
None => {
if ["-h", "--help"].contains(&test_bin) {
test_bins::show_help(&dispatcher);
} else {
eprintln!("ERROR: Unknown testbin '{test_bin}'");
std::process::exit(1);
}
}
}
std::process::exit(0)
} else {
// If we're not running a testbin, set the current working directory to
// the location of the Nushell executable. This prevents the OS from
// locking the directory where the user launched Nushell.
std::env::set_current_dir(current_exe_directory())
.expect("set_current_dir() should succeed");
}
perf!("run test_bins", start_time, use_color);
start_time = std::time::Instant::now();
let input = if let Some(redirect_stdin) = &parsed_nu_cli_args.redirect_stdin {
trace!("redirecting stdin");
PipelineData::byte_stream(ByteStream::stdin(redirect_stdin.span)?, None)
} else {
trace!("not redirecting stdin");
PipelineData::empty()
};
perf!("redirect stdin", start_time, use_color);
start_time = std::time::Instant::now();
// Set up the $nu constant before evaluating config files (need to have $nu available in them)
engine_state.generate_nu_constant();
perf!("create_nu_constant", start_time, use_color);
#[cfg(feature = "plugin")]
if let Some(plugins) = &parsed_nu_cli_args.plugins {
use nu_plugin_engine::{GetPlugin, PluginDeclaration};
use nu_protocol::{ErrSpan, PluginIdentity, RegisteredPlugin, engine::StateWorkingSet};
// Load any plugins specified with --plugins
start_time = std::time::Instant::now();
let mut working_set = StateWorkingSet::new(&engine_state);
for plugin_filename in plugins {
// Make sure the plugin filenames are canonicalized
let filename = canonicalize_with(&plugin_filename.item, &init_cwd)
.map_err(|err| {
nu_protocol::shell_error::io::IoError::new(
err,
plugin_filename.span,
PathBuf::from(&plugin_filename.item),
)
})
.map_err(ShellError::from)?;
let identity = PluginIdentity::new(&filename, None)
.err_span(plugin_filename.span)
.map_err(ShellError::from)?;
// Create the plugin and add it to the working set
let plugin = nu_plugin_engine::add_plugin_to_working_set(&mut working_set, &identity)?;
// Spawn the plugin to get the metadata and signatures
let interface = plugin.clone().get_plugin(None)?;
// Set its metadata
plugin.set_metadata(Some(interface.get_metadata()?));
// Add the commands from the signature to the working set
for signature in interface.get_signature()? {
let decl = PluginDeclaration::new(plugin.clone(), signature);
working_set.add_decl(Box::new(decl));
}
}
engine_state.merge_delta(working_set.render())?;
perf!("load plugins specified in --plugins", start_time, use_color)
}
start_time = std::time::Instant::now();
#[cfg(feature = "mcp")]
if parsed_nu_cli_args.mcp {
perf!("mcp starting", start_time, use_color);
if parsed_nu_cli_args.no_config_file.is_none() {
let mut stack = nu_protocol::engine::Stack::new();
config_files::setup_config(
&mut engine_state,
&mut stack,
#[cfg(feature = "plugin")]
parsed_nu_cli_args.plugin_file,
parsed_nu_cli_args.config_file,
parsed_nu_cli_args.env_file,
parsed_nu_cli_args.login_shell.is_some(),
);
}
nu_mcp::initialize_mcp_server(engine_state)?;
return Ok(());
}
if parsed_nu_cli_args.lsp {
perf!("lsp starting", start_time, use_color);
if parsed_nu_cli_args.no_config_file.is_none() {
let mut stack = nu_protocol::engine::Stack::new();
config_files::setup_config(
&mut engine_state,
&mut stack,
#[cfg(feature = "plugin")]
parsed_nu_cli_args.plugin_file,
parsed_nu_cli_args.config_file,
parsed_nu_cli_args.env_file,
false,
);
}
LanguageServer::initialize_stdio_connection(engine_state)?.serve_requests()?
} else if let Some(commands) = parsed_nu_cli_args.commands.clone() {
run_commands(
&mut engine_state,
stack,
parsed_nu_cli_args,
use_color,
&commands,
input,
entire_start_time,
);
cleanup_exit(0, &engine_state, 0);
} else if !script_name.is_empty() {
run_file(
&mut engine_state,
stack,
parsed_nu_cli_args,
use_color,
script_name,
args_to_script,
input,
);
cleanup_exit(0, &engine_state, 0);
} else {
// Environment variables that apply only when in REPL
engine_state.add_env_var("PROMPT_INDICATOR".to_string(), Value::test_string("> "));
engine_state.add_env_var(
"PROMPT_INDICATOR_VI_NORMAL".to_string(),
Value::test_string("> "),
);
engine_state.add_env_var(
"PROMPT_INDICATOR_VI_INSERT".to_string(),
Value::test_string(": "),
);
engine_state.add_env_var(
"PROMPT_MULTILINE_INDICATOR".to_string(),
Value::test_string("::: "),
);
engine_state.add_env_var(
"TRANSIENT_PROMPT_MULTILINE_INDICATOR".to_string(),
Value::test_string(""),
);
engine_state.add_env_var(
"TRANSIENT_PROMPT_COMMAND_RIGHT".to_string(),
Value::test_string(""),
);
let mut shlvl = engine_state
.get_env_var("SHLVL")
.map(|x| x.as_str().unwrap_or("0").parse::<i64>().unwrap_or(0))
.unwrap_or(0);
shlvl += 1;
engine_state.add_env_var("SHLVL".to_string(), Value::int(shlvl, Span::unknown()));
run_repl(
&mut engine_state,
stack,
parsed_nu_cli_args,
entire_start_time,
)?;
cleanup_exit(0, &engine_state, 0);
}
Ok(())
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/src/experimental_options.rs | src/experimental_options.rs | use std::borrow::Borrow;
use nu_protocol::{
engine::{EngineState, StateWorkingSet},
report_error::report_experimental_option_warning,
};
use crate::command::NushellCliArgs;
// 1. Parse experimental options from env
// 2. See if we should have any and disable all of them if not
// 3. Parse CLI arguments, if explicitly mentioned, let's enable them
pub fn load(engine_state: &EngineState, cli_args: &NushellCliArgs, has_script: bool) {
let working_set = StateWorkingSet::new(engine_state);
if !should_disable_experimental_options(has_script, cli_args) {
let env_content = std::env::var(nu_experimental::ENV).unwrap_or_default();
let env_offset = format!("{}=", nu_experimental::ENV).len();
for (env_warning, span) in nu_experimental::parse_env() {
let span_offset = (span.start + env_offset)..(span.end + env_offset);
let mut diagnostic = miette::diagnostic!(
severity = miette::Severity::Warning,
code = env_warning.code(),
labels = vec![miette::LabeledSpan::new_with_span(None, span_offset)],
"{}",
env_warning,
);
if let Some(help) = env_warning.help() {
diagnostic = diagnostic.with_help(help);
}
let error = miette::Error::from(diagnostic).with_source_code(format!(
"{}={}",
nu_experimental::ENV,
env_content
));
report_experimental_option_warning(None, &working_set, error.borrow());
}
}
for (cli_arg_warning, ctx) in
nu_experimental::parse_iter(cli_args.experimental_options.iter().flatten().map(|entry| {
entry
.item
.split_once("=")
.map(|(key, val)| (key.into(), Some(val.into()), entry))
.unwrap_or((entry.item.clone().into(), None, entry))
}))
{
let diagnostic = miette::diagnostic!(
severity = miette::Severity::Warning,
code = cli_arg_warning.code(),
labels = vec![miette::LabeledSpan::new_with_span(None, ctx.span)],
"{}",
cli_arg_warning,
);
match cli_arg_warning.help() {
Some(help) => {
report_experimental_option_warning(None, &working_set, &diagnostic.with_help(help))
}
None => report_experimental_option_warning(None, &working_set, &diagnostic),
}
}
}
fn should_disable_experimental_options(has_script: bool, cli_args: &NushellCliArgs) -> bool {
has_script
|| cli_args.commands.is_some()
|| cli_args.execute.is_some()
|| cli_args.no_config_file.is_some()
|| cli_args.login_shell.is_some()
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/src/test_bins.rs | src/test_bins.rs | use nu_cmd_base::hook::{eval_env_change_hook, eval_hooks};
use nu_engine::eval_block;
use nu_parser::parse;
use nu_protocol::{
PipelineData, ShellError, Value,
debugger::WithoutDebug,
engine::{EngineState, Stack, StateWorkingSet},
report_parse_error, report_shell_error,
};
use nu_std::load_standard_library;
use std::{
collections::HashMap,
io::{self, BufRead, Read, Write},
sync::Arc,
};
pub trait TestBin {
fn help(&self) -> &'static str;
fn run(&self);
}
pub struct EchoEnv;
pub struct EchoEnvStderr;
pub struct EchoEnvStderrFail;
pub struct EchoEnvMixed;
pub struct Cococo;
pub struct Meow;
pub struct Meowb;
pub struct Relay;
pub struct Iecho;
pub struct Fail;
pub struct Nonu;
pub struct Chop;
pub struct Repeater;
pub struct RepeatBytes;
pub struct NuRepl;
pub struct InputBytesLength;
impl TestBin for EchoEnv {
fn help(&self) -> &'static str {
"Echo's value of env keys from args(e.g: nu --testbin echo_env FOO BAR)"
}
fn run(&self) {
echo_env(true)
}
}
impl TestBin for EchoEnvStderr {
fn help(&self) -> &'static str {
"Echo's value of env keys from args to stderr(e.g: nu --testbin echo_env_stderr FOO BAR)"
}
fn run(&self) {
echo_env(false)
}
}
impl TestBin for EchoEnvStderrFail {
fn help(&self) -> &'static str {
"Echo's value of env keys from args to stderr, and exit with failure(e.g: nu --testbin echo_env_stderr_fail FOO BAR)"
}
fn run(&self) {
echo_env(false);
fail(1);
}
}
impl TestBin for EchoEnvMixed {
fn help(&self) -> &'static str {
"Mix echo of env keys from input(e.g: nu --testbin echo_env_mixed out-err FOO BAR; nu --testbin echo_env_mixed err-out FOO BAR)"
}
fn run(&self) {
let args = args();
let args = &args[1..];
if args.len() != 3 {
panic!(
r#"Usage examples:
* nu --testbin echo_env_mixed out-err FOO BAR
* nu --testbin echo_env_mixed err-out FOO BAR"#
)
}
match args[0].as_str() {
"out-err" => {
let (out_arg, err_arg) = (&args[1], &args[2]);
echo_one_env(out_arg, true);
echo_one_env(err_arg, false);
}
"err-out" => {
let (err_arg, out_arg) = (&args[1], &args[2]);
echo_one_env(err_arg, false);
echo_one_env(out_arg, true);
}
_ => panic!("The mixed type must be `out_err`, `err_out`"),
}
}
}
impl TestBin for Cococo {
fn help(&self) -> &'static str {
"Cross platform echo using println!()(e.g: nu --testbin cococo a b c)"
}
fn run(&self) {
let args: Vec<String> = args();
if args.len() > 1 {
// Write back out all the arguments passed
// if given at least 1 instead of chickens
// speaking co co co.
println!("{}", &args[1..].join(" "));
} else {
println!("cococo");
}
}
}
impl TestBin for Meow {
fn help(&self) -> &'static str {
"Cross platform cat (open a file, print the contents) using read_to_string and println!()(e.g: nu --testbin meow file.txt)"
}
fn run(&self) {
let args: Vec<String> = args();
for arg in args.iter().skip(1) {
let contents = std::fs::read_to_string(arg).expect("Expected a filepath");
println!("{contents}");
}
}
}
impl TestBin for Meowb {
fn help(&self) -> &'static str {
"Cross platform cat (open a file, print the contents) using read() and write_all() / binary(e.g: nu --testbin meowb sample.db)"
}
fn run(&self) {
let args: Vec<String> = args();
let stdout = io::stdout();
let mut handle = stdout.lock();
for arg in args.iter().skip(1) {
let buf = std::fs::read(arg).expect("Expected a filepath");
handle.write_all(&buf).expect("failed to write to stdout");
}
}
}
impl TestBin for Relay {
fn help(&self) -> &'static str {
"Relays anything received on stdin to stdout(e.g: 0x[beef] | nu --testbin relay)"
}
fn run(&self) {
io::copy(&mut io::stdin().lock(), &mut io::stdout().lock())
.expect("failed to copy stdin to stdout");
}
}
impl TestBin for Iecho {
fn help(&self) -> &'static str {
"Another type of echo that outputs a parameter per line, looping infinitely(e.g: nu --testbin iecho 3)"
}
fn run(&self) {
// println! panics if stdout gets closed, whereas writeln gives us an error
let mut stdout = io::stdout();
let _ = args()
.iter()
.skip(1)
.cycle()
.try_for_each(|v| writeln!(stdout, "{v}"));
}
}
impl TestBin for Fail {
fn help(&self) -> &'static str {
"Exits with failure code <c>, if not given, fail with code 1(e.g: nu --testbin fail 10)"
}
fn run(&self) {
let args: Vec<String> = args();
let exit_code: i32 = if args.len() > 1 {
args[1].parse().expect("given exit_code should be a number")
} else {
1
};
fail(exit_code);
}
}
impl TestBin for Nonu {
fn help(&self) -> &'static str {
"Cross platform echo but concats arguments without space and NO newline(e.g: nu --testbin nonu a b c)"
}
fn run(&self) {
args().iter().skip(1).for_each(|arg| print!("{arg}"));
}
}
impl TestBin for Chop {
fn help(&self) -> &'static str {
"With no parameters, will chop a character off the end of each line"
}
fn run(&self) {
if did_chop_arguments() {
// we are done and don't care about standard input.
std::process::exit(0);
}
// if no arguments given, chop from standard input and exit.
let stdin = io::stdin();
let mut stdout = io::stdout();
for given in stdin.lock().lines().map_while(Result::ok) {
let chopped = if given.is_empty() {
&given
} else {
let to = given.len() - 1;
&given[..to]
};
if let Err(_e) = writeln!(stdout, "{chopped}") {
break;
}
}
std::process::exit(0);
}
}
impl TestBin for Repeater {
fn help(&self) -> &'static str {
"Repeat a string or char N times(e.g: nu --testbin repeater a 5)"
}
fn run(&self) {
let mut stdout = io::stdout();
let args = args();
let mut args = args.iter().skip(1);
let letter = args.next().expect("needs a character to iterate");
let count = args.next().expect("need the number of times to iterate");
let count: u64 = count.parse().expect("can't convert count to number");
for _ in 0..count {
let _ = write!(stdout, "{letter}");
}
let _ = stdout.flush();
}
}
impl TestBin for RepeatBytes {
fn help(&self) -> &'static str {
"A version of repeater that can output binary data, even null bytes(e.g: nu --testbin repeat_bytes 003d9fbf 10)"
}
fn run(&self) {
let mut stdout = io::stdout();
let args = args();
let mut args = args.iter().skip(1);
while let (Some(binary), Some(count)) = (args.next(), args.next()) {
let bytes: Vec<u8> = (0..binary.len())
.step_by(2)
.map(|i| {
u8::from_str_radix(&binary[i..i + 2], 16)
.expect("binary string is valid hexadecimal")
})
.collect();
let count: u64 = count.parse().expect("repeat count must be a number");
for _ in 0..count {
stdout
.write_all(&bytes)
.expect("writing to stdout must not fail");
}
}
let _ = stdout.flush();
}
}
impl TestBin for NuRepl {
fn help(&self) -> &'static str {
"Run a REPL with the given source lines, it must be called with `--testbin=nu_repl`, `--testbin nu_repl` will not work due to argument count logic"
}
fn run(&self) {
nu_repl();
}
}
impl TestBin for InputBytesLength {
fn help(&self) -> &'static str {
"Prints the number of bytes received on stdin(e.g: 0x[deadbeef] | nu --testbin input_bytes_length)"
}
fn run(&self) {
let stdin = io::stdin();
let count = stdin.lock().bytes().count();
println!("{count}");
}
}
/// Echo's value of env keys from args
/// Example: nu --testbin env_echo FOO BAR
/// If it it's not present echo's nothing
pub fn echo_env(to_stdout: bool) {
let args = args();
for arg in args {
echo_one_env(&arg, to_stdout)
}
}
fn echo_one_env(arg: &str, to_stdout: bool) {
if let Ok(v) = std::env::var(arg) {
if to_stdout {
println!("{v}");
} else {
eprintln!("{v}");
}
}
}
pub fn fail(exit_code: i32) {
std::process::exit(exit_code);
}
fn outcome_err(stack: Option<&Stack>, engine_state: &EngineState, error: &ShellError) -> ! {
report_shell_error(stack, engine_state, error);
std::process::exit(1);
}
fn outcome_ok(msg: String) -> ! {
println!("{msg}");
std::process::exit(0);
}
/// Generate a minimal engine state with just `nu-cmd-lang`, `nu-command`, and `nu-cli` commands.
fn get_engine_state() -> EngineState {
let engine_state = nu_cmd_lang::create_default_context();
let engine_state = nu_command::add_shell_command_context(engine_state);
nu_cli::add_cli_context(engine_state)
}
pub fn nu_repl() {
//cwd: &str, source_lines: &[&str]) {
let cwd = std::env::current_dir().expect("Could not get current working directory.");
let source_lines = args();
let mut engine_state = get_engine_state();
let mut top_stack = Arc::new(Stack::new());
engine_state.add_env_var("PWD".into(), Value::test_string(cwd.to_string_lossy()));
engine_state.add_env_var("PATH".into(), Value::test_string(""));
let mut last_output = String::new();
load_standard_library(&mut engine_state).expect("Could not load the standard library.");
for (i, line) in source_lines.iter().enumerate() {
let mut stack = Stack::with_parent(top_stack.clone());
// Before doing anything, merge the environment from the previous REPL iteration into the
// permanent state.
if let Err(err) = engine_state.merge_env(&mut stack) {
outcome_err(None, &engine_state, &err);
}
// Check for pre_prompt hook
let hook = engine_state.get_config().hooks.pre_prompt.clone();
if let Err(err) = eval_hooks(&mut engine_state, &mut stack, vec![], &hook, "pre_prompt") {
outcome_err(None, &engine_state, &err);
}
// Check for env change hook
if let Err(err) = eval_env_change_hook(
&engine_state.get_config().hooks.env_change.clone(),
&mut engine_state,
&mut stack,
) {
outcome_err(None, &engine_state, &err);
}
// Check for pre_execution hook
engine_state
.repl_state
.lock()
.expect("repl state mutex")
.buffer = line.to_string();
let hook = engine_state.get_config().hooks.pre_execution.clone();
if let Err(err) = eval_hooks(
&mut engine_state,
&mut stack,
vec![],
&hook,
"pre_execution",
) {
outcome_err(None, &engine_state, &err);
}
// Eval the REPL line
let (block, delta) = {
let mut working_set = StateWorkingSet::new(&engine_state);
let block = parse(
&mut working_set,
Some(&format!("line{i}")),
line.as_bytes(),
false,
);
if let Some(err) = working_set.parse_errors.first() {
report_parse_error(None, &working_set, err);
std::process::exit(1);
}
(block, working_set.render())
};
if let Err(err) = engine_state.merge_delta(delta) {
outcome_err(None, &engine_state, &err);
}
let input = PipelineData::empty();
let config = engine_state.get_config();
{
let stack = &mut stack.start_collect_value();
match eval_block::<WithoutDebug>(&engine_state, stack, &block, input).map(|p| p.body) {
Ok(pipeline_data) => match pipeline_data.collect_string("", config) {
Ok(s) => last_output = s,
Err(err) => outcome_err(Some(stack), &engine_state, &err),
},
Err(err) => outcome_err(Some(stack), &engine_state, &err),
}
}
if let Some(cwd) = stack.get_env_var(&engine_state, "PWD") {
let path = cwd
.coerce_str()
.unwrap_or_else(|err| outcome_err(Some(&stack), &engine_state, &err));
let _ = std::env::set_current_dir(path.as_ref());
engine_state.add_env_var("PWD".into(), cwd.clone());
}
top_stack = Arc::new(Stack::with_changes_from_child(top_stack, stack));
}
outcome_ok(last_output)
}
fn did_chop_arguments() -> bool {
let args: Vec<String> = args();
if args.len() > 1 {
let mut arguments = args.iter();
arguments.next();
for arg in arguments {
let chopped = if arg.is_empty() {
arg
} else {
let to = arg.len() - 1;
&arg[..to]
};
println!("{chopped}");
}
return true;
}
false
}
fn args() -> Vec<String> {
// skip (--testbin bin_name args)
std::env::args().skip(2).collect()
}
pub fn show_help(dispatcher: &std::collections::HashMap<String, Box<dyn TestBin>>) {
println!("Usage: nu --testbin <bin>\n<bin>:");
let mut names = dispatcher.keys().collect::<Vec<_>>();
names.sort();
for n in names {
let test_bin = dispatcher.get(n).expect("Test bin should exist");
println!("{n} -> {}", test_bin.help())
}
}
/// Create a new testbin dispatcher, which is useful to guide the testbin to run.
pub fn new_testbin_dispatcher() -> HashMap<String, Box<dyn TestBin>> {
let mut dispatcher: HashMap<String, Box<dyn TestBin>> = HashMap::new();
dispatcher.insert("echo_env".to_string(), Box::new(EchoEnv));
dispatcher.insert("echo_env_stderr".to_string(), Box::new(EchoEnvStderr));
dispatcher.insert(
"echo_env_stderr_fail".to_string(),
Box::new(EchoEnvStderrFail),
);
dispatcher.insert("echo_env_mixed".to_string(), Box::new(EchoEnvMixed));
dispatcher.insert("cococo".to_string(), Box::new(Cococo));
dispatcher.insert("meow".to_string(), Box::new(Meow));
dispatcher.insert("meowb".to_string(), Box::new(Meowb));
dispatcher.insert("relay".to_string(), Box::new(Relay));
dispatcher.insert("iecho".to_string(), Box::new(Iecho));
dispatcher.insert("fail".to_string(), Box::new(Fail));
dispatcher.insert("nonu".to_string(), Box::new(Nonu));
dispatcher.insert("chop".to_string(), Box::new(Chop));
dispatcher.insert("repeater".to_string(), Box::new(Repeater));
dispatcher.insert("repeat_bytes".to_string(), Box::new(RepeatBytes));
dispatcher.insert("nu_repl".to_string(), Box::new(NuRepl));
dispatcher.insert("input_bytes_length".to_string(), Box::new(InputBytesLength));
dispatcher
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/src/signals.rs | src/signals.rs | use nu_protocol::{Handlers, SignalAction, Signals, engine::EngineState};
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
pub(crate) fn ctrlc_protection(engine_state: &mut EngineState) {
let interrupt = Arc::new(AtomicBool::new(false));
engine_state.set_signals(Signals::new(interrupt.clone()));
let signal_handlers = Handlers::new();
// Register a handler to kill all background jobs on interrupt.
signal_handlers
.register_unguarded({
let jobs = engine_state.jobs.clone();
Box::new(move |action| {
if action == SignalAction::Interrupt
&& let Ok(mut jobs) = jobs.lock()
{
let _ = jobs.kill_all();
}
})
})
.expect("Failed to register interrupt signal handler");
engine_state.signal_handlers = Some(signal_handlers.clone());
ctrlc::set_handler(move || {
interrupt.store(true, Ordering::Relaxed);
signal_handlers.run(SignalAction::Interrupt);
})
.expect("Error setting Ctrl-C handler");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/main.rs | tests/main.rs | extern crate nu_test_support;
mod const_;
mod eval;
mod hooks;
mod integration;
mod modules;
mod overlays;
mod parsing;
mod path;
#[cfg(feature = "plugin")]
mod plugin_persistence;
#[cfg(feature = "plugin")]
mod plugins;
mod repl;
mod scope;
mod shell;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/scope/mod.rs | tests/scope/mod.rs | use nu_test_support::fs::Stub::FileWithContent;
use nu_test_support::nu;
use nu_test_support::playground::Playground;
use pretty_assertions::assert_eq;
// Note: These tests might slightly overlap with crates/nu-command/tests/commands/help.rs
#[test]
fn scope_shows_alias() {
let actual = nu!("alias xaz = echo alias1
scope aliases | find xaz | length
");
let length: i32 = actual.out.parse().unwrap();
assert_eq!(length, 1);
}
#[test]
fn scope_shows_command() {
let actual = nu!("def xaz [] { echo xaz }
scope commands | find xaz | length
");
let length: i32 = actual.out.parse().unwrap();
assert_eq!(length, 1);
}
#[test]
fn scope_doesnt_show_scoped_hidden_alias() {
let actual = nu!("alias xaz = echo alias1
do {
hide xaz
scope aliases | find xaz | length
}
");
let length: i32 = actual.out.parse().unwrap();
assert_eq!(length, 0);
}
#[test]
fn scope_doesnt_show_hidden_alias() {
let actual = nu!("alias xaz = echo alias1
hide xaz
scope aliases | find xaz | length
");
let length: i32 = actual.out.parse().unwrap();
assert_eq!(length, 0);
}
#[test]
fn scope_doesnt_show_scoped_hidden_command() {
let actual = nu!("def xaz [] { echo xaz }
do {
hide xaz
scope commands | find xaz | length
}
");
let length: i32 = actual.out.parse().unwrap();
assert_eq!(length, 0);
}
#[test]
fn scope_doesnt_show_hidden_command() {
let actual = nu!("def xaz [] { echo xaz }
hide xaz
scope commands | find xaz | length
");
let length: i32 = actual.out.parse().unwrap();
assert_eq!(length, 0);
}
// same problem as 'which' command
#[ignore = "See https://github.com/nushell/nushell/issues/4837"]
#[test]
fn correctly_report_of_shadowed_alias() {
let actual = nu!("alias xaz = echo alias1
def helper [] {
alias xaz = echo alias2
scope aliases
}
helper | where alias == xaz | get expansion.0");
assert_eq!(actual.out, "echo alias2");
}
#[test]
fn correct_scope_modules_fields() {
let module_setup = r#"
# nice spam
#
# and some extra description for spam
export module eggs {
export module bacon {
export def sausage [] { 'sausage' }
}
}
export def main [] { 'foo' };
export alias xaz = print
export extern git []
export const X = 4
export-env { $env.SPAM = 'spam' }
"#;
Playground::setup("correct_scope_modules_fields", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent("spam.nu", module_setup)]);
let inp = &[
"use spam.nu",
"scope modules | where name == spam | get 0.name",
];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "spam");
let inp = &[
"use spam.nu",
"scope modules | where name == spam | get 0.description",
];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "nice spam");
let inp = &[
"use spam.nu",
"scope modules | where name == spam | get 0.extra_description",
];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "and some extra description for spam");
let inp = &[
"use spam.nu",
"scope modules | where name == spam | get 0.has_env_block",
];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "true");
let inp = &[
"use spam.nu",
"scope modules | where name == spam | get 0.commands.0.name",
];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "spam");
let inp = &[
"use spam.nu",
"scope modules | where name == spam | get 0.aliases.0.name",
];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "xaz");
let inp = &[
"use spam.nu",
"scope modules | where name == spam | get 0.externs.0.name",
];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "git");
let inp = &[
"use spam.nu",
"scope modules | where name == spam | get 0.constants.0.name",
];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "X");
let inp = &[
"use spam.nu",
"scope modules | where name == spam | get 0.submodules.0.submodules.0.name",
];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "bacon");
let inp = &[
"use spam.nu",
"scope modules | where name == spam | get 0.submodules.0.submodules.0.commands.0.name",
];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "sausage");
})
}
#[test]
fn correct_scope_aliases_fields() {
let module_setup = r#"
# nice alias
export alias xaz = print
"#;
Playground::setup("correct_scope_aliases_fields", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent("spam.nu", module_setup)]);
let inp = &[
"use spam.nu",
"scope aliases | where name == 'spam xaz' | get 0.name",
];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "spam xaz");
let inp = &[
"use spam.nu",
"scope aliases | where name == 'spam xaz' | get 0.expansion",
];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "print");
let inp = &[
"use spam.nu",
"scope aliases | where name == 'spam xaz' | get 0.description",
];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "nice alias");
let inp = &[
"use spam.nu",
"scope aliases | where name == 'spam xaz' | get 0.decl_id | is-empty",
];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "false");
let inp = &[
"use spam.nu",
"scope aliases | where name == 'spam xaz' | get 0.aliased_decl_id | is-empty",
];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "false");
})
}
#[test]
fn scope_alias_aliased_decl_id_external() {
let inp = &[
"alias c = cargo",
"scope aliases | where name == c | get 0.aliased_decl_id | is-empty",
];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "true");
}
#[test]
fn correct_scope_externs_fields() {
let module_setup = r#"
# nice extern
export extern git []
"#;
Playground::setup("correct_scope_aliases_fields", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent("spam.nu", module_setup)]);
let inp = &[
"use spam.nu",
"scope externs | where name == 'spam git' | get 0.name",
];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "spam git");
let inp = &[
"use spam.nu",
"scope externs | where name == 'spam git' | get 0.description",
];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "nice extern");
let inp = &[
"use spam.nu",
"scope externs | where name == 'spam git' | get 0.description | str contains (char nl)",
];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "false");
let inp = &[
"use spam.nu",
"scope externs | where name == 'spam git' | get 0.decl_id | is-empty",
];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "false");
})
}
#[test]
fn scope_externs_sorted() {
let inp = &[
"extern a []",
"extern b []",
"extern c []",
"scope externs | get name | str join ''",
];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "abc");
}
#[test]
fn correct_scope_variables_fields() {
let inp = &[
"let x = 'x'",
"scope variables | where name == '$x' | get 0.type",
];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "string");
let inp = &[
"let x = 'x'",
"scope variables | where name == '$x' | get 0.value",
];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "x");
let inp = &[
"let x = 'x'",
"scope variables | where name == '$x' | get 0.is_const",
];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "false");
let inp = &[
"const x = 'x'",
"scope variables | where name == '$x' | get 0.is_const",
];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "true");
let inp = &[
"let x = 'x'",
"scope variables | where name == '$x' | get 0.var_id | is-empty",
];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "false");
}
#[test]
fn example_results_have_valid_span() {
let inp = &[
"scope commands",
"| where name == 'do'",
"| first",
"| get examples",
"| where result == 177",
"| get 0.result",
"| metadata",
"| view span $in.span.start $in.span.end",
];
let actual = nu!(&inp.join(" "));
assert_eq!(actual.out, "scope commands");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/integration/mod.rs | tests/integration/mod.rs | use nu_test_support::nu;
use pretty_assertions::assert_str_eq;
#[test]
fn multiword_commands_have_their_parent_commands() {
let out = nu!(r#"
scope commands
| where type == built-in and name like ' '
| where ($it.name | split row ' ' | first) not-in (
scope commands
| where type in [keyword built-in]
| get name
)
| get name
| to json --raw
"#);
assert_str_eq!(
"[]",
out.out,
"These multiword commands are missing their dummy parent commands: {}",
out.out
);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/repl/test_converters.rs | tests/repl/test_converters.rs | use crate::repl::tests::{TestResult, run_test};
#[test]
fn from_json_1() -> TestResult {
run_test(r#"('{"name": "Fred"}' | from json).name"#, "Fred")
}
#[test]
fn from_json_2() -> TestResult {
run_test(
r#"('{"name": "Fred"}
{"name": "Sally"}' | from json -o).name.1"#,
"Sally",
)
}
#[test]
fn to_json_raw_flag_1() -> TestResult {
run_test(
"[[a b]; [jim susie] [3 4]] | to json -r",
r#"[{"a":"jim","b":"susie"},{"a":3,"b":4}]"#,
)
}
#[test]
fn to_json_raw_flag_2() -> TestResult {
run_test(
"[[\"a b\" c]; [jim susie] [3 4]] | to json -r",
r#"[{"a b":"jim","c":"susie"},{"a b":3,"c":4}]"#,
)
}
#[test]
fn to_json_raw_flag_3() -> TestResult {
run_test(
"[[\"a b\" \"c d\"]; [\"jim smith\" \"susie roberts\"] [3 4]] | to json -r",
r#"[{"a b":"jim smith","c d":"susie roberts"},{"a b":3,"c d":4}]"#,
)
}
#[test]
fn to_json_escaped() -> TestResult {
run_test(
r#"{foo: {bar: '[{"a":"b","c": 2}]'}} | to json --raw"#,
r#"{"foo":{"bar":"[{\"a\":\"b\",\"c\": 2}]"}}"#,
)
}
#[test]
fn to_json_raw_backslash_in_quotes() -> TestResult {
run_test(
r#"{a: '\', b: 'some text'} | to json -r"#,
r#"{"a":"\\","b":"some text"}"#,
)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/repl/test_math.rs | tests/repl/test_math.rs | use crate::repl::tests::{TestResult, fail_test, run_test};
#[test]
fn add_simple() -> TestResult {
run_test("3 + 4", "7")
}
#[test]
fn add_simple2() -> TestResult {
run_test("3 + 4 + 9", "16")
}
#[test]
fn broken_math() -> TestResult {
fail_test("3 + ", "incomplete")
}
#[test]
fn modulo1() -> TestResult {
run_test("5 mod 2", "1")
}
#[test]
fn modulo2() -> TestResult {
run_test("5.25 mod 2", "1.25")
}
#[test]
fn bit_shr() -> TestResult {
run_test("16 bit-shr 1", "8")
}
#[test]
fn bit_shl() -> TestResult {
run_test("5 bit-shl 1", "10")
}
#[test]
fn bit_shr_overflow() -> TestResult {
fail_test("16 bit-shr 10000", "exceeds available bits")
}
#[test]
fn bit_shl_overflow() -> TestResult {
fail_test("5 bit-shl 10000000", "exceeds available bits")
}
#[test]
fn bit_shl_neg_operand() -> TestResult {
// This would overflow the `u32` in the right hand side to 2
fail_test(
"9 bit-shl -9_223_372_036_854_775_806",
"exceeds available bits",
)
}
#[test]
fn bit_shr_neg_operand() -> TestResult {
// This would overflow the `u32` in the right hand side
fail_test("9 bit-shr -2", "exceeds available bits")
}
#[test]
fn bit_shl_add() -> TestResult {
run_test("2 bit-shl 1 + 2", "16")
}
#[test]
fn sub_bit_shr() -> TestResult {
run_test("10 - 2 bit-shr 2", "2")
}
#[test]
fn and() -> TestResult {
run_test("true and false", "false")
}
#[test]
fn or() -> TestResult {
run_test("true or false", "true")
}
#[test]
fn xor_1() -> TestResult {
run_test("false xor true", "true")
}
#[test]
fn xor_2() -> TestResult {
run_test("true xor true", "false")
}
#[test]
fn bit_xor() -> TestResult {
run_test("4 bit-xor 4", "0")
}
#[test]
fn bit_xor_add() -> TestResult {
run_test("4 bit-xor 2 + 2", "0")
}
#[test]
fn bit_and() -> TestResult {
run_test("2 bit-and 4", "0")
}
#[test]
fn bit_or() -> TestResult {
run_test("2 bit-or 4", "6")
}
#[test]
fn bit_and_or() -> TestResult {
run_test("2 bit-or 4 bit-and 1 + 2", "2")
}
#[test]
fn pow() -> TestResult {
run_test("3 ** 3", "27").unwrap();
run_test("2 ** 1 ** 2", "2").unwrap();
run_test("2 ** 3 ** 2 ** 1 ** 5", "512").unwrap();
run_test("1.42 ** 2 ** 1.01 ** 9", "2.1135450418757156").unwrap();
run_test("2.571 ** 3.1 ** 2.18", "67804.81966071267").unwrap();
run_test("2.0 ** 3.0 ** 4.0", "2417851639229258349412352.0")
}
#[test]
fn contains() -> TestResult {
run_test("'testme' =~ 'test'", "true")
}
#[test]
fn not_contains() -> TestResult {
run_test("'testme' !~ 'test'", "false")
}
#[test]
fn not_precedence() -> TestResult {
run_test("not false and false", "false")
}
#[test]
fn not_precedence2() -> TestResult {
run_test("(not false) and false", "false")
}
#[test]
fn not_precedence3() -> TestResult {
run_test("not not true and true", "true")
}
#[test]
fn not_precedence4() -> TestResult {
run_test("not not true and not not true", "true")
}
#[test]
fn floating_add() -> TestResult {
run_test("10.1 + 0.8", "10.9")
}
#[test]
fn precedence_of_or_groups() -> TestResult {
run_test(r#"4 mod 3 == 0 or 5 mod 5 == 0"#, "true")
}
#[test]
fn test_filesize_op() -> TestResult {
run_test("-5kb + 4.5kb", "-500 B")
}
#[test]
fn test_duration_op() -> TestResult {
run_test("4min + 20sec", "4min 20sec").unwrap();
run_test("42sec * 2", "1min 24sec").unwrap();
run_test("(3min + 14sec) / 2", "1min 37sec").unwrap();
run_test("(4min + 20sec) mod 69sec", "53sec")
}
#[test]
fn lt() -> TestResult {
run_test("1 < 3", "true").unwrap();
run_test("3 < 3", "false").unwrap();
run_test("3 < 1", "false")
}
// Comparison operators return null if 1 side or both side is null.
// The motivation for this behaviour: JT asked the C# devs and they said this is
// the behaviour they would choose if they were starting from scratch.
#[test]
fn lt_null() -> TestResult {
run_test("3 < null | to nuon", "null").unwrap();
run_test("null < 3 | to nuon", "null").unwrap();
run_test("null < null | to nuon", "null")
}
#[test]
fn lte() -> TestResult {
run_test("1 <= 3", "true").unwrap();
run_test("3 <= 3", "true").unwrap();
run_test("3 <= 1", "false")
}
#[test]
fn lte_null() -> TestResult {
run_test("3 <= null | to nuon", "null").unwrap();
run_test("null <= 3 | to nuon", "null").unwrap();
run_test("null <= null | to nuon", "null")
}
#[test]
fn gt() -> TestResult {
run_test("1 > 3", "false").unwrap();
run_test("3 > 3", "false").unwrap();
run_test("3 > 1", "true")
}
#[test]
fn gt_null() -> TestResult {
run_test("3 > null | to nuon", "null").unwrap();
run_test("null > 3 | to nuon", "null").unwrap();
run_test("null > null | to nuon", "null")
}
#[test]
fn gte() -> TestResult {
run_test("1 >= 3", "false").unwrap();
run_test("3 >= 3", "true").unwrap();
run_test("3 >= 1", "true")
}
#[test]
fn gte_null() -> TestResult {
run_test("3 >= null | to nuon", "null").unwrap();
run_test("null >= 3 | to nuon", "null").unwrap();
run_test("null >= null | to nuon", "null")
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/repl/test_cell_path.rs | tests/repl/test_cell_path.rs | use crate::repl::tests::{TestResult, fail_test, run_test};
// Tests for null / null / Value::Nothing
#[test]
fn nothing_fails_string() -> TestResult {
fail_test("let nil = null; $nil.foo", "doesn't support cell paths")
}
#[test]
fn nothing_fails_int() -> TestResult {
fail_test("let nil = null; $nil.3", "doesn't support cell paths")
}
// Tests for records
#[test]
fn record_single_field_success() -> TestResult {
run_test("{foo: 'bar'}.foo == 'bar'", "true")
}
#[test]
fn record_single_field_optional_success() -> TestResult {
run_test("{foo: 'bar'}.foo? == 'bar'", "true")
}
#[test]
fn get_works_with_cell_path_success() -> TestResult {
run_test("{foo: 'bar'} | get foo?", "bar")
}
#[test]
fn get_works_with_cell_path_missing_data() -> TestResult {
run_test("{foo: 'bar'} | get foobar? | to nuon", "null")
}
#[test]
fn record_single_field_failure() -> TestResult {
fail_test("{foo: 'bar'}.foobar", "")
}
#[test]
fn record_int_failure() -> TestResult {
fail_test("{foo: 'bar'}.3", "")
}
#[test]
fn record_single_field_optional() -> TestResult {
run_test("{foo: 'bar'}.foobar? | to nuon", "null")
}
#[test]
fn record_single_field_optional_short_circuits() -> TestResult {
// Check that we return null as soon as the `.foobar?` access
// fails instead of erroring on the `.baz` access
run_test("{foo: 'bar'}.foobar?.baz | to nuon", "null")
}
#[test]
fn record_multiple_optional_fields() -> TestResult {
run_test("{foo: 'bar'}.foobar?.baz? | to nuon", "null")
}
#[test]
fn nested_record_field_success() -> TestResult {
run_test("{foo: {bar: 'baz'} }.foo.bar == 'baz'", "true")
}
#[test]
fn nested_record_field_failure() -> TestResult {
fail_test("{foo: {bar: 'baz'} }.foo.asdf", "")
}
#[test]
fn nested_record_field_optional() -> TestResult {
run_test("{foo: {bar: 'baz'} }.foo.asdf? | to nuon", "null")
}
#[test]
fn record_with_nested_list_success() -> TestResult {
run_test("{foo: [{bar: 'baz'}]}.foo.0.bar == 'baz'", "true")
}
#[test]
fn record_with_nested_list_int_failure() -> TestResult {
fail_test("{foo: [{bar: 'baz'}]}.foo.3.bar", "")
}
#[test]
fn record_with_nested_list_column_failure() -> TestResult {
fail_test("{foo: [{bar: 'baz'}]}.foo.0.asdf", "")
}
// Tests for lists
#[test]
fn list_single_field_success() -> TestResult {
run_test("[{foo: 'bar'}].foo.0 == 'bar'", "true")?;
// test field access both ways
run_test("[{foo: 'bar'}].0.foo == 'bar'", "true")
}
#[test]
fn list_single_field_failure() -> TestResult {
fail_test("[{foo: 'bar'}].asdf", "")
}
// Test the scenario where the requested column is not present in all rows
#[test]
fn jagged_list_access_fails() -> TestResult {
fail_test("[{foo: 'bar'}, {}].foo", "cannot find column")?;
fail_test("[{}, {foo: 'bar'}].foo", "cannot find column")
}
#[test]
fn jagged_list_optional_access_succeeds() -> TestResult {
run_test("[{foo: 'bar'}, {}].foo?.0", "bar")?;
run_test("[{foo: 'bar'}, {}].foo?.1 | to nuon", "null")?;
run_test("[{}, {foo: 'bar'}].foo?.0 | to nuon", "null")?;
run_test("[{}, {foo: 'bar'}].foo?.1", "bar")
}
// test that accessing a nonexistent row fails
#[test]
fn list_row_access_failure() -> TestResult {
fail_test("[{foo: 'bar'}, {foo: 'baz'}].2", "")
}
#[test]
fn list_row_optional_access_succeeds() -> TestResult {
run_test("[{foo: 'bar'}, {foo: 'baz'}].2? | to nuon", "null")?;
run_test("[{foo: 'bar'}, {foo: 'baz'}].3? | to nuon", "null")
}
// regression test for an old bug
#[test]
fn do_not_delve_too_deep_in_nested_lists() -> TestResult {
fail_test("[[{foo: bar}]].foo", "cannot find column")
}
#[test]
fn cell_path_literals() -> TestResult {
run_test("let cell_path = $.a.b; {a: {b: 3}} | get $cell_path", "3")
}
// Test whether cell path access short-circuits properly
#[test]
fn deeply_nested_cell_path_short_circuits() -> TestResult {
run_test(
"{foo: [{bar: 'baz'}]}.foo.3?.bar.asdfdafg.234.foobar | to nuon",
"null",
)
}
#[test]
fn cell_path_type() -> TestResult {
run_test("$.a.b | describe", "cell-path")
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/repl/test_commandline.rs | tests/repl/test_commandline.rs | use crate::repl::tests::{TestResult, fail_test, run_test};
#[test]
fn commandline_test_get_empty() -> TestResult {
run_test("commandline", "")
}
#[test]
fn commandline_test_append() -> TestResult {
run_test(
"commandline edit --replace '0👩❤️👩2'\n\
commandline set-cursor 2\n\
commandline edit --append 'ab'\n\
print (commandline)\n\
commandline get-cursor",
"0👩❤️👩2ab\n\
2",
)
}
#[test]
fn commandline_test_insert() -> TestResult {
run_test(
"commandline edit --replace '0👩❤️👩2'\n\
commandline set-cursor 2\n\
commandline edit --insert 'ab'\n\
print (commandline)\n\
commandline get-cursor",
"0👩❤️👩ab2\n\
4",
)
}
#[test]
fn commandline_test_replace() -> TestResult {
run_test(
"commandline edit --replace '0👩❤️👩2'\n\
commandline edit --replace 'ab'\n\
print (commandline)\n\
commandline get-cursor",
"ab\n\
2",
)
}
#[test]
fn commandline_test_cursor() -> TestResult {
run_test(
"commandline edit --replace '0👩❤️👩2'\n\
commandline set-cursor 1\n\
commandline edit --insert 'x'\n\
commandline",
"0x👩❤️👩2",
)?;
run_test(
"commandline edit --replace '0👩❤️👩2'\n\
commandline set-cursor 2\n\
commandline edit --insert 'x'\n\
commandline",
"0👩❤️👩x2",
)
}
#[test]
fn commandline_test_cursor_show_pos_begin() -> TestResult {
run_test(
"commandline edit --replace '0👩❤️👩'\n\
commandline set-cursor 0\n\
commandline get-cursor",
"0",
)
}
#[test]
fn commandline_test_cursor_show_pos_end() -> TestResult {
run_test(
"commandline edit --replace '0👩❤️👩'\n\
commandline set-cursor 2\n\
commandline get-cursor",
"2",
)
}
#[test]
fn commandline_test_cursor_show_pos_mid() -> TestResult {
run_test(
"commandline edit --replace '0👩❤️👩2'\n\
commandline set-cursor 1\n\
commandline get-cursor",
"1",
)?;
run_test(
"commandline edit --replace '0👩❤️👩2'\n\
commandline set-cursor 2\n\
commandline get-cursor",
"2",
)
}
#[test]
fn commandline_test_cursor_too_small() -> TestResult {
run_test(
"commandline edit --replace '123456'\n\
commandline set-cursor -1\n\
commandline edit --insert '0'\n\
commandline",
"0123456",
)
}
#[test]
fn commandline_test_cursor_too_large() -> TestResult {
run_test(
"commandline edit --replace '123456'\n\
commandline set-cursor 10\n\
commandline edit --insert '0'\n\
commandline",
"1234560",
)
}
#[test]
fn commandline_test_cursor_invalid() -> TestResult {
fail_test(
"commandline edit --replace '123456'\n\
commandline set-cursor 'abc'",
"expected int",
)
}
#[test]
fn commandline_test_cursor_end() -> TestResult {
run_test(
"commandline edit --insert '🤔🤔'; commandline set-cursor --end; commandline get-cursor",
"2", // 2 graphemes
)
}
#[test]
fn commandline_test_cursor_type() -> TestResult {
run_test("commandline get-cursor | describe", "int")
}
#[test]
fn commandline_test_accepted_command() -> TestResult {
run_test(
"commandline edit --accept \"print accepted\"\n | commandline",
"print accepted",
)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/repl/test_help.rs | tests/repl/test_help.rs | use crate::repl::tests::{TestResult, run_test};
use rstest::rstest;
#[rstest]
// avoid feeding strings containing parens to regex. Does not end well.
#[case(": arga help")]
#[case("argb help")]
#[case("optional, default: 20")]
#[case(": f1 switch")]
#[case(": f2 named no default")]
#[case(": f3 named default 3")]
#[case("default: 33")]
#[case("--help: Display the help message")]
fn can_get_help(#[case] exp_result: &str) -> TestResult {
run_test(
&format!(
r#"def t [a:string, # arga help
b:int=20, # argb help
--f1, # f1 switch help
--f2:string, # f2 named no default
--f3:int=33 # f3 named default 3
] {{ true }};
help t | ansi strip | find `{exp_result}` | get 0 | str replace --all --regex '^(.*({exp_result}).*)$' '$2'"#,
),
exp_result,
)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/repl/tests.rs | tests/repl/tests.rs | use assert_cmd::prelude::*;
use pretty_assertions::assert_eq;
use std::collections::HashMap;
use std::io::Write;
use std::process::Command;
use tempfile::NamedTempFile;
pub type TestResult = Result<(), Box<dyn std::error::Error>>;
pub fn run_test_with_env(input: &str, expected: &str, env: &HashMap<&str, &str>) -> TestResult {
let mut file = NamedTempFile::new()?;
let name = file.path();
let mut cmd = Command::cargo_bin("nu")?;
cmd.arg("--no-config-file");
cmd.arg(name).envs(env);
writeln!(file, "{input}")?;
run_cmd_and_assert(cmd, expected)
}
#[cfg(test)]
pub fn run_test(input: &str, expected: &str) -> TestResult {
let mut file = NamedTempFile::new()?;
let name = file.path();
let mut cmd = Command::cargo_bin("nu")?;
cmd.arg("--no-std-lib");
cmd.arg("--no-config-file");
cmd.arg(name);
cmd.env(
"PWD",
std::env::current_dir().expect("Can't get current dir"),
);
writeln!(file, "{input}")?;
run_cmd_and_assert(cmd, expected)
}
#[cfg(test)]
pub fn run_test_std(input: &str, expected: &str) -> TestResult {
let mut file = NamedTempFile::new()?;
let name = file.path();
let mut cmd = Command::cargo_bin("nu")?;
cmd.arg("--no-config-file");
cmd.arg(name);
cmd.env(
"PWD",
std::env::current_dir().expect("Can't get current dir"),
);
writeln!(file, "{input}")?;
run_cmd_and_assert(cmd, expected)
}
#[cfg(test)]
fn run_cmd_and_assert(mut cmd: Command, expected: &str) -> TestResult {
let output = cmd.output()?;
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
let stdout = String::from_utf8_lossy(&output.stdout).to_string();
println!("stdout: {stdout}");
println!("stderr: {stderr}");
assert!(output.status.success());
assert_eq!(stdout.trim(), expected);
Ok(())
}
#[cfg(test)]
pub fn run_test_contains(input: &str, expected: &str) -> TestResult {
let mut file = NamedTempFile::new()?;
let name = file.path();
let mut cmd = Command::cargo_bin("nu")?;
cmd.arg("--no-std-lib");
cmd.arg("--no-config-file");
cmd.arg(name);
writeln!(file, "{input}")?;
let output = cmd.output()?;
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
let stdout = String::from_utf8_lossy(&output.stdout).to_string();
println!("stdout: {stdout}");
println!("stderr: {stderr}");
println!("Expected output to contain: {expected}");
assert!(output.status.success());
assert!(stdout.contains(expected));
Ok(())
}
#[cfg(test)]
pub fn test_ide_contains(input: &str, ide_commands: &[&str], expected: &str) -> TestResult {
let mut file = NamedTempFile::new()?;
let name = file.path();
let mut cmd = Command::cargo_bin("nu")?;
cmd.arg("--no-std-lib");
cmd.arg("--no-config-file");
for ide_command in ide_commands {
cmd.arg(ide_command);
}
cmd.arg(name);
writeln!(file, "{input}")?;
let output = cmd.output()?;
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
let stdout = String::from_utf8_lossy(&output.stdout).to_string();
println!("stdout: {stdout}");
println!("stderr: {stderr}");
println!("Expected output to contain: {expected}");
assert!(output.status.success());
assert!(stdout.contains(expected));
Ok(())
}
#[cfg(test)]
pub fn fail_test(input: &str, expected: &str) -> TestResult {
let mut file = NamedTempFile::new()?;
let name = file.path();
let mut cmd = Command::cargo_bin("nu")?;
cmd.arg("--no-std-lib");
cmd.arg("--no-config-file");
cmd.arg(name);
cmd.env(
"PWD",
std::env::current_dir().expect("Can't get current dir"),
);
writeln!(file, "{input}")?;
let output = cmd.output()?;
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
let stdout = String::from_utf8_lossy(&output.stdout).to_string();
println!("stdout: {stdout}");
println!("stderr: {stderr}");
println!("Expected error to contain: {expected}");
assert!(!stderr.is_empty() && stderr.contains(expected));
Ok(())
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/repl/test_modules.rs | tests/repl/test_modules.rs | use crate::repl::tests::{TestResult, fail_test, run_test};
use rstest::rstest;
#[test]
fn module_def_imports_1() -> TestResult {
run_test(
r#"module foo { export def a [] { 1 }; def b [] { 2 } }; use foo; foo a"#,
"1",
)
}
#[test]
fn module_def_imports_2() -> TestResult {
run_test(
r#"module foo { export def a [] { 1 }; def b [] { 2 } }; use foo a; a"#,
"1",
)
}
#[test]
fn module_def_imports_3() -> TestResult {
run_test(
r#"module foo { export def a [] { 1 }; export def b [] { 2 } }; use foo *; b"#,
"2",
)
}
#[test]
fn module_def_imports_4() -> TestResult {
fail_test(
r#"module foo { export def a [] { 1 }; export def b [] { 2 } }; use foo c"#,
"not find import",
)
}
#[test]
fn module_def_imports_5() -> TestResult {
run_test(
r#"module foo { export def a [] { 1 }; def b [] { '2' }; export def c [] { '3' } }; use foo [a, c]; c"#,
"3",
)
}
#[test]
fn module_env_imports_1() -> TestResult {
run_test(
r#"module foo { export-env { $env.a = '1' } }; use foo; $env.a"#,
"1",
)
}
#[test]
fn module_env_imports_2() -> TestResult {
run_test(
r#"module foo { export-env { $env.a = '1'; $env.b = '2' } }; use foo; $env.b"#,
"2",
)
}
#[test]
fn module_env_imports_3() -> TestResult {
run_test(
r#"module foo { export-env { $env.a = '1' }; export-env { $env.b = '2' }; export-env {$env.c = '3'} }; use foo; $env.c"#,
"3",
)
}
#[test]
fn module_def_and_env_imports_1() -> TestResult {
run_test(
r#"module spam { export-env { $env.foo = "foo" }; export def foo [] { "bar" } }; use spam; $env.foo"#,
"foo",
)
}
#[test]
fn module_def_and_env_imports_2() -> TestResult {
run_test(
r#"module spam { export-env { $env.foo = "foo" }; export def foo [] { "bar" } }; use spam foo; foo"#,
"bar",
)
}
#[test]
fn module_def_import_uses_internal_command() -> TestResult {
run_test(
r#"module foo { def b [] { 2 }; export def a [] { b } }; use foo; foo a"#,
"2",
)
}
#[test]
fn module_env_import_uses_internal_command() -> TestResult {
run_test(
r#"module foo { def b [] { "2" }; export-env { $env.a = (b) } }; use foo; $env.a"#,
"2",
)
}
#[test]
fn multi_word_imports() -> TestResult {
run_test(
r#"module spam { export def "foo bar" [] { 10 } }; use spam "foo bar"; foo bar"#,
"10",
)
}
#[test]
fn export_alias() -> TestResult {
run_test(
r#"module foo { export alias hi = echo hello }; use foo hi; hi"#,
"hello",
)
}
#[test]
fn export_consts() -> TestResult {
run_test(
r#"module spam { export const b = 3; }; use spam b; $b"#,
"3",
)?;
run_test(
r#"module spam { export const b: int = 3; }; use spam b; $b"#,
"3",
)
}
#[test]
fn dont_export_module_name_as_a_variable() -> TestResult {
fail_test(r#"module spam { }; use spam; $spam"#, "variable not found")
}
#[test]
fn func_use_consts() -> TestResult {
run_test(
r#"module spam { const b = 3; export def c [] { $b } }; use spam; spam c"#,
"3",
)
}
#[test]
fn export_module_which_defined_const() -> TestResult {
run_test(
r#"module spam { export const b = 3; export const c = 4 }; use spam; $spam.b + $spam.c"#,
"7",
)?;
fail_test(
r#"module spam { export const b = 3; export const c = 4 }; use spam; $b"#,
"variable not found",
)
}
#[rstest]
#[case("spam-mod")]
#[case("spam/mod")]
#[case("spam=mod")]
fn export_module_with_normalized_var_name(#[case] name: &str) -> TestResult {
let def = format!(
"module {name} {{ export const b = 3; export module {name}2 {{ export const c = 4 }} }}"
);
run_test(&format!("{def}; use {name}; $spam_mod.b"), "3")?;
run_test(&format!("{def}; use {name} *; $spam_mod2.c"), "4")
}
#[rstest]
#[case("spam-mod")]
#[case("spam/mod")]
fn use_module_with_invalid_var_name(#[case] name: &str) -> TestResult {
fail_test(
&format!("module {name} {{ export const b = 3 }}; use {name}; ${name}"),
"expected valid variable name. Did you mean '$spam_mod'",
)
}
#[test]
fn cannot_export_private_const() -> TestResult {
fail_test(
r#"module spam { const b = 3; export const c = 4 }; use spam; $spam.b + $spam.c"#,
"cannot find column 'b'",
)
}
#[test]
fn test_lexical_binding() -> TestResult {
run_test(
r#"module spam { const b = 3; export def c [] { $b } }; use spam c; const b = 4; c"#,
"3",
)?;
run_test(
r#"const b = 4; module spam { const b = 3; export def c [] { $b } }; use spam; spam c"#,
"3",
)
}
#[test]
fn propagate_errors_in_export_env_on_use() -> TestResult {
fail_test(
r#"module foo { export-env { error make -u { msg: "error in export-env"} } }; use foo"#,
"error in export-env",
)
}
#[test]
fn propagate_errors_in_export_env_when_run() -> TestResult {
fail_test(
r#"export-env { error make -u { msg: "error in export-env" } }"#,
"error in export-env",
)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/repl/test_config_path.rs | tests/repl/test_config_path.rs | use nu_path::{AbsolutePath, AbsolutePathBuf, Path};
use nu_test_support::nu;
use nu_test_support::playground::{Executable, Playground};
use pretty_assertions::assert_eq;
use std::fs::{self, File};
#[cfg(not(target_os = "windows"))]
fn adjust_canonicalization<P: AsRef<Path>>(p: P) -> String {
p.as_ref().display().to_string()
}
#[cfg(target_os = "windows")]
fn adjust_canonicalization<P: AsRef<Path>>(p: P) -> String {
const VERBATIM_PREFIX: &str = r"\\?\";
let p = p.as_ref().display().to_string();
if let Some(stripped) = p.strip_prefix(VERBATIM_PREFIX) {
stripped.to_string()
} else {
p
}
}
/// The default Nushell config directory, ignoring XDG_CONFIG_HOME
fn non_xdg_config_dir() -> AbsolutePathBuf {
#[cfg(any(target_os = "windows", target_os = "macos"))]
let config_dir = dirs::config_dir().expect("Could not get config directory");
// On Linux, dirs::config_dir checks $XDG_CONFIG_HOME first, then gets $HOME/.config,
// so we have to get $HOME ourselves
#[cfg(target_os = "linux")]
let config_dir = {
let mut dir = dirs::home_dir().expect("Could not get config directory");
dir.push(".config");
dir
};
let config_dir = config_dir.canonicalize().unwrap_or(config_dir);
let mut config_dir_nushell =
AbsolutePathBuf::try_from(config_dir).expect("Invalid config directory");
config_dir_nushell.push("nushell");
config_dir_nushell
}
/// Make the config directory a symlink that points to a temporary folder, and also makes
/// the nushell directory inside a symlink.
/// Returns the path to the `nushell` config folder inside, via the symlink.
fn setup_fake_config(playground: &mut Playground) -> AbsolutePathBuf {
let config_real = "config_real";
let config_link = "config_link";
let nushell_real = "nushell_real";
let nushell_link = Path::new(config_real)
.join("nushell")
.into_os_string()
.into_string()
.unwrap();
let config_home = playground.cwd().join(config_link);
playground.mkdir(nushell_real);
playground.mkdir(config_real);
playground.symlink(nushell_real, &nushell_link);
playground.symlink(config_real, config_link);
playground.with_env("XDG_CONFIG_HOME", config_home.to_str().unwrap());
let path = config_home.join("nushell");
path.canonicalize().map(Into::into).unwrap_or(path)
}
fn run(playground: &mut Playground, command: &str) -> String {
if let Ok(home) = std::env::var("HOME") {
playground.with_env("HOME", home.as_str());
}
let result = playground.pipeline(command).execute().map_err(|e| {
let outcome = e.output.map(|outcome| {
format!(
"out: '{}', err: '{}'",
String::from_utf8_lossy(&outcome.out),
String::from_utf8_lossy(&outcome.err)
)
});
format!(
"desc: {}, exit: {:?}, outcome: {}",
e.desc,
e.exit,
outcome.unwrap_or("empty".to_owned())
)
});
String::from_utf8_lossy(&result.unwrap().out)
.trim()
.to_string()
}
#[cfg(not(windows))]
fn run_interactive_stderr(xdg_config_home: impl AsRef<Path>) -> String {
let child_output = std::process::Command::new("sh")
.arg("-c")
.arg(format!(
"{:?} -i -c 'echo $nu.is-interactive'",
nu_test_support::fs::executable_path()
))
.env("XDG_CONFIG_HOME", adjust_canonicalization(xdg_config_home))
.output()
.expect("Should have outputted");
String::from_utf8_lossy(&child_output.stderr)
.trim()
.to_string()
}
fn test_config_path_helper(
playground: &mut Playground,
config_dir_nushell: impl AsRef<AbsolutePath>,
) {
let config_dir_nushell = config_dir_nushell.as_ref();
// Create the config dir folder structure if it does not already exist
if !config_dir_nushell.exists() {
let _ = fs::create_dir_all(config_dir_nushell);
}
let config_dir_nushell = config_dir_nushell
.canonicalize()
.expect("canonicalize config dir failed");
let actual = run(playground, "$nu.default-config-dir");
assert_eq!(actual, adjust_canonicalization(&config_dir_nushell));
let config_path = config_dir_nushell.join("config.nu");
// We use canonicalize here in case the config or env is symlinked since $nu.config-path is returning the canonicalized path in #8653
let canon_config_path =
adjust_canonicalization(std::fs::canonicalize(&config_path).unwrap_or(config_path.into()));
let actual = run(playground, "$nu.config-path");
assert_eq!(actual, canon_config_path);
let env_path = config_dir_nushell.join("env.nu");
let canon_env_path =
adjust_canonicalization(std::fs::canonicalize(&env_path).unwrap_or(env_path.into()));
let actual = run(playground, "$nu.env-path");
assert_eq!(actual, canon_env_path);
let history_path = config_dir_nushell.join("history.txt");
let canon_history_path = adjust_canonicalization(
std::fs::canonicalize(&history_path).unwrap_or(history_path.into()),
);
let actual = run(playground, "$nu.history-path");
assert_eq!(actual, canon_history_path);
let login_path = config_dir_nushell.join("login.nu");
let canon_login_path =
adjust_canonicalization(std::fs::canonicalize(&login_path).unwrap_or(login_path.into()));
let actual = run(playground, "$nu.loginshell-path");
assert_eq!(actual, canon_login_path);
#[cfg(feature = "plugin")]
{
let plugin_path = config_dir_nushell.join("plugin.msgpackz");
let canon_plugin_path = adjust_canonicalization(
std::fs::canonicalize(&plugin_path).unwrap_or(plugin_path.into()),
);
let actual = run(playground, "$nu.plugin-path");
assert_eq!(actual, canon_plugin_path);
}
}
/// Test that the config files are in the right places when XDG_CONFIG_HOME isn't set
#[test]
fn test_default_config_path() {
Playground::setup("default_config_path", |_, playground| {
test_config_path_helper(playground, non_xdg_config_dir());
});
}
/// Make the config folder a symlink to a temporary folder without any config files
/// and see if the config files' paths are properly canonicalized
#[test]
fn test_default_symlinked_config_path_empty() {
Playground::setup("symlinked_empty_config_dir", |_, playground| {
let config_dir_nushell = setup_fake_config(playground);
test_config_path_helper(playground, config_dir_nushell);
});
}
/// Like [`test_default_symlinked_config_path_empty`], but fill the temporary folder
/// with broken symlinks and see if they're properly canonicalized
#[test]
fn test_default_symlink_config_path_broken_symlink_config_files() {
Playground::setup(
"symlinked_cfg_dir_with_symlinked_cfg_files_broken",
|_, playground| {
let fake_config_dir_nushell = setup_fake_config(playground);
let fake_dir = "fake";
playground.mkdir(fake_dir);
let fake_dir = Path::new(fake_dir);
for config_file in [
"config.nu",
"env.nu",
"history.txt",
"history.sqlite3",
"login.nu",
"plugin.msgpackz",
] {
let fake_file = fake_dir.join(config_file);
File::create(playground.cwd().join(&fake_file)).unwrap();
playground.symlink(&fake_file, fake_config_dir_nushell.join(config_file));
}
// Windows doesn't allow creating a symlink without the file existing,
// so we first create original files for the symlinks, then delete them
// to break the symlinks
std::fs::remove_dir_all(playground.cwd().join(fake_dir)).unwrap();
test_config_path_helper(playground, fake_config_dir_nushell);
},
);
}
/// Like [`test_default_symlinked_config_path_empty`], but fill the temporary folder
/// with working symlinks to empty files and see if they're properly canonicalized
#[test]
fn test_default_config_path_symlinked_config_files() {
Playground::setup(
"symlinked_cfg_dir_with_symlinked_cfg_files",
|_, playground| {
let fake_config_dir_nushell = setup_fake_config(playground);
for config_file in [
"config.nu",
"env.nu",
"history.txt",
"history.sqlite3",
"login.nu",
"plugin.msgpackz",
] {
let empty_file = playground.cwd().join(format!("empty-{config_file}"));
File::create(&empty_file).unwrap();
playground.symlink(empty_file, fake_config_dir_nushell.join(config_file));
}
test_config_path_helper(playground, fake_config_dir_nushell);
},
);
}
#[test]
fn test_alternate_config_path() {
let config_file = "crates/nu-utils/src/default_files/scaffold_config.nu";
let env_file = "crates/nu-utils/src/default_files/scaffold_env.nu";
let cwd = std::env::current_dir().expect("Could not get current working directory");
let config_path =
nu_path::canonicalize_with(config_file, &cwd).expect("Could not get config path");
let actual = nu!(
cwd: &cwd,
format!("nu --config {config_path:?} -c '$nu.config-path'")
);
assert_eq!(actual.out, config_path.to_string_lossy().to_string());
let env_path = nu_path::canonicalize_with(env_file, &cwd).expect("Could not get env path");
let actual = nu!(
cwd: &cwd,
format!("nu --env-config {env_path:?} -c '$nu.env-path'")
);
assert_eq!(actual.out, env_path.to_string_lossy().to_string());
}
#[test]
fn use_last_config_path() {
let config_file = "crates/nu-utils/src/default_files/scaffold_config.nu";
let env_file = "crates/nu-utils/src/default_files/scaffold_env.nu";
let cwd = std::env::current_dir().expect("Could not get current working directory");
let config_path =
nu_path::canonicalize_with(config_file, &cwd).expect("Could not get config path");
let actual = nu!(
cwd: &cwd,
format!("nu --config non-existing-path --config another-random-path.nu --config {config_path:?} -c '$nu.config-path'")
);
assert_eq!(actual.out, config_path.to_string_lossy().to_string());
let env_path = nu_path::canonicalize_with(env_file, &cwd).expect("Could not get env path");
let actual = nu!(
cwd: &cwd,
format!("nu --env-config non-existing-path --env-config {env_path:?} -c '$nu.env-path'")
);
assert_eq!(actual.out, env_path.to_string_lossy().to_string());
}
#[test]
fn test_xdg_config_empty() {
Playground::setup("xdg_config_empty", |_, playground| {
playground.with_env("XDG_CONFIG_HOME", "");
let actual = run(playground, "$nu.default-config-dir");
let expected = non_xdg_config_dir();
assert_eq!(actual, adjust_canonicalization(expected));
});
}
#[test]
fn test_xdg_config_bad() {
Playground::setup("xdg_config_bad", |_, playground| {
let xdg_config_home = r#"mn2''6t\/k*((*&^//k//: "#;
playground.with_env("XDG_CONFIG_HOME", xdg_config_home);
let actual = run(playground, "$nu.default-config-dir");
let expected = non_xdg_config_dir();
assert_eq!(actual, adjust_canonicalization(expected));
#[cfg(not(windows))]
{
let stderr = run_interactive_stderr(xdg_config_home);
assert!(
stderr.contains("xdg_config_home_invalid"),
"stderr was {stderr}"
);
}
});
}
/// Shouldn't complain if XDG_CONFIG_HOME is a symlink
#[test]
#[cfg(not(windows))]
fn test_xdg_config_symlink() {
Playground::setup("xdg_config_symlink", |_, playground| {
let config_link = "config_link";
playground.symlink("real", config_link);
let stderr = run_interactive_stderr(playground.cwd().join(config_link));
assert!(
!stderr.contains("xdg_config_home_invalid"),
"stderr was {stderr}"
);
});
}
#[test]
fn no_config_does_not_load_env_files() {
let nu = nu_test_support::fs::executable_path().display().to_string();
let cmd = format!(
r#"
{nu} -n -c "view files | where filename =~ 'env\\.nu$' | length"
"#
);
let actual = nu!(cmd);
assert_eq!(actual.out, "0");
}
#[test]
fn no_config_does_not_load_config_files() {
let nu = nu_test_support::fs::executable_path().display().to_string();
let cmd = format!(
r#"
{nu} -n -c "view files | where filename =~ 'config\\.nu$' | length"
"#
);
let actual = nu!(cmd);
assert_eq!(actual.out, "0");
}
#[test]
fn commandstring_does_not_load_config_files() {
let nu = nu_test_support::fs::executable_path().display().to_string();
let cmd = format!(
r#"
{nu} -c "view files | where filename =~ 'config\\.nu$' | length"
"#
);
let actual = nu!(cmd);
assert_eq!(actual.out, "0");
}
#[test]
fn commandstring_does_not_load_user_env() {
let nu = nu_test_support::fs::executable_path().display().to_string();
let cmd = format!(
r#"
{nu} -c "view files | where filename =~ '[^_]env\\.nu$' | length"
"#
);
let actual = nu!(cmd);
assert_eq!(actual.out, "0");
}
#[test]
fn commandstring_loads_default_env() {
let nu = nu_test_support::fs::executable_path().display().to_string();
let cmd = format!(
r#"
{nu} -c "view files | where filename =~ 'default_env\\.nu$' | length"
"#
);
let actual = nu!(cmd);
assert_eq!(actual.out, "1");
}
#[test]
fn commandstring_populates_config_record() {
let nu = nu_test_support::fs::executable_path().display().to_string();
let cmd = format!(
r#"
{nu} --no-std-lib -n -c "$env.config.show_banner"
"#
);
let actual = nu!(cmd);
assert_eq!(actual.out, "true");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/repl/test_hiding.rs | tests/repl/test_hiding.rs | use crate::repl::tests::{TestResult, fail_test, run_test};
// TODO: Test the use/hide tests also as separate lines in REPL (i.e., with merging the delta in between)
#[test]
fn hides_def() -> TestResult {
fail_test(
r#"def myfoosymbol [] { "myfoosymbol" }; hide myfoosymbol; myfoosymbol"#,
"external_command",
)
}
#[test]
fn hides_alias() -> TestResult {
fail_test(
r#"alias myfoosymbol = echo "myfoosymbol"; hide myfoosymbol; myfoosymbol"#,
"external_command",
)
}
#[test]
fn hides_env() -> TestResult {
fail_test(
r#"$env.myfoosymbol = "myfoosymbol"; hide-env myfoosymbol; $env.myfoosymbol"#,
"",
)
}
#[test]
fn hides_def_then_redefines() -> TestResult {
// this one should fail because of predecl -- cannot have more defs with the same name in a
// block
fail_test(
r#"def myfoosymbol [] { "myfoosymbol" }; hide myfoosymbol; def myfoosymbol [] { "bar" }; myfoosymbol"#,
"defined more than once",
)
}
#[ignore = "TODO: We'd need to make predecls work with hiding as well"]
#[test]
fn hides_alias_then_redefines() -> TestResult {
run_test(
r#"alias myfoosymbol = echo "myfoosymbol"; hide myfoosymbol; alias myfoosymbol = echo "myfoosymbol"; myfoosymbol"#,
"myfoosymbol",
)
}
#[test]
fn hides_env_then_redefines() -> TestResult {
run_test(
r#"$env.myfoosymbol = "myfoosymbol"; hide-env myfoosymbol; $env.myfoosymbol = "bar"; $env.myfoosymbol"#,
"bar",
)
}
#[test]
fn hides_def_in_scope_1() -> TestResult {
fail_test(
r#"def myfoosymbol [] { "myfoosymbol" }; do { hide myfoosymbol; myfoosymbol }"#,
"external_command",
)
}
#[test]
fn hides_def_in_scope_2() -> TestResult {
run_test(
r#"def myfoosymbol [] { "myfoosymbol" }; do { def myfoosymbol [] { "bar" }; hide myfoosymbol; myfoosymbol }"#,
"myfoosymbol",
)
}
#[test]
fn hides_def_in_scope_3() -> TestResult {
fail_test(
r#"def myfoosymbol [] { "myfoosymbol" }; do { hide myfoosymbol; def myfoosymbol [] { "bar" }; hide myfoosymbol; myfoosymbol }"#,
"external_command",
)
}
#[test]
fn hides_def_in_scope_4() -> TestResult {
fail_test(
r#"def myfoosymbol [] { "myfoosymbol" }; do { def myfoosymbol [] { "bar" }; hide myfoosymbol; hide myfoosymbol; myfoosymbol }"#,
"external_command",
)
}
#[test]
fn hides_alias_in_scope_1() -> TestResult {
fail_test(
r#"alias myfoosymbol = echo "myfoosymbol"; do { hide myfoosymbol; myfoosymbol }"#,
"external_command",
)
}
#[test]
fn hides_alias_in_scope_2() -> TestResult {
run_test(
r#"alias myfoosymbol = echo "myfoosymbol"; do { alias myfoosymbol = echo "bar"; hide myfoosymbol; myfoosymbol }"#,
"myfoosymbol",
)
}
#[test]
fn hides_alias_in_scope_3() -> TestResult {
fail_test(
r#"alias myfoosymbol = echo "myfoosymbol"; do { hide myfoosymbol; alias myfoosymbol = echo "bar"; hide myfoosymbol; myfoosymbol }"#,
"external_command",
)
}
#[test]
fn hides_alias_in_scope_4() -> TestResult {
fail_test(
r#"alias myfoosymbol = echo "myfoosymbol"; do { alias myfoosymbol = echo "bar"; hide myfoosymbol; hide myfoosymbol; myfoosymbol }"#,
"external_command",
)
}
#[test]
fn hides_env_in_scope_1() -> TestResult {
fail_test(
r#"$env.myfoosymbol = "myfoosymbol"; do { hide-env myfoosymbol; $env.myfoosymbol }"#,
"not_found",
)
}
#[test]
fn hides_env_in_scope_2() -> TestResult {
run_test(
r#"$env.myfoosymbol = "myfoosymbol"; do { $env.myfoosymbol = "bar"; hide-env myfoosymbol; $env.myfoosymbol }"#,
"myfoosymbol",
)
}
#[test]
fn hides_env_in_scope_3() -> TestResult {
fail_test(
r#"$env.myfoosymbol = "myfoosymbol"; do { hide-env myfoosymbol; $env.myfoosymbol = "bar"; hide-env myfoosymbol; $env.myfoosymbol }"#,
"",
)
}
#[test]
fn hides_env_in_scope_4() -> TestResult {
fail_test(
r#"$env.myfoosymbol = "myfoosymbol"; do { $env.myfoosymbol = "bar"; hide-env myfoosymbol; hide-env myfoosymbol; $env.myfoosymbol }"#,
"",
)
}
#[test]
#[ignore]
fn hide_def_twice_not_allowed() -> TestResult {
fail_test(
r#"def myfoosymbol [] { "myfoosymbol" }; hide myfoosymbol; hide myfoosymbol"#,
"did not find",
)
}
#[test]
#[ignore]
fn hide_alias_twice_not_allowed() -> TestResult {
fail_test(
r#"alias myfoosymbol = echo "myfoosymbol"; hide myfoosymbol; hide myfoosymbol"#,
"did not find",
)
}
#[test]
fn hide_env_twice_not_allowed() -> TestResult {
fail_test(
r#"$env.myfoosymbol = "myfoosymbol"; hide-env myfoosymbol; hide-env myfoosymbol"#,
"",
)
}
#[test]
fn hide_env_twice_allowed() -> TestResult {
fail_test(
r#"$env.myfoosymbol = "myfoosymbol"; hide-env myfoosymbol; hide-env -i myfoosymbol; $env.myfoosymbol"#,
"",
)
}
#[test]
fn hides_def_runs_env() -> TestResult {
run_test(
r#"$env.myfoosymbol = "bar"; def myfoosymbol [] { "myfoosymbol" }; hide myfoosymbol; $env.myfoosymbol"#,
"bar",
)
}
#[test]
fn hides_def_import_1() -> TestResult {
fail_test(
r#"module myspammodule { export def myfoosymbol [] { "myfoosymbol" } }; use myspammodule; hide myspammodule myfoosymbol; myspammodule myfoosymbol"#,
"external_command",
)
}
#[test]
fn hides_def_import_2() -> TestResult {
fail_test(
r#"module myspammodule { export def myfoosymbol [] { "myfoosymbol" } }; use myspammodule; hide myspammodule; myspammodule myfoosymbol"#,
"external_command",
)
}
#[test]
fn hides_def_import_3() -> TestResult {
fail_test(
r#"module myspammodule { export def myfoosymbol [] { "myfoosymbol" } }; use myspammodule; hide myspammodule [myfoosymbol]; myspammodule myfoosymbol"#,
"external_command",
)
}
#[test]
fn hides_def_import_4() -> TestResult {
fail_test(
r#"module myspammodule { export def myfoosymbol [] { "myfoosymbol" } }; use myspammodule myfoosymbol; hide myfoosymbol; myfoosymbol"#,
"external_command",
)
}
#[test]
fn hides_def_import_5() -> TestResult {
fail_test(
r#"module myspammodule { export def myfoosymbol [] { "myfoosymbol" } }; use myspammodule *; hide myfoosymbol; myfoosymbol"#,
"external_command",
)
}
#[test]
fn hides_def_import_6() -> TestResult {
fail_test(
r#"module myspammodule { export def myfoosymbol [] { "myfoosymbol" } }; use myspammodule *; hide myspammodule *; myfoosymbol"#,
"external_command",
)
}
#[test]
fn hides_def_import_then_reimports() -> TestResult {
run_test(
r#"module myspammodule { export def myfoosymbol [] { "myfoosymbol" } }; use myspammodule myfoosymbol; hide myfoosymbol; use myspammodule myfoosymbol; myfoosymbol"#,
"myfoosymbol",
)
}
#[test]
fn hides_alias_import_1() -> TestResult {
fail_test(
r#"module myspammodule { export alias myfoosymbol = echo "myfoosymbol" }; use myspammodule; hide myspammodule myfoosymbol; myspammodule myfoosymbol"#,
"external_command",
)
}
#[test]
fn hides_alias_import_2() -> TestResult {
fail_test(
r#"module myspammodule { export alias myfoosymbol = echo "myfoosymbol" }; use myspammodule; hide myspammodule; myspammodule myfoosymbol"#,
"external_command",
)
}
#[test]
fn hides_alias_import_3() -> TestResult {
fail_test(
r#"module myspammodule { export alias myfoosymbol = echo "myfoosymbol" }; use myspammodule; hide myspammodule [myfoosymbol]; myspammodule myfoosymbol"#,
"external_command",
)
}
#[test]
fn hides_alias_import_4() -> TestResult {
fail_test(
r#"module myspammodule { export alias myfoosymbol = echo "myfoosymbol" }; use myspammodule myfoosymbol; hide myfoosymbol; myfoosymbol"#,
"external_command",
)
}
#[test]
fn hides_alias_import_5() -> TestResult {
fail_test(
r#"module myspammodule { export alias myfoosymbol = echo "myfoosymbol" }; use myspammodule *; hide myfoosymbol; myfoosymbol"#,
"external_command",
)
}
#[test]
fn hides_alias_import_6() -> TestResult {
fail_test(
r#"module myspammodule { export alias myfoosymbol = echo "myfoosymbol" }; use myspammodule *; hide myspammodule *; myfoosymbol"#,
"external_command",
)
}
#[test]
fn hides_alias_import_then_reimports() -> TestResult {
run_test(
r#"module myspammodule { export alias myfoosymbol = echo "myfoosymbol" }; use myspammodule myfoosymbol; hide myfoosymbol; use myspammodule myfoosymbol; myfoosymbol"#,
"myfoosymbol",
)
}
#[test]
fn hides_env_import_1() -> TestResult {
fail_test(
r#"module myspammodule { export-env { $env.myfoosymbol = "myfoosymbol" } }; use myspammodule; hide-env myfoosymbol; $env.myfoosymbol"#,
"",
)
}
#[test]
fn hides_def_runs_env_import() -> TestResult {
run_test(
r#"module myspammodule { export-env { $env.myfoosymbol = "myfoosymbol" }; export def myfoosymbol [] { "bar" } }; use myspammodule myfoosymbol; hide myfoosymbol; $env.myfoosymbol"#,
"myfoosymbol",
)
}
#[test]
fn hides_def_and_env_import_1() -> TestResult {
fail_test(
r#"module myspammodule { export-env { $env.myfoosymbol = "myfoosymbol" }; export def myfoosymbol [] { "bar" } }; use myspammodule myfoosymbol; hide myfoosymbol; hide-env myfoosymbol; $env.myfoosymbol"#,
"",
)
}
#[test]
fn use_def_import_after_hide() -> TestResult {
run_test(
r#"module myspammodule { export def myfoosymbol [] { "myfoosymbol" } }; use myspammodule myfoosymbol; hide myfoosymbol; use myspammodule myfoosymbol; myfoosymbol"#,
"myfoosymbol",
)
}
#[test]
fn use_env_import_after_hide() -> TestResult {
run_test(
r#"module myspammodule { export-env { $env.myfoosymbol = "myfoosymbol" } }; use myspammodule; hide-env myfoosymbol; use myspammodule; $env.myfoosymbol"#,
"myfoosymbol",
)
}
#[test]
fn hide_shadowed_decl() -> TestResult {
run_test(
r#"module myspammodule { export def myfoosymbol [] { "bar" } }; def myfoosymbol [] { "myfoosymbol" }; do { use myspammodule myfoosymbol; hide myfoosymbol; myfoosymbol }"#,
"myfoosymbol",
)
}
#[test]
fn hide_shadowed_env() -> TestResult {
run_test(
r#"module myspammodule { export-env { $env.myfoosymbol = "bar" } }; $env.myfoosymbol = "myfoosymbol"; do { use myspammodule; hide-env myfoosymbol; $env.myfoosymbol }"#,
"myfoosymbol",
)
}
#[test]
fn hides_all_decls_within_scope() -> TestResult {
fail_test(
r#"module myspammodule { export def myfoosymbol [] { "bar" } }; def myfoosymbol [] { "myfoosymbol" }; use myspammodule myfoosymbol; hide myfoosymbol; myfoosymbol"#,
"external_command",
)
}
#[test]
fn hides_all_envs_within_scope() -> TestResult {
fail_test(
r#"module myspammodule { export-env { $env.myfoosymbol = "bar" } }; $env.myfoosymbol = "myfoosymbol"; use myspammodule; hide-env myfoosymbol; $env.myfoosymbol"#,
"",
)
}
#[test]
fn hides_main_import_1() -> TestResult {
fail_test(
r#"module myspammodule { export def main [] { "myfoosymbol" } }; use myspammodule; hide myspammodule; myspammodule"#,
"external_command",
)
}
#[test]
fn hides_main_import_2() -> TestResult {
fail_test(
r#"module myspammodule { export def main [] { "myfoosymbol" } }; use myspammodule; hide myspammodule main; myspammodule"#,
"external_command",
)
}
#[test]
fn hides_main_import_3() -> TestResult {
fail_test(
r#"module myspammodule { export def main [] { "myfoosymbol" } }; use myspammodule; hide myspammodule [ main ]; myspammodule"#,
"external_command",
)
}
#[test]
fn hides_main_import_4() -> TestResult {
fail_test(
r#"module myspammodule { export def main [] { "myfoosymbol" } }; use myspammodule; hide myspammodule *; myspammodule"#,
"external_command",
)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/repl/test_known_external.rs | tests/repl/test_known_external.rs | use crate::repl::tests::{TestResult, fail_test, run_test, run_test_contains};
use std::process::Command;
// cargo version prints a string of the form:
// cargo 1.60.0 (d1fd9fe2c 2022-03-01)
#[test]
fn known_external_runs() -> TestResult {
run_test_contains(r#"extern "cargo version" []; cargo version"#, "cargo")
}
#[test]
fn known_external_unknown_flag() -> TestResult {
run_test_contains(r#"extern "cargo" []; cargo --version"#, "cargo")
}
/// GitHub issues #5179, #4618
#[test]
fn known_external_alias() -> TestResult {
run_test_contains(
r#"extern "cargo version" []; alias cv = cargo version; cv"#,
"cargo",
)
}
/// GitHub issues #5179, #4618
#[test]
fn known_external_subcommand_alias() -> TestResult {
run_test_contains(
r#"extern "cargo version" []; alias c = cargo; c version"#,
"cargo",
)
}
#[test]
fn known_external_complex_unknown_args() -> TestResult {
run_test_contains(
"extern echo []; echo foo -b -as -9 --abc -- -Dxmy=AKOO - bar",
"foo -b -as -9 --abc -- -Dxmy=AKOO - bar",
)
}
#[test]
fn known_external_from_module() -> TestResult {
run_test_contains(
r#"module spam {
export extern echo []
}
use spam echo
echo foo -b -as -9 --abc -- -Dxmy=AKOO - bar
"#,
"foo -b -as -9 --abc -- -Dxmy=AKOO - bar",
)
}
#[test]
fn known_external_short_flag_batch_arg_allowed() -> TestResult {
run_test_contains("extern echo [-a, -b: int]; echo -ab 10", "-b 10")
}
#[test]
fn known_external_short_flag_batch_arg_disallowed() -> TestResult {
fail_test(
"extern echo [-a: int, -b]; echo -ab 10",
"last flag can take args",
)
}
#[test]
fn known_external_short_flag_batch_multiple_args() -> TestResult {
fail_test(
"extern echo [-a: int, -b: int]; echo -ab 10 20",
"last flag can take args",
)
}
#[test]
fn known_external_missing_positional() -> TestResult {
fail_test("extern echo [a]; echo", "missing_positional")
}
#[test]
fn known_external_type_mismatch() -> TestResult {
fail_test("extern echo [a: int]; echo 1.234", "mismatch")
}
#[test]
fn known_external_missing_flag_param() -> TestResult {
fail_test(
"extern echo [--foo: string]; echo --foo",
"missing_flag_param",
)
}
#[test]
fn known_external_misc_values() -> TestResult {
run_test(
r#"
let x = 'abc'
extern echo [...args]
echo $x ...[ a b c ]
"#,
"abc a b c",
)
}
/// GitHub issue #7822
#[test]
fn known_external_subcommand_from_module() -> TestResult {
let output = Command::new("cargo").arg("add").arg("-h").output()?;
run_test(
r#"
module cargo {
export extern add []
};
use cargo;
cargo add -h
"#,
String::from_utf8(output.stdout)?.trim(),
)
}
/// GitHub issue #7822
#[test]
fn known_external_aliased_subcommand_from_module() -> TestResult {
let output = Command::new("cargo").arg("add").arg("-h").output()?;
run_test(
r#"
module cargo {
export extern add []
};
use cargo;
alias cc = cargo add;
cc -h
"#,
String::from_utf8(output.stdout)?.trim(),
)
}
#[test]
fn known_external_arg_expansion() -> TestResult {
run_test(
r#"
extern echo [];
echo ~/foo
"#,
&dirs::home_dir()
.expect("can't find home dir")
.join("foo")
.to_string_lossy(),
)
}
#[test]
fn known_external_arg_quoted_no_expand() -> TestResult {
run_test(
r#"
extern echo [];
echo "~/foo"
"#,
"~/foo",
)
}
#[test]
fn known_external_arg_internally_quoted_options() -> TestResult {
run_test(
r#"
extern echo [];
echo --option="test"
"#,
"--option=test",
)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/repl/test_env.rs | tests/repl/test_env.rs | use crate::repl::tests::{TestResult, fail_test, run_test};
use nu_test_support::nu;
#[test]
fn shorthand_env_1() -> TestResult {
run_test(r#"FOO=BAZ $env.FOO"#, "BAZ")
}
#[test]
fn shorthand_env_2() -> TestResult {
fail_test(r#"FOO=BAZ FOO=MOO $env.FOO"#, "defined_twice")
}
#[test]
fn shorthand_env_3() -> TestResult {
run_test(r#"FOO=BAZ BAR=MOO $env.FOO"#, "BAZ")
}
#[test]
fn default_nu_lib_dirs_env_type() {
// Previously, this was a list<string>
// While we are transitioning to const NU_LIB_DIRS
// the env version will be empty, and thus a
// list<any>
let actual = nu!("$env.NU_LIB_DIRS | describe");
assert_eq!(actual.out, "list<any>");
}
#[test]
fn default_nu_lib_dirs_type() {
let actual = nu!("$NU_LIB_DIRS | describe");
assert_eq!(actual.out, "list<string>");
}
#[test]
fn default_nu_plugin_dirs_env_type() {
// Previously, this was a list<string>
// While we are transitioning to const NU_PLUGIN_DIRS
// the env version will be empty, and thus a
// list<any>
let actual = nu!("$env.NU_PLUGIN_DIRS | describe");
assert_eq!(actual.out, "list<any>");
}
#[test]
fn default_nu_plugin_dirs_type() {
let actual = nu!("$NU_PLUGIN_DIRS | describe");
assert_eq!(actual.out, "list<string>");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/repl/test_ranges.rs | tests/repl/test_ranges.rs | use crate::repl::tests::{TestResult, fail_test, run_test};
use rstest::rstest;
#[test]
fn int_in_inc_range() -> TestResult {
run_test(r#"1 in -4..9.42"#, "true")
}
#[test]
fn int_in_dec_range() -> TestResult {
run_test(r#"1 in 9..-4.42"#, "true")
}
#[test]
fn int_in_exclusive_range() -> TestResult {
run_test(r#"3 in 0..<3"#, "false")
}
#[test]
fn float_in_inc_range() -> TestResult {
run_test(r#"1.58 in -4.42..9"#, "true")
}
#[test]
fn float_in_dec_range() -> TestResult {
run_test(r#"1.42 in 9.42..-4.42"#, "true")
}
#[test]
fn non_number_in_range() -> TestResult {
fail_test(r#"'a' in 1..3"#, "nu::parser::operator_incompatible_types")
}
#[test]
fn float_not_in_inc_range() -> TestResult {
run_test(r#"1.4 not-in 2..9.42"#, "true")
}
#[test]
fn range_and_reduction() -> TestResult {
run_test(r#"1..6..36 | math sum"#, "148")
}
#[test]
fn zip_ranges() -> TestResult {
run_test(r#"1..3 | zip 4..6 | get 2.1"#, "6")
}
#[test]
fn int_in_stepped_range() -> TestResult {
run_test(r#"7 in 1..3..15"#, "true")?;
run_test(r#"7 in 1..3..=15"#, "true")
}
#[test]
fn int_in_unbounded_stepped_range() -> TestResult {
run_test(r#"1000001 in 1..3.."#, "true")
}
#[test]
fn int_not_in_unbounded_stepped_range() -> TestResult {
run_test(r#"2 in 1..3.."#, "false")
}
#[test]
fn float_in_stepped_range() -> TestResult {
run_test(r#"5.5 in 1..1.5..10"#, "true")
}
#[test]
fn float_in_unbounded_stepped_range() -> TestResult {
run_test(r#"100.5 in 1..1.5.."#, "true")
}
#[test]
fn float_not_in_unbounded_stepped_range() -> TestResult {
run_test(r#"2.1 in 1.2..3.."#, "false")
}
#[rstest]
#[case("1..=3..", "expected number")]
#[case("..=3..=15", "expected number")]
#[case("..=(..", "expected closing )")]
#[case("..=()..", "expected at least one range bound")]
#[case("..=..", "expected at least one range bound")]
#[test]
fn bad_range_syntax(#[case] input: &str, #[case] expect: &str) -> TestResult {
fail_test(&format!("def foo [r: range] {{}}; foo {input}"), expect)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/repl/test_iteration.rs | tests/repl/test_iteration.rs | use crate::repl::tests::{TestResult, run_test};
#[test]
fn better_block_types() -> TestResult {
run_test(
r#"([1, 2, 3] | enumerate | each { |e| $"($e.index) is ($e.item)" }).1"#,
"1 is 2",
)
}
#[test]
fn row_iteration() -> TestResult {
run_test(
"[[name, size]; [tj, 100], [rl, 200]] | each { |it| $it.size * 8 } | get 1",
"1600",
)
}
#[test]
fn row_condition1() -> TestResult {
run_test(
"([[name, size]; [a, 1], [b, 2], [c, 3]] | where size < 3).name | get 1",
"b",
)
}
#[test]
fn row_condition2() -> TestResult {
run_test(
"[[name, size]; [a, 1], [b, 2], [c, 3]] | where $it.size > 2 | length",
"1",
)
}
#[test]
fn par_each() -> TestResult {
run_test(
r#"1..10 | enumerate | par-each { |it| ([[index, item]; [$it.index, ($it.item > 5)]]).0 } | where index == 4 | get item.0"#,
"false",
)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/repl/test_regex.rs | tests/repl/test_regex.rs | use crate::repl::tests::{TestResult, fail_test, run_test};
#[test]
fn contains() -> TestResult {
run_test(r#"'foobarbaz' =~ bar"#, "true")
}
#[test]
fn contains_case_insensitive() -> TestResult {
run_test(r#"'foobarbaz' =~ '(?i)BaR'"#, "true")
}
#[test]
fn not_contains() -> TestResult {
run_test(r#"'foobarbaz' !~ asdf"#, "true")
}
#[test]
fn match_full_line() -> TestResult {
run_test(r#"'foobarbaz' =~ '^foobarbaz$'"#, "true")
}
#[test]
fn not_match_full_line() -> TestResult {
run_test(r#"'foobarbaz' !~ '^foobarbaz$'"#, "false")
}
#[test]
fn starts_with() -> TestResult {
run_test(r#"'foobarbaz' =~ '^foo'"#, "true")
}
#[test]
fn not_starts_with() -> TestResult {
run_test(r#"'foobarbaz' !~ '^foo'"#, "false")
}
#[test]
fn ends_with() -> TestResult {
run_test(r#"'foobarbaz' =~ 'baz$'"#, "true")
}
#[test]
fn not_ends_with() -> TestResult {
run_test(r#"'foobarbaz' !~ 'baz$'"#, "false")
}
#[test]
fn where_works() -> TestResult {
run_test(
r#"[{name: somefile.txt} {name: anotherfile.csv }] | where name =~ ^s | get name.0"#,
"somefile.txt",
)
}
#[test]
fn where_not_works() -> TestResult {
run_test(
r#"[{name: somefile.txt} {name: anotherfile.csv }] | where name !~ ^s | get name.0"#,
"anotherfile.csv",
)
}
#[test]
fn invalid_regex_fails() -> TestResult {
fail_test(r#"'foo' =~ '['"#, "Invalid character class")
}
#[test]
fn invalid_not_regex_fails() -> TestResult {
fail_test(r#"'foo' !~ '['"#, "Invalid character class")
}
#[test]
fn regex_on_int_fails() -> TestResult {
fail_test(r#"33 =~ foo"#, "nu::parser::operator_unsupported_type")
}
#[test]
fn not_regex_on_int_fails() -> TestResult {
fail_test(r#"33 !~ foo"#, "nu::parser::operator_unsupported_type")
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/repl/test_parser.rs | tests/repl/test_parser.rs | use crate::repl::tests::{TestResult, fail_test, run_test, run_test_contains, run_test_with_env};
use nu_test_support::{nu, nu_repl_code};
use std::collections::HashMap;
#[test]
fn env_shorthand() -> TestResult {
run_test("FOO=BAR if false { 3 } else { 4 }", "4")
}
#[test]
fn subcommand() -> TestResult {
run_test("def foo [] {}; def \"foo bar\" [] {3}; foo bar", "3")
}
#[test]
fn alias_1() -> TestResult {
run_test("def foo [$x] { $x + 10 }; alias f = foo; f 100", "110")
}
#[test]
fn ints_with_underscores() -> TestResult {
run_test("1_0000_0000_0000 + 10", "1000000000010")
}
#[test]
fn floats_with_underscores() -> TestResult {
run_test("3.1415_9265_3589_793 * 2", "6.283185307179586")
}
#[test]
fn bin_ints_with_underscores() -> TestResult {
run_test("0b_10100_11101_10010", "21426")
}
#[test]
fn oct_ints_with_underscores() -> TestResult {
run_test("0o2443_6442_7652_0044", "90422533333028")
}
#[test]
fn hex_ints_with_underscores() -> TestResult {
run_test("0x68__9d__6a", "6856042")
}
#[test]
fn alias_2() -> TestResult {
run_test(
"def foo [$x $y] { $x + $y + 10 }; alias f = foo 33; f 100",
"143",
)
}
#[test]
fn alias_2_multi_word() -> TestResult {
run_test(
r#"def "foo bar" [$x $y] { $x + $y + 10 }; alias f = foo bar 33; f 100"#,
"143",
)
}
#[ignore = "TODO: Allow alias to alias existing command with the same name"]
#[test]
fn alias_recursion() -> TestResult {
run_test_contains(r#"alias ls = ls -a; ls"#, " ")
}
#[test]
fn block_param1() -> TestResult {
run_test("[3] | each { |it| $it + 10 } | get 0", "13")
}
#[test]
fn block_param2() -> TestResult {
run_test("[3] | each { |y| $y + 10 } | get 0", "13")
}
#[test]
fn block_param3_list_iteration() -> TestResult {
run_test("[1,2,3] | each { |it| $it + 10 } | get 1", "12")
}
#[test]
fn block_param4_list_iteration() -> TestResult {
run_test("[1,2,3] | each { |y| $y + 10 } | get 2", "13")
}
#[test]
fn range_iteration1() -> TestResult {
run_test("1..4 | each { |y| $y + 10 } | get 0", "11")
}
#[test]
fn range_iteration2() -> TestResult {
run_test("4..1 | each { |y| $y + 100 } | get 3", "101")
}
#[test]
fn range_ends_with_duration_suffix_variable_name() -> TestResult {
run_test("let runs = 10; 1..$runs | math sum", "55")
}
#[test]
fn range_ends_with_filesize_suffix_variable_name() -> TestResult {
run_test("let sizekb = 10; 1..$sizekb | math sum", "55")
}
#[test]
fn simple_value_iteration() -> TestResult {
run_test("4 | each { |it| $it + 10 }", "14")
}
#[test]
fn comment_multiline() -> TestResult {
run_test(
r#"def foo [] {
let x = 1 + 2 # comment
let y = 3 + 4 # another comment
$x + $y
}; foo"#,
"10",
)
}
#[test]
fn comment_skipping_1() -> TestResult {
run_test(
r#"let x = {
y: 20
# foo
}; $x.y"#,
"20",
)
}
#[test]
fn comment_skipping_2() -> TestResult {
run_test(
r#"let x = {
y: 20
# foo
z: 40
}; $x.z"#,
"40",
)
}
#[test]
fn comment_skipping_in_pipeline_1() -> TestResult {
run_test(
r#"[1,2,3] | #comment
each { |$it| $it + 2 } | # foo
math sum #bar"#,
"12",
)
}
#[test]
fn comment_skipping_in_pipeline_2() -> TestResult {
run_test(
r#"[1,2,3] #comment
| #comment2
each { |$it| $it + 2 } #foo
| # bar
math sum #baz"#,
"12",
)
}
#[test]
fn comment_skipping_in_pipeline_3() -> TestResult {
run_test(
r#"[1,2,3] | #comment
#comment2
each { |$it| $it + 2 } #foo
| # bar
#baz
math sum #foobar"#,
"12",
)
}
#[test]
fn still_string_if_hashtag_is_middle_of_string() -> TestResult {
run_test(r#"echo test#testing"#, "test#testing")
}
#[test]
fn non_comment_hashtag_in_comment_does_not_stop_comment() -> TestResult {
run_test(r#"# command_bar_text: { fg: '#C4C9C6' },"#, "")
}
#[test]
fn non_comment_hashtag_in_comment_does_not_stop_comment_in_block() -> TestResult {
run_test(
r#"{
explore: {
# command_bar_text: { fg: '#C4C9C6' },
}
} | get explore | is-empty"#,
"true",
)
}
#[test]
fn still_string_if_hashtag_is_middle_of_string_inside_each() -> TestResult {
run_test(
r#"1..1 | each {echo test#testing } | get 0"#,
"test#testing",
)
}
#[test]
fn still_string_if_hashtag_is_middle_of_string_inside_each_also_with_dot() -> TestResult {
run_test(r#"1..1 | each {echo '.#testing' } | get 0"#, ".#testing")
}
#[test]
fn bad_var_name() -> TestResult {
fail_test(r#"let $"foo bar" = 4"#, "can't contain")
}
#[test]
fn bad_var_name2() -> TestResult {
fail_test(r#"let $foo-bar = 4"#, "valid variable")?;
fail_test(r#"foo-bar=4 true"#, "Command `foo-bar=4` not found")
}
#[test]
fn bad_var_name3() -> TestResult {
fail_test(r#"let $=foo = 4"#, "valid variable")?;
fail_test(r#"=foo=4 true"#, "Command `=foo=4` not found")
}
#[test]
fn assignment_with_no_var() -> TestResult {
let cases = [
"let = if $",
"mut = if $",
"const = if $",
"let = 'foo' | $in; $x | describe",
"mut = 'foo' | $in; $x | describe",
];
let expecteds = [
"missing var_name",
"missing var_name",
"missing const_name",
"missing var_name",
"missing var_name",
];
for (case, expected) in std::iter::zip(cases, expecteds) {
fail_test(case, expected)?;
}
Ok(())
}
#[test]
fn too_few_arguments() -> TestResult {
// Test for https://github.com/nushell/nushell/issues/9072
let cases = [
"def a [b: bool, c: bool, d: float, e: float, f: float] {}; a true true 1 1",
"def a [b: bool, c: bool, d: float, e: float, f: float, g: float] {}; a true true 1 1",
"def a [b: bool, c: bool, d: float, e: float, f: float, g: float, h: float] {}; a true true 1 1",
];
let expected = "missing f";
for case in cases {
fail_test(case, expected)?;
}
Ok(())
}
#[test]
fn long_flag() -> TestResult {
run_test(
r#"([a, b, c] | enumerate | each --keep-empty { |e| if $e.index != 1 { 100 }}).1 | to nuon"#,
"null",
)
}
#[test]
fn for_in_missing_var_name() -> TestResult {
fail_test("for in", "missing")
}
#[test]
fn multiline_pipe_in_block() -> TestResult {
run_test(
r#"do {
echo hello |
str length
}"#,
"5",
)
}
#[test]
fn bad_short_flag() -> TestResult {
fail_test(r#"def foo3 [-l?:int] { $l }"#, "short flag")
}
#[test]
fn quotes_with_equals() -> TestResult {
run_test(
r#"let query_prefix = "https://api.github.com/search/issues?q=repo:nushell/"; $query_prefix"#,
"https://api.github.com/search/issues?q=repo:nushell/",
)
}
#[test]
fn string_interp_with_equals() -> TestResult {
run_test(
r#"let query_prefix = $"https://api.github.com/search/issues?q=repo:nushell/"; $query_prefix"#,
"https://api.github.com/search/issues?q=repo:nushell/",
)
}
#[test]
fn raw_string_with_equals() -> TestResult {
run_test(
r#"let query_prefix = r#'https://api.github.com/search/issues?q=repo:nushell/'#; $query_prefix"#,
"https://api.github.com/search/issues?q=repo:nushell/",
)
}
#[test]
fn raw_string_with_hashtag() -> TestResult {
run_test(r#"r##' one # two '##"#, "one # two")
}
#[test]
fn list_quotes_with_equals() -> TestResult {
run_test(
r#"["https://api.github.com/search/issues?q=repo:nushell/"] | get 0"#,
"https://api.github.com/search/issues?q=repo:nushell/",
)
}
#[test]
fn record_quotes_with_equals() -> TestResult {
run_test(r#"{"a=":b} | get a="#, "b")?;
run_test(r#"{"=a":b} | get =a"#, "b")?;
run_test(r#"{a:"=b"} | get a"#, "=b")?;
run_test(r#"{a:"b="} | get a"#, "b=")?;
run_test(r#"{a:b,"=c":d} | get =c"#, "d")?;
run_test(r#"{a:b,"c=":d} | get c="#, "d")
}
#[test]
fn recursive_parse() -> TestResult {
run_test(r#"def c [] { c }; echo done"#, "done")
}
#[test]
fn commands_have_description() -> TestResult {
run_test_contains(
r#"
# This is a test
#
# To see if I have cool description
def foo [] {}
help foo"#,
"cool description",
)
}
#[test]
fn commands_from_crlf_source_have_short_description() -> TestResult {
run_test_contains(
"# This is a test\r\n#\r\n# To see if I have cool description\r\ndef foo [] {}\r\nscope commands | where name == foo | get description.0",
"This is a test",
)
}
#[test]
fn commands_from_crlf_source_have_extra_description() -> TestResult {
run_test_contains(
"# This is a test\r\n#\r\n# To see if I have cool description\r\ndef foo [] {}\r\nscope commands | where name == foo | get extra_description.0",
"To see if I have cool description",
)
}
#[test]
fn equals_separates_long_flag() -> TestResult {
run_test(
r#"'nushell' | fill --alignment right --width=10 --character='-'"#,
"---nushell",
)
}
#[test]
fn assign_expressions() -> TestResult {
let env = HashMap::from([("VENV_OLD_PATH", "Foobar"), ("Path", "Quux")]);
run_test_with_env(
r#"$env.Path = (if ($env | columns | "VENV_OLD_PATH" in $in) { $env.VENV_OLD_PATH } else { $env.Path }); echo $env.Path"#,
"Foobar",
&env,
)
}
#[test]
fn assign_takes_pipeline() -> TestResult {
run_test(
r#"mut foo = 'bar'; $foo = $foo | str upcase | str reverse; $foo"#,
"RAB",
)
}
#[test]
fn append_assign_takes_pipeline() -> TestResult {
run_test(
r#"mut foo = 'bar'; $foo ++= $foo | str upcase; $foo"#,
"barBAR",
)
}
#[test]
fn assign_bare_external_fails() {
let result = nu!("$env.FOO = nu --testbin cococo");
assert!(!result.status.success());
assert!(result.err.contains("must be explicit"));
}
#[test]
fn assign_bare_external_with_caret() {
let result = nu!("$env.FOO = ^nu --testbin cococo");
assert!(result.status.success());
}
#[test]
fn assign_backtick_quoted_external_fails() {
let result = nu!("$env.FOO = `nu` --testbin cococo");
assert!(!result.status.success());
assert!(result.err.contains("must be explicit"));
}
#[test]
fn assign_backtick_quoted_external_with_caret() {
let result = nu!("$env.FOO = ^`nu` --testbin cococo");
assert!(result.status.success());
}
#[test]
fn string_interpolation_paren_test() -> TestResult {
run_test(r#"$"('(')(')')""#, "()")
}
#[test]
fn string_interpolation_paren_test2() -> TestResult {
run_test(r#"$"('(')test(')')""#, "(test)")
}
#[test]
fn string_interpolation_paren_test3() -> TestResult {
run_test(r#"$"('(')("test")test(')')""#, "(testtest)")
}
#[test]
fn string_interpolation_escaping() -> TestResult {
run_test(r#"$"hello\nworld" | lines | length"#, "2")
}
#[test]
fn capture_multiple_commands() -> TestResult {
run_test(
r#"
let CONST_A = 'Hello'
def 'say-hi' [] {
echo (call-me)
}
def 'call-me' [] {
echo $CONST_A
}
[(say-hi) (call-me)] | str join
"#,
"HelloHello",
)
}
#[test]
fn capture_multiple_commands2() -> TestResult {
run_test(
r#"
let CONST_A = 'Hello'
def 'call-me' [] {
echo $CONST_A
}
def 'say-hi' [] {
echo (call-me)
}
[(say-hi) (call-me)] | str join
"#,
"HelloHello",
)
}
#[test]
fn capture_multiple_commands3() -> TestResult {
run_test(
r#"
let CONST_A = 'Hello'
def 'say-hi' [] {
echo (call-me)
}
def 'call-me' [] {
echo $CONST_A
}
[(call-me) (say-hi)] | str join
"#,
"HelloHello",
)
}
#[test]
fn capture_multiple_commands4() -> TestResult {
run_test(
r#"
let CONST_A = 'Hello'
def 'call-me' [] {
echo $CONST_A
}
def 'say-hi' [] {
echo (call-me)
}
[(call-me) (say-hi)] | str join
"#,
"HelloHello",
)
}
#[test]
fn capture_row_condition() -> TestResult {
run_test(
r#"let name = "foo"; [foo] | where $'($name)' =~ $it | str join"#,
"foo",
)
}
#[test]
fn starts_with_operator_succeeds() -> TestResult {
run_test(
r#"[Moe Larry Curly] | where $it starts-with L | str join"#,
"Larry",
)
}
#[test]
fn not_starts_with_operator_succeeds() -> TestResult {
run_test(
r#"[Moe Larry Curly] | where $it not-starts-with L | str join"#,
"MoeCurly",
)
}
#[test]
fn ends_with_operator_succeeds() -> TestResult {
run_test(
r#"[Moe Larry Curly] | where $it ends-with ly | str join"#,
"Curly",
)
}
#[test]
fn not_ends_with_operator_succeeds() -> TestResult {
run_test(
r#"[Moe Larry Curly] | where $it not-ends-with y | str join"#,
"Moe",
)
}
#[test]
fn proper_missing_param() -> TestResult {
fail_test(r#"def foo [x y z w] { }; foo a b c"#, "missing w")
}
#[test]
fn block_arity_check1() -> TestResult {
fail_test(r#"ls | each { |x, y| 1}"#, "expected 1 closure parameter")
}
// deprecating former support for escapes like `/uNNNN`, dropping test.
#[test]
fn string_escape_unicode_extended() -> TestResult {
run_test(r#""\u{015B}\u{1f10b}""#, "ś🄋")
}
#[test]
fn string_escape_interpolation() -> TestResult {
run_test(r#"$"\u{015B}(char hamburger)abc""#, "ś≡abc")
}
#[test]
fn string_escape_interpolation2() -> TestResult {
run_test(r#"$"2 + 2 is \(2 + 2)""#, "2 + 2 is (2 + 2)")
}
#[test]
fn proper_rest_types() -> TestResult {
run_test(
r#"def foo [--verbose(-v), # my test flag
...rest: int # my rest comment
] { if $verbose { print "verbose!" } else { print "not verbose!" } }; foo"#,
"not verbose!",
)
}
#[test]
fn single_value_row_condition() -> TestResult {
run_test(
r#"[[a, b]; [true, false], [true, true]] | where a | length"#,
"2",
)
}
#[test]
fn row_condition_non_boolean() -> TestResult {
fail_test(r#"[1 2 3] | where 1"#, "expected bool")
}
#[test]
fn performance_nested_lists() -> TestResult {
// Parser used to be exponential on deeply nested lists
// TODO: Add a timeout
fail_test(r#"[[[[[[[[[[[[[[[[[[[[[[[[[[[["#, "Unexpected end of code")
}
#[test]
fn performance_nested_modules() -> TestResult {
// Parser used to be exponential on deeply nested modules
// TODO: Add a timeout
fail_test(
r#"
module foo { module foo { module foo { module foo {
module foo { module foo { module foo { module foo {
module foo { module foo { module foo { module foo {
module foo { module foo { module foo { module foo {
module foo { module foo { module foo { module foo {
module foo { module foo { module foo { module foo {
module foo { module foo { module foo { module foo {
use bar.nu }}}}}}}}}}}}}}}}}}}}}}}}}}}}"#,
"module bar.nu not found",
)
}
#[test]
fn unary_not_1() -> TestResult {
run_test(r#"not false"#, "true")
}
#[test]
fn unary_not_2() -> TestResult {
run_test(r#"not (false)"#, "true")
}
#[test]
fn unary_not_3() -> TestResult {
run_test(r#"(not false)"#, "true")
}
#[test]
fn unary_not_4() -> TestResult {
run_test(r#"if not false { "hello" } else { "world" }"#, "hello")
}
#[test]
fn unary_not_5() -> TestResult {
run_test(
r#"if not not not not false { "hello" } else { "world" }"#,
"world",
)
}
#[test]
fn unary_not_6() -> TestResult {
run_test(
r#"[[name, present]; [abc, true], [def, false]] | where not present | get name.0"#,
"def",
)
}
#[test]
fn comment_in_multiple_pipelines() -> TestResult {
run_test(
r#"[[name, present]; [abc, true], [def, false]]
# | where not present
| get name.0"#,
"abc",
)
}
#[test]
fn date_literal() -> TestResult {
run_test(r#"2022-09-10 | into record | get day"#, "10")
}
#[test]
fn and_and_or() -> TestResult {
run_test(r#"true and false or true"#, "true")
}
#[test]
fn and_and_xor() -> TestResult {
// Assumes the precedence NOT > AND > XOR > OR
run_test(r#"true and true xor true and false"#, "true")
}
#[test]
fn or_and_xor() -> TestResult {
// Assumes the precedence NOT > AND > XOR > OR
run_test(r#"true or false xor true or false"#, "true")
}
#[test]
fn unbalanced_delimiter() -> TestResult {
fail_test(r#"{a:{b:5}}}"#, "unbalanced { and }")
}
#[test]
fn unbalanced_delimiter2() -> TestResult {
fail_test(r#"{}#.}"#, "unbalanced { and }")
}
#[test]
fn unbalanced_delimiter3() -> TestResult {
fail_test(r#"{"#, "Unexpected end of code")
}
#[test]
fn unbalanced_delimiter4() -> TestResult {
fail_test(r#"}"#, "unbalanced { and }")
}
#[test]
fn unbalanced_parens1() -> TestResult {
fail_test(r#")"#, "unbalanced ( and )")
}
#[test]
fn unbalanced_parens2() -> TestResult {
fail_test(r#"("("))"#, "unbalanced ( and )")
}
#[cfg(feature = "plugin")]
mod plugin_tests {
use super::*;
#[test]
fn plugin_use_with_string_literal() -> TestResult {
fail_test(
r#"plugin use 'nu-plugin-math'"#,
"Plugin registry file not set",
)
}
#[test]
fn plugin_use_with_string_constant() -> TestResult {
let input = "\
const file = 'nu-plugin-math'
plugin use $file
";
// should not fail with `not a constant`
fail_test(input, "Plugin registry file not set")
}
#[test]
fn plugin_use_with_string_variable() -> TestResult {
let input = "\
let file = 'nu-plugin-math'
plugin use $file
";
fail_test(input, "Value is not a parse-time constant")
}
#[test]
fn plugin_use_with_non_string_constant() -> TestResult {
let input = "\
const file = 6
plugin use $file
";
fail_test(input, "expected string, found int")
}
}
#[test]
fn extern_errors_with_no_space_between_params_and_name_1() -> TestResult {
fail_test("extern cmd[]", "expected space")
}
#[test]
fn extern_errors_with_no_space_between_params_and_name_2() -> TestResult {
fail_test("extern cmd(--flag)", "expected space")
}
#[test]
fn duration_with_underscores_1() -> TestResult {
run_test("420_min", "7hr")
}
#[test]
fn duration_with_underscores_2() -> TestResult {
run_test("1_000_000sec", "1wk 4day 13hr 46min 40sec")
}
#[test]
fn duration_with_underscores_3() -> TestResult {
fail_test("1_000_d_ay", "Command `1_000_d_ay` not found")
}
#[test]
fn duration_with_faulty_number() -> TestResult {
fail_test("sleep 4-ms", "duration value must be a number")
}
#[test]
fn filesize_with_underscores_1() -> TestResult {
run_test("420_MB", "420.0 MB")
}
#[test]
fn filesize_with_underscores_2() -> TestResult {
run_test("1_000_000B", "1.0 MB")
}
#[test]
fn filesize_with_underscores_3() -> TestResult {
fail_test("42m_b", "Command `42m_b` not found")
}
#[test]
fn filesize_is_not_hex() -> TestResult {
run_test("0x42b", "1067")
}
#[test]
fn let_variable_type_mismatch() -> TestResult {
fail_test(r#"let x: int = "foo""#, "expected int, found string")
}
#[test]
fn let_variable_table_runtime_cast() -> TestResult {
let outcome = nu!(
experimental: vec!["enforce-runtime-annotations".to_string()],
r#"let x: table = ([[a]; [1]] | to nuon | from nuon); $x | describe"#,
);
// Type::Any should be accepted by compatible types (record can convert to table)
assert!(outcome.out.contains("table<a: int>"));
Ok(())
}
#[test]
fn let_variable_table_runtime_mismatch() -> TestResult {
let outcome = nu!(
experimental: vec!["enforce-runtime-annotations".to_string()],
r#"mut x: table<b: int> = ([[b]; [1]] | to nuon | from nuon); $x = [[a]; [1]]"#,
);
// This conversion should fail due to a key mismatch
assert!(
outcome
.err
.contains("does not operate between 'table<b: int>' and 'table<a: int>'")
);
Ok(())
}
#[test]
fn mut_variable_table_runtime_mismatch() -> TestResult {
let outcome = nu!(
experimental: vec!["enforce-runtime-annotations".to_string()],
r#"mut x: table<b: int> = ([[b]; [1]] | to nuon | from nuon); $x = [[a]; [1]]"#,
);
assert!(
outcome
.err
.contains("does not operate between 'table<b: int>' and 'table<a: int>'")
);
Ok(())
}
#[test]
fn let_variable_record_runtime_cast() -> TestResult {
let outcome = nu!(
experimental: vec!["enforce-runtime-annotations".to_string()],
r#"let x: record<a: int> = ({a: 1} | to nuon | from nuon); $x | describe"#,
);
// Records from Type::Any sources should be convertible to tables when field types match
assert!(outcome.out.contains("record<a: int>"));
Ok(())
}
#[test]
fn let_variable_record_runtime_mismatch() -> TestResult {
let outcome = nu!(
experimental: vec!["enforce-runtime-annotations".to_string()],
r#"let x: record<b: int> = ({a: 1} | to nuon | from nuon); $x | describe"#,
);
// This conversion should fail due to a key mismatch
assert!(
outcome
.err
.contains("can't convert record<a: int> to record<b: int>")
);
Ok(())
}
#[test]
fn let_variable_disallows_completer() -> TestResult {
fail_test(
r#"let x: int@completer = 42"#,
"Unexpected custom completer",
)
}
#[test]
fn def_with_input_output() -> TestResult {
run_test(r#"def foo []: nothing -> int { 3 }; foo"#, "3")
}
#[test]
fn def_with_input_output_with_line_breaks() -> TestResult {
run_test(
r#"def foo []: [
nothing -> int
] { 3 }; foo"#,
"3",
)
}
#[test]
fn def_with_multi_input_output_with_line_breaks() -> TestResult {
run_test(
r#"def foo []: [
nothing -> int
string -> int
] { 3 }; foo"#,
"3",
)
}
#[test]
fn def_with_multi_input_output_without_commas() -> TestResult {
run_test(
r#"def foo []: [nothing -> int string -> int] { 3 }; foo"#,
"3",
)
}
#[test]
fn def_with_multi_input_output_called_with_first_sig() -> TestResult {
run_test(
r#"def foo []: [int -> int, string -> int] { 3 }; 10 | foo"#,
"3",
)
}
#[test]
fn def_with_multi_input_output_called_with_second_sig() -> TestResult {
run_test(
r#"def foo []: [int -> int, string -> int] { 3 }; "bob" | foo"#,
"3",
)
}
#[test]
fn def_with_input_output_mismatch_1() -> TestResult {
fail_test(
r#"def foo []: [int -> int, string -> int] { 3 }; foo"#,
"command doesn't support",
)
}
#[test]
fn def_with_input_output_mismatch_2() -> TestResult {
fail_test(
r#"def foo []: [int -> int, string -> int] { 3 }; {x: 2} | foo"#,
"command doesn't support",
)
}
#[test]
fn def_with_input_output_broken_1() -> TestResult {
fail_test(r#"def foo []: int { 3 }"#, "expected arrow")
}
#[test]
fn def_with_input_output_broken_2() -> TestResult {
fail_test(r#"def foo []: int -> { 3 }"#, "expected type")
}
#[test]
fn def_with_input_output_broken_3() -> TestResult {
fail_test(
r#"def foo []: int -> int@completer {}"#,
"Unexpected custom completer",
)
}
#[test]
fn def_with_input_output_broken_4() -> TestResult {
fail_test(
r#"def foo []: int -> list<int@completer> {}"#,
"Unexpected custom completer",
)
}
#[test]
fn def_with_in_var_let_1() -> TestResult {
run_test(
r#"def foo []: [int -> int, string -> int] { let x = $in; if ($x | describe) == "int" { 3 } else { 4 } }; "100" | foo"#,
"4",
)
}
#[test]
fn def_with_in_var_let_2() -> TestResult {
run_test(
r#"def foo []: [int -> int, string -> int] { let x = $in; if ($x | describe) == "int" { 3 } else { 4 } }; 100 | foo"#,
"3",
)
}
#[test]
fn def_with_in_var_mut_1() -> TestResult {
run_test(
r#"def foo []: [int -> int, string -> int] { mut x = $in; if ($x | describe) == "int" { 3 } else { 4 } }; "100" | foo"#,
"4",
)
}
#[test]
fn def_with_in_var_mut_2() -> TestResult {
run_test(
r#"def foo []: [int -> int, string -> int] { mut x = $in; if ($x | describe) == "int" { 3 } else { 4 } }; 100 | foo"#,
"3",
)
}
#[test]
fn properly_nest_captures() -> TestResult {
run_test(r#"do { let b = 3; def c [] { $b }; c }"#, "3")
}
#[test]
fn properly_nest_captures_call_first() -> TestResult {
run_test(r#"do { let b = 3; c; def c [] { $b }; c }"#, "3")
}
#[test]
fn properly_typecheck_rest_param() -> TestResult {
run_test(
r#"def foo [...rest: string] { $rest | length }; foo "a" "b" "c""#,
"3",
)
}
#[test]
fn implied_collect_has_compatible_type() -> TestResult {
run_test(r#"let idx = 3 | $in; $idx < 1"#, "false")
}
#[test]
fn record_expected_colon() -> TestResult {
fail_test(r#"{ a: 2 b }"#, "expected ':'")?;
fail_test(r#"{ a: 2 b 3 }"#, "expected ':'")
}
#[test]
fn record_missing_value() -> TestResult {
fail_test(r#"{ a: 2 b: }"#, "expected value for record field")
}
#[test]
fn def_requires_body_closure() -> TestResult {
fail_test("def a [] (echo 4)", "expected definition body closure")
}
#[test]
fn not_panic_with_recursive_call() {
let result = nu!(nu_repl_code(&[
"def px [] { if true { 3 } else { px } }",
"let x = 1",
"$x | px",
]));
assert_eq!(result.out, "3");
let result = nu!(nu_repl_code(&[
"def px [n=0] { let l = $in; if $n == 0 { return false } else { $l | px ($n - 1) } }",
"let x = 1",
"$x | px"
]));
assert_eq!(result.out, "false");
let result = nu!(nu_repl_code(&[
"def px [n=0] { let l = $in; if $n == 0 { return false } else { $l | px ($n - 1) } }",
"let x = 1",
"def foo [] { $x }",
"foo | px"
]));
assert_eq!(result.out, "false");
let result = nu!(nu_repl_code(&[
"def px [n=0] { let l = $in; if $n == 0 { return false } else { $l | px ($n - 1) } }",
"let x = 1",
"do {|| $x } | px"
]));
assert_eq!(result.out, "false");
let result = nu!(
cwd: "tests/parsing/samples",
"nu recursive_func_with_alias.nu"
);
assert!(result.status.success());
}
// https://github.com/nushell/nushell/issues/16040
#[test]
fn external_argument_with_subexpressions() -> TestResult {
run_test(r#"^echo foo( ('bar') | $in ++ 'baz' )"#, "foobarbaz")?;
run_test(r#"^echo foo( 'bar' )('baz')"#, "foobarbaz")?;
run_test(r#"^echo ")('foo')(""#, ")('foo')(")?;
fail_test(r#"^echo foo( 'bar'"#, "Unexpected end of code")
}
// https://github.com/nushell/nushell/issues/16332
#[test]
fn quote_escape_but_not_env_shorthand() -> TestResult {
run_test(r#""\"=foo""#, "\"=foo")
}
// https://github.com/nushell/nushell/issues/16586
#[test]
fn redefine_def_should_not_panic() -> TestResult {
fail_test(r#"def def (=a|s)>"#, "Unclosed delimiter")
}
#[test]
fn table_literal_column_var() -> TestResult {
run_test(
r#"
let column_name = 'column0'
let tbl = [[ $column_name column1 ]; [ foo bar ] [ baz car ] [ far fit ]]
$tbl.column0.0
"#,
"foo",
)
}
#[test]
fn table_literal_column_var_parse_err() -> TestResult {
fail_test(
r#"
let column_name = {a: 123}
let tbl = [[ $column_name column1 ]; [ foo bar ] [ baz car ] [ far fit ]]
$tbl.column0.0
"#,
"must be a string",
)
}
#[test]
fn table_literal_column_var_shell_err() -> TestResult {
fail_test(
r#"
let column_name = echo {a: 123}
let tbl = [[ $column_name column1 ]; [ foo bar ] [ baz car ] [ far fit ]]
$tbl.column0.0
"#,
"can't convert",
)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/repl/mod.rs | tests/repl/mod.rs | mod test_bits;
mod test_cell_path;
mod test_commandline;
mod test_conditionals;
mod test_config;
mod test_config_path;
mod test_converters;
mod test_custom_commands;
mod test_engine;
mod test_env;
mod test_help;
mod test_hiding;
mod test_ide;
mod test_iteration;
mod test_known_external;
mod test_math;
mod test_modules;
mod test_parser;
mod test_ranges;
mod test_regex;
mod test_signatures;
mod test_spread;
mod test_stdlib;
mod test_strings;
mod test_table_operations;
mod test_type_check;
mod tests;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/repl/test_ide.rs | tests/repl/test_ide.rs | use crate::repl::tests::{TestResult, test_ide_contains};
#[test]
fn parser_recovers() -> TestResult {
test_ide_contains(
"3 + \"bob\"\nlet x = \"fred\"\n",
&["--ide-check 5"],
"\"typename\":\"string\"",
)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/repl/test_table_operations.rs | tests/repl/test_table_operations.rs | use crate::repl::tests::{TestResult, fail_test, run_test};
#[test]
fn illegal_column_duplication() -> TestResult {
fail_test("[[lang, lang]; [nu, 100]]", "column_defined_twice")
}
#[test]
fn cell_path_subexpr1() -> TestResult {
run_test("([[lang, gems]; [nu, 100]]).lang | get 0", "nu")
}
#[test]
fn cell_path_subexpr2() -> TestResult {
run_test("([[lang, gems]; [nu, 100]]).lang.0", "nu")
}
#[test]
fn cell_path_var1() -> TestResult {
run_test("let x = [[lang, gems]; [nu, 100]]; $x.lang | get 0", "nu")
}
#[test]
fn cell_path_var2() -> TestResult {
run_test("let x = [[lang, gems]; [nu, 100]]; $x.lang.0", "nu")
}
#[test]
fn flatten_simple_list() -> TestResult {
run_test(
"[[N, u, s, h, e, l, l]] | flatten | str join (char nl)",
"N\nu\ns\nh\ne\nl\nl",
)
}
#[test]
fn flatten_get_simple_list() -> TestResult {
run_test("[[N, u, s, h, e, l, l]] | flatten | get 0", "N")
}
#[test]
fn flatten_table_get() -> TestResult {
run_test(
"[[origin, people]; [Ecuador, ([[name, meal]; ['Andres', 'arepa']])]] | flatten --all | get meal.0",
"arepa",
)
}
#[test]
fn flatten_table_column_get_last() -> TestResult {
run_test(
"[[origin, crate, versions]; [World, ([[name]; ['nu-cli']]), ['0.21', '0.22']]] | flatten versions --all | last | get versions",
"0.22",
)
}
#[test]
fn flatten_should_just_flatten_one_level() -> TestResult {
run_test(
"[[origin, crate, versions]; [World, ([[name]; ['nu-cli']]), ['0.21', '0.22']]] | flatten crate | get crate.name.0",
"nu-cli",
)
}
#[test]
fn flatten_nest_table_when_all_provided() -> TestResult {
run_test(
"[[origin, crate, versions]; [World, ([[name]; ['nu-cli']]), ['0.21', '0.22']]] | flatten crate --all | get name.0",
"nu-cli",
)
}
#[test]
fn get_table_columns_1() -> TestResult {
run_test(
"[[name, age, grade]; [paul,21,a]] | columns | first",
"name",
)
}
#[test]
fn get_table_columns_2() -> TestResult {
run_test("[[name, age, grade]; [paul,21,a]] | columns | get 1", "age")
}
#[test]
fn flatten_should_flatten_inner_table() -> TestResult {
run_test(
"[[[name, value]; [abc, 123]]] | flatten --all | get value.0",
"123",
)
}
#[test]
fn command_filter_reject_1() -> TestResult {
run_test(
"[[lang, gems]; [nu, 100]] | reject gems | to json",
r#"[
{
"lang": "nu"
}
]"#,
)
}
#[test]
fn command_filter_reject_2() -> TestResult {
run_test(
"[[lang, gems, grade]; [nu, 100, a]] | reject gems grade | to json",
r#"[
{
"lang": "nu"
}
]"#,
)
}
#[test]
fn command_filter_reject_3() -> TestResult {
run_test(
"[[lang, gems, grade]; [nu, 100, a]] | reject grade gems | to json",
r#"[
{
"lang": "nu"
}
]"#,
)
}
#[test]
#[rustfmt::skip]
fn command_filter_reject_4() -> TestResult {
run_test(
"[[lang, gems, grade]; [nu, 100, a]] | reject gems | to json -r",
r#"[{"lang":"nu","grade":"a"}]"#,
)
}
#[test]
fn command_drop_column_1() -> TestResult {
run_test(
"[[lang, gems, grade]; [nu, 100, a]] | drop column 2 | to json",
r#"[
{
"lang": "nu"
}
]"#,
)
}
#[test]
fn record_1() -> TestResult {
run_test(r#"{'a': 'b'} | get a"#, "b")
}
#[test]
fn record_2() -> TestResult {
run_test(r#"{'b': 'c'}.b"#, "c")
}
#[test]
fn where_on_ranges() -> TestResult {
run_test(r#"1..10 | where $it > 8 | math sum"#, "19")
}
#[test]
fn index_on_list() -> TestResult {
run_test(r#"[1, 2, 3].1"#, "2")
}
#[test]
fn update_cell_path_1() -> TestResult {
run_test(
r#"[[name, size]; [a, 1.1]] | into int size | get size.0"#,
"1",
)
}
#[test]
fn missing_column_errors() -> TestResult {
fail_test(
r#"[ { name: ABC, size: 20 }, { name: HIJ } ].size.1 == null"#,
"cannot find column",
)
}
#[test]
fn missing_optional_column_fills_in_nothing() -> TestResult {
// The empty value will be replaced with null because of the ?
run_test(
r#"[ { name: ABC, size: 20 }, { name: HIJ } ].size?.1 == null"#,
"true",
)
}
#[test]
fn missing_required_row_fails() -> TestResult {
// .3 will fail if there is no 3rd row
fail_test(
r#"[ { name: ABC, size: 20 }, { name: HIJ } ].3"#,
"", // we just care if it errors
)
}
#[test]
fn missing_optional_row_fills_in_nothing() -> TestResult {
// ?.3 will return null if there is no 3rd row
run_test(
r#"[ { name: ABC, size: 20 }, { name: HIJ } ].3? == null"#,
"true",
)
}
#[test]
fn string_cell_path() -> TestResult {
run_test(
r#"let x = "name"; [["name", "score"]; [a, b], [c, d]] | get $x | get 1"#,
"c",
)
}
#[test]
fn split_row() -> TestResult {
run_test(r#""hello world" | split row " " | get 1"#, "world")
}
#[test]
fn split_column() -> TestResult {
run_test(
r#""hello world" | split column " " | get "column0".0"#,
"hello",
)
}
#[test]
fn wrap() -> TestResult {
run_test(r#"([1, 2, 3] | wrap foo).foo.1"#, "2")
}
#[test]
fn get() -> TestResult {
run_test(
r#"[[name, grade]; [Alice, A], [Betty, B]] | get grade.1"#,
"B",
)
}
#[test]
fn select_1() -> TestResult {
run_test(
r#"([[name, age]; [a, 1], [b, 2]]) | select name | get 1 | get name"#,
"b",
)
}
#[test]
fn select_2() -> TestResult {
run_test(
r#"[[name, age]; [a, 1] [b, 2]] | get 1 | select age | get age"#,
"2",
)
}
#[test]
fn update_will_insert() -> TestResult {
run_test(r#"{} | upsert a b | get a"#, "b")
}
#[test]
fn length_for_columns() -> TestResult {
run_test(
r#"[[name,age,grade]; [bill,20,a] [a b c]] | columns | length"#,
"3",
)
}
#[test]
fn length_for_rows() -> TestResult {
run_test(r#"[[name,age,grade]; [bill,20,a] [a b c]] | length"#, "2")
}
#[test]
fn length_defaulted_columns() -> TestResult {
run_test(
r#"[[name, age]; [test, 10]] | default 11 age | get 0 | columns | length"#,
"2",
)
}
#[test]
fn nullify_errors() -> TestResult {
run_test("([{a:1} {a:2} {a:3}] | get foo? | length) == 3", "true")?;
run_test(
"([{a:1} {a:2} {a:3}] | get foo? | to nuon) == '[null, null, null]'",
"true",
)
}
#[test]
fn nullify_holes() -> TestResult {
run_test(
"([{a:1} {b:2} {a:3}] | get a? | to nuon) == '[1, null, 3]'",
"true",
)
}
#[test]
fn get_with_insensitive_cellpath() -> TestResult {
run_test(
r#"[[name, age]; [a, 1] [b, 2]] | get NAmE! | select 0 | get 0"#,
"a",
)
}
#[test]
fn ignore_case_flag() -> TestResult {
run_test(
r#"
[
[Origin, Crate, Versions];
[World, {Name: "nu-cli"}, ['0.21', '0.22']]
]
| get --ignore-case crate.name.0
"#,
"nu-cli",
)?;
run_test(
r#"
[
[Origin, Crate, Versions];
[World, {Name: "nu-cli"}, ['0.21', '0.22']]
]
| select --ignore-case origin
| to nuon --raw
"#,
r#"[[origin];[World]]"#,
)?;
run_test(
r#"{A: {B: 3, C: 5}} | reject --ignore-case a.b | to nuon --raw"#,
"{A:{C:5}}",
)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/repl/test_spread.rs | tests/repl/test_spread.rs | use crate::repl::tests::{TestResult, fail_test, run_test};
use nu_test_support::nu;
#[test]
fn spread_in_list() -> TestResult {
run_test(r#"[...[]] | to nuon"#, "[]").unwrap();
run_test(
r#"[1 2 ...[[3] {x: 1}] 5] | to nuon"#,
"[1, 2, [3], {x: 1}, 5]",
)
.unwrap();
run_test(
r#"[...("foo" | split chars) 10] | to nuon"#,
"[f, o, o, 10]",
)
.unwrap();
run_test(
r#"let l = [1, 2, [3]]; [...$l $l] | to nuon"#,
"[1, 2, [3], [1, 2, [3]]]",
)
.unwrap();
run_test(
r#"[ ...[ ...[ ...[ a ] b ] c ] d ] | to nuon"#,
"[a, b, c, d]",
)
}
#[test]
fn not_spread() -> TestResult {
run_test(r#"def ... [x] { $x }; ... ..."#, "...").unwrap();
run_test(
r#"let a = 4; [... $a ... [1] ... (5) ...bare ...] | to nuon"#,
r#"["...", 4, "...", [1], "...", 5, "...bare", "..."]"#,
)
}
#[test]
fn bad_spread_on_non_list() -> TestResult {
fail_test(r#"let x = 5; [...$x]"#, "cannot spread").unwrap();
fail_test(r#"[...({ x: 1 })]"#, "cannot spread")
}
#[test]
fn spread_type_list() -> TestResult {
run_test(
r#"def f [a: list<int>] { $a | describe }; f [1 ...[]]"#,
"list<int>",
)
.unwrap();
run_test(
r#"def f [a: list<int>] { $a | describe }; f [1 ...[2]]"#,
"list<int>",
)
.unwrap();
fail_test(
r#"def f [a: list<int>] { }; f ["foo" ...[4 5 6]]"#,
"expected int",
)
.unwrap();
fail_test(
r#"def f [a: list<int>] { }; f [1 2 ...["misfit"] 4]"#,
"expected int",
)
}
#[test]
fn spread_in_record() -> TestResult {
run_test(r#"{...{} ...{}, a: 1} | to nuon"#, "{a: 1}").unwrap();
run_test(r#"{...{...{...{}}}} | to nuon"#, "{}").unwrap();
run_test(
r#"{foo: bar ...{a: {x: 1}} b: 3} | to nuon"#,
"{foo: bar, a: {x: 1}, b: 3}",
)
}
#[test]
fn duplicate_cols() -> TestResult {
fail_test(r#"{a: 1, ...{a: 3}}"#, "column used twice").unwrap();
fail_test(r#"{...{a: 4, x: 3}, x: 1}"#, "column used twice").unwrap();
fail_test(r#"{...{a: 0, x: 2}, ...{x: 5}}"#, "column used twice")
}
#[test]
fn bad_spread_on_non_record() -> TestResult {
fail_test(r#"let x = 5; { ...$x }"#, "cannot spread").unwrap();
fail_test(r#"{...([1, 2])}"#, "cannot spread")
}
#[test]
fn spread_type_record() -> TestResult {
run_test(
r#"def f [a: record<x: int>] { $a.x }; f { ...{x: 0} }"#,
"0",
)
.unwrap();
fail_test(
r#"def f [a: record<x: int>] {}; f { ...{x: "not an int"} }"#,
"type_mismatch",
)
}
#[test]
fn spread_external_args() {
assert_eq!(
nu!(r#"nu --testbin cococo ...[1 "foo"] 2 ...[3 "bar"]"#).out,
"1 foo 2 3 bar",
);
// exec doesn't have rest parameters but allows unknown arguments
assert_eq!(
nu!(r#"exec nu --testbin cococo "foo" ...[5 6]"#).out,
"foo 5 6"
);
}
#[test]
fn spread_internal_args() -> TestResult {
run_test(
r#"
let list = ["foo" 4]
def f [a b c? d? ...x] { [$a $b $c $d $x] | to nuon }
f 1 2 ...[5 6] 7 ...$list"#,
"[1, 2, null, null, [5, 6, 7, foo, 4]]",
)
.unwrap();
run_test(
r#"
def f [a b c? d? ...x] { [$a $b $c $d $x] | to nuon }
f 1 2 3 ...[5 6]"#,
"[1, 2, 3, null, [5, 6]]",
)
.unwrap();
run_test(
r#"
def f [--flag: int ...x] { [$flag $x] | to nuon }
f 2 ...[foo] 4 --flag 5 6 ...[7 8]"#,
"[5, [2, foo, 4, 6, 7, 8]]",
)
.unwrap();
run_test(
r#"
def f [a b? --flag: int ...x] { [$a $b $flag $x] | to nuon }
f 1 ...[foo] 4 --flag 5 6 ...[7 8]"#,
"[1, null, 5, [foo, 4, 6, 7, 8]]",
)
}
#[test]
fn bad_spread_internal_args() -> TestResult {
fail_test(
r#"
def f [a b c? d? ...x] { echo $a $b $c $d $x }
f 1 ...[5 6]"#,
"Missing required positional argument",
)
.unwrap();
fail_test(
r#"
def f [a b?] { echo a b c d }
f ...[5 6]"#,
"unexpected spread argument",
)
}
#[test]
fn spread_non_list_args() {
fail_test(r#"echo ...(1)"#, "cannot spread value").unwrap();
assert!(
nu!(r#"nu --testbin cococo ...(1)"#)
.err
.contains("cannot spread value")
);
}
#[test]
fn spread_args_type() -> TestResult {
fail_test(r#"def f [...x: int] {}; f ...["abc"]"#, "expected int")
}
#[test]
fn explain_spread_args() -> TestResult {
run_test(
r#"(explain { || echo ...[1 2] }).cmd_args.0 | select arg_type name type | to nuon"#,
r#"[[arg_type, name, type]; [spread, "[1 2]", list<int>]]"#,
)
}
#[test]
fn disallow_implicit_spread_for_externals() -> TestResult {
fail_test(r#"^echo [1 2]"#, "Lists are not automatically spread")
}
#[test]
fn respect_shape() -> TestResult {
fail_test(
"def foo [...rest] { ...$rest }; foo bar baz",
"Command `...$rest` not found",
)
.unwrap();
fail_test("module foo { ...$bar }", "expected_keyword").unwrap();
run_test(r#"def "...$foo" [] {2}; do { ...$foo }"#, "2").unwrap();
run_test(r#"match "...$foo" { ...$foo => 5 }"#, "5")
}
#[test]
fn spread_null() -> TestResult {
// Spread in list
run_test(r#"[1, 2, ...(null)] | to nuon --raw"#, r#"[1,2]"#)?;
// Spread in record
run_test(r#"{a: 1, b: 2, ...(null)} | to nuon --raw"#, r#"{a:1,b:2}"#)?;
// Spread to built-in command's ...rest
run_test(r#"echo 1 2 ...(null) | to nuon --raw"#, r#"[1,2]"#)?;
// Spread to custom command's ...rest
run_test(
r#"
def foo [...rest] { $rest }
foo ...(null) 1 2 ...(null) 3 | to nuon --raw
"#,
r#"[1,2,3]"#,
)?;
// Spread to external command's arguments
assert_eq!(nu!(r#"nu --testbin cococo 1 ...(null) 2"#).out, "1 2");
Ok(())
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/repl/test_engine.rs | tests/repl/test_engine.rs | use crate::repl::tests::{TestResult, fail_test, run_test, run_test_contains};
use rstest::rstest;
#[test]
fn concrete_variable_assignment() -> TestResult {
run_test(
"let x = (1..100 | each { |y| $y + 100 }); let y = ($x | length); $x | length",
"100",
)
}
#[test]
fn proper_shadow() -> TestResult {
run_test("let x = 10; let x = $x + 9; $x", "19")
}
#[test]
fn in_variable_1() -> TestResult {
run_test(r#"[3] | if $in.0 > 4 { "yay!" } else { "boo" }"#, "boo")
}
#[test]
fn in_variable_2() -> TestResult {
run_test(r#"3 | if $in > 2 { "yay!" } else { "boo" }"#, "yay!")
}
#[test]
fn in_variable_3() -> TestResult {
run_test(r#"3 | if $in > 4 { "yay!" } else { $in }"#, "3")
}
#[test]
fn in_variable_4() -> TestResult {
run_test(r#"3 | do { $in }"#, "3")
}
#[test]
fn in_variable_5() -> TestResult {
run_test(r#"3 | if $in > 2 { $in - 10 } else { $in * 10 }"#, "-7")
}
#[test]
fn in_variable_6() -> TestResult {
run_test(r#"3 | if $in > 6 { $in - 10 } else { $in * 10 }"#, "30")
}
#[test]
fn in_and_if_else() -> TestResult {
run_test(
r#"[1, 2, 3] | if false {} else if true { $in | length }"#,
"3",
)
}
#[test]
fn in_with_closure() -> TestResult {
// Can use $in twice
run_test(r#"3 | do { let x = $in; let y = $in; $x + $y }"#, "6")
}
#[test]
fn in_with_custom_command() -> TestResult {
// Can use $in twice
run_test(
r#"def foo [] { let x = $in; let y = $in; $x + $y }; 3 | foo"#,
"6",
)
}
#[test]
fn in_used_twice_and_also_in_pipeline() -> TestResult {
run_test(
r#"3 | do { let x = $in; let y = $in; $x + $y | $in * 4 }"#,
"24",
)
}
// #13441
#[test]
fn in_used_in_range_from() -> TestResult {
run_test(r#"6 | $in..10 | math sum"#, "40")
}
#[test]
fn in_used_in_range_to() -> TestResult {
run_test(r#"6 | 3..$in | math sum"#, "18")
}
#[test]
fn help_works_with_missing_requirements() -> TestResult {
fail_test(r#"each"#, "missing_positional")?;
run_test_contains(r#"each --help"#, "Usage")
}
#[rstest]
#[case("let x = 3", "$x", "int", "3")]
#[case("const x = 3", "$x", "int", "3")]
fn scope_variable(
#[case] var_decl: &str,
#[case] exp_name: &str,
#[case] exp_type: &str,
#[case] exp_value: &str,
) -> TestResult {
let get_var_info =
format!(r#"{var_decl}; scope variables | where name == "{exp_name}" | first"#);
run_test(&format!(r#"{get_var_info} | get type"#), exp_type)?;
run_test(&format!(r#"{get_var_info} | get value"#), exp_value)
}
#[rstest]
#[case("a", "<> nothing")]
#[case("b", "<1.23> float")]
#[case("flag1", "<> nothing")]
#[case("flag2", "<4.56> float")]
fn scope_command_defaults(#[case] var: &str, #[case] exp_result: &str) -> TestResult {
run_test(
&format!(
r#"def t1 [a:int b?:float=1.23 --flag1:string --flag2:float=4.56] {{ true }};
let rslt = (scope commands | where name == 't1' | get signatures.0.any | where parameter_name == '{var}' | get parameter_default.0);
$"<($rslt)> ($rslt | describe)""#
),
exp_result,
)
}
#[test]
fn earlier_errors() -> TestResult {
fail_test(
r#"[1, "bob"] | each { |it| $it + 3 } | each { |it| $it / $it } | table"#,
"int",
)
}
#[test]
fn missing_flags_are_nothing() -> TestResult {
run_test(
r#"def foo [--aaa(-a): int, --bbb(-b): int] { (if $aaa == null { 10 } else { $aaa }) + (if $bbb == null { 100 } else { $bbb }) }; foo"#,
"110",
)
}
#[test]
fn missing_flags_are_nothing2() -> TestResult {
run_test(
r#"def foo [--aaa(-a): int, --bbb(-b): int] { (if $aaa == null { 10 } else { $aaa }) + (if $bbb == null { 100 } else { $bbb }) }; foo -a 90"#,
"190",
)
}
#[test]
fn missing_flags_are_nothing3() -> TestResult {
run_test(
r#"def foo [--aaa(-a): int, --bbb(-b): int] { (if $aaa == null { 10 } else { $aaa }) + (if $bbb == null { 100 } else { $bbb }) }; foo -b 45"#,
"55",
)
}
#[test]
fn missing_flags_are_nothing4() -> TestResult {
run_test(
r#"def foo [--aaa(-a): int, --bbb(-b): int] { (if $aaa == null { 10 } else { $aaa }) + (if $bbb == null { 100 } else { $bbb }) }; foo -a 3 -b 10000"#,
"10003",
)
}
#[test]
fn proper_variable_captures() -> TestResult {
run_test(
r#"def foo [x] { let y = 100; { || $y + $x } }; do (foo 23)"#,
"123",
)
}
#[test]
fn proper_variable_captures_with_calls() -> TestResult {
run_test(
r#"def foo [] { let y = 60; def bar [] { $y }; {|| bar } }; do (foo)"#,
"60",
)
}
#[test]
fn proper_variable_captures_with_nesting() -> TestResult {
run_test(
r#"def foo [x] { let z = 100; def bar [y] { $y - $x + $z } ; { |z| bar $z } }; do (foo 11) 13"#,
"102",
)
}
#[test]
fn divide_duration() -> TestResult {
run_test(r#"4ms / 4ms"#, "1.0")
}
#[test]
fn divide_filesize() -> TestResult {
run_test(r#"4mb / 4mb"#, "1.0")
}
#[test]
fn date_comparison() -> TestResult {
run_test(r#"(date now) < ((date now) + 2min)"#, "true")
}
#[test]
fn let_sees_input() -> TestResult {
run_test(
r#"def c [] { let x = (str length); $x }; "hello world" | c"#,
"11",
)
}
#[test]
fn let_sees_in_variable() -> TestResult {
run_test(
r#"def c [] { let x = $in.name; $x | str length }; {name: bob, size: 100 } | c"#,
"3",
)
}
#[test]
fn let_sees_in_variable2() -> TestResult {
run_test(
r#"def c [] { let x = ($in | str length); $x }; 'bob' | c"#,
"3",
)
}
#[test]
fn def_env() -> TestResult {
run_test(
r#"def --env bob [] { $env.BAR = "BAZ" }; bob; $env.BAR"#,
"BAZ",
)
}
#[test]
fn not_def_env() -> TestResult {
fail_test(r#"def bob [] { $env.BAR = "BAZ" }; bob; $env.BAR"#, "")
}
#[test]
fn def_env_hiding_something() -> TestResult {
fail_test(
r#"$env.FOO = "foo"; def --env bob [] { hide-env FOO }; bob; $env.FOO"#,
"",
)
}
#[test]
fn def_env_then_hide() -> TestResult {
fail_test(
r#"def --env bob [] { $env.BOB = "bob" }; def --env un-bob [] { hide-env BOB }; bob; un-bob; $env.BOB"#,
"",
)
}
#[test]
fn export_def_env() -> TestResult {
run_test(
r#"module foo { export def --env bob [] { $env.BAR = "BAZ" } }; use foo bob; bob; $env.BAR"#,
"BAZ",
)
}
#[test]
fn dynamic_load_env() -> TestResult {
run_test(r#"let x = "FOO"; load-env {$x: "BAZ"}; $env.FOO"#, "BAZ")
}
#[test]
fn reduce_spans() -> TestResult {
fail_test(
r#"let x = ([1, 2, 3] | reduce --fold 0 { $it.item + 2 * $it.acc }); error make {msg: "oh that hurts", label: {text: "right here", start: (metadata $x).span.start, end: (metadata $x).span.end } }"#,
"right here",
)
}
#[test]
fn with_env_shorthand_nested_quotes() -> TestResult {
run_test(
r#"FOO='-arg "hello world"' echo $env | get FOO"#,
"-arg \"hello world\"",
)
}
#[test]
fn test_redirection_stderr() -> TestResult {
// try a nonsense binary
run_test(r#"do -i { asdjw4j5cnaabw44rd }; echo done"#, "done")
}
#[test]
fn datetime_literal() -> TestResult {
run_test(r#"(date now) - 2019-08-23 > 1hr"#, "true")
}
#[test]
fn shortcircuiting_and() -> TestResult {
run_test(r#"false and (5 / 0; false)"#, "false")
}
#[test]
fn shortcircuiting_or() -> TestResult {
run_test(r#"true or (5 / 0; false)"#, "true")
}
#[test]
fn nonshortcircuiting_xor() -> TestResult {
run_test(r#"true xor (print "hello"; false) | ignore"#, "hello")
}
#[test]
fn open_ended_range() -> TestResult {
run_test(r#"1.. | first 100000 | length"#, "100000")
}
#[test]
fn default_value1() -> TestResult {
run_test(r#"def foo [x = 3] { $x }; foo"#, "3")
}
#[test]
fn default_value2() -> TestResult {
run_test(r#"def foo [x: int = 3] { $x }; foo"#, "3")
}
#[test]
fn default_value3() -> TestResult {
run_test(r#"def foo [--x = 3] { $x }; foo"#, "3")
}
#[test]
fn default_value4() -> TestResult {
run_test(r#"def foo [--x: int = 3] { $x }; foo"#, "3")
}
#[test]
fn default_value5() -> TestResult {
run_test(r#"def foo [x = 3] { $x }; foo 10"#, "10")
}
#[test]
fn default_value6() -> TestResult {
run_test(r#"def foo [x: int = 3] { $x }; foo 10"#, "10")
}
#[test]
fn default_value7() -> TestResult {
run_test(r#"def foo [--x = 3] { $x }; foo --x 10"#, "10")
}
#[test]
fn default_value8() -> TestResult {
run_test(r#"def foo [--x: int = 3] { $x }; foo --x 10"#, "10")
}
#[test]
fn default_value9() -> TestResult {
fail_test(r#"def foo [--x = 3] { $x }; foo --x a"#, "expected int")
}
#[test]
fn default_value10() -> TestResult {
fail_test(r#"def foo [x = 3] { $x }; foo a"#, "expected int")
}
#[test]
fn default_value11() -> TestResult {
fail_test(
r#"def foo [x = 3, y] { $x }; foo a"#,
"after optional parameter",
)
}
#[test]
fn default_value12() -> TestResult {
fail_test(
r#"def foo [--x:int = "a"] { $x }"#,
"expected default value to be `int`",
)
}
#[test]
fn default_value_constant1() -> TestResult {
run_test(r#"def foo [x = "foo"] { $x }; foo"#, "foo")
}
#[test]
fn default_value_constant2() -> TestResult {
run_test(r#"def foo [secs = 1sec] { $secs }; foo"#, "1sec")
}
#[test]
fn default_value_constant3() -> TestResult {
run_test(r#"def foo [x = ("foo" | str length)] { $x }; foo"#, "3")
}
#[test]
fn default_value_not_constant2() -> TestResult {
fail_test(
r#"def foo [x = (loop { break })] { $x }; foo"#,
"expected a constant",
)
}
#[test]
fn loose_each() -> TestResult {
run_test(
r#"[[1, 2, 3], [4, 5, 6]] | each {|| $in.1 } | math sum"#,
"7",
)
}
#[test]
fn in_means_input() -> TestResult {
run_test(r#"def shl [] { $in * 2 }; 2 | shl"#, "4")
}
#[test]
fn in_iteration() -> TestResult {
run_test(
r#"[3, 4, 5] | each {|| echo $"hi ($in)" } | str join"#,
"hi 3hi 4hi 5",
)
}
#[test]
fn reusable_in() -> TestResult {
run_test(
r#"[1, 2, 3, 4] | take (($in | length) - 1) | math sum"#,
"6",
)
}
#[test]
fn better_operator_spans() -> TestResult {
run_test(
r#"metadata ({foo: 10} | (20 - $in.foo)) | get span | $in.start < $in.end"#,
"true",
)
}
#[test]
fn call_rest_arg_span() -> TestResult {
run_test(
r#"let l = [2, 3]; def foo [...rest] { metadata $rest | view span $in.span.start $in.span.end }; foo 1 ...$l"#,
"1 ...$l",
)
}
#[test]
fn range_right_exclusive() -> TestResult {
run_test(r#"[1, 4, 5, 8, 9] | slice 1..<3 | math sum"#, "9")
}
/// Issue #7872
#[test]
fn assignment_to_in_var_no_panic() -> TestResult {
fail_test(r#"$in = 3"#, "needs to be a mutable variable")
}
#[test]
fn assignment_to_env_no_panic() -> TestResult {
fail_test(r#"$env = 3"#, "cannot_replace_env")
}
#[test]
fn short_flags() -> TestResult {
run_test(
r#"def foobar [-a: int, -b: string, -c: string] { echo $'($a) ($c) ($b)' }; foobar -b "balh balh" -a 1543 -c "FALSE123""#,
"1543 FALSE123 balh balh",
)
}
#[test]
fn short_flags_1() -> TestResult {
run_test(
r#"def foobar [-a: string, -b: string, -s: int] { if ( $s == 0 ) { echo $'($b)($a)' }}; foobar -a test -b case -s 0 "#,
"casetest",
)
}
#[test]
fn short_flags_2() -> TestResult {
run_test(
r#"def foobar [-a: int, -b: string, -c: int] { $a + $c };foobar -b "balh balh" -a 10 -c 1 "#,
"11",
)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/repl/test_config.rs | tests/repl/test_config.rs | use crate::repl::tests::{TestResult, fail_test, run_test, run_test_std};
#[test]
fn mutate_nu_config() -> TestResult {
run_test_std(
r#"$env.config.footer_mode = 30; $env.config.footer_mode"#,
"30",
)
}
#[test]
fn mutate_nu_config_nested_ls() -> TestResult {
run_test_std(
r#"$env.config.ls.clickable_links = false; $env.config.ls.clickable_links"#,
"false",
)
}
#[test]
fn mutate_nu_config_nested_table() -> TestResult {
run_test_std(
r#"
$env.config.table.trim.methodology = 'wrapping'
$env.config.table.trim.wrapping_try_keep_words = false
$env.config.table.trim.wrapping_try_keep_words
"#,
"false",
)
}
#[test]
fn mutate_nu_config_nested_menu() -> TestResult {
run_test_std(
r#"
$env.config.menus = [
{
name: menu
only_buffer_difference: true
marker: "M "
type: {}
style: {}
}
];
$env.config.menus.0.type.columns = 3;
$env.config.menus.0.type.columns
"#,
"3",
)
}
#[test]
fn mutate_nu_config_nested_keybindings() -> TestResult {
run_test_std(
r#"
$env.config.keybindings = [
{
name: completion_previous
modifier: shift
keycode: backtab
mode: [ vi_normal, vi_insert ]
event: { send: menuprevious }
}
];
$env.config.keybindings.0.keycode = 'char_x';
$env.config.keybindings.0.keycode
"#,
"char_x",
)
}
#[test]
fn mutate_nu_config_nested_color_nested() -> TestResult {
run_test_std(
r#"$env.config.color_config.shape_flag = 'cyan'; $env.config.color_config.shape_flag"#,
"cyan",
)
}
#[test]
fn mutate_nu_config_nested_completion() -> TestResult {
run_test_std(
r#"$env.config.completions.external.enable = false; $env.config.completions.external.enable"#,
"false",
)
}
#[test]
fn mutate_nu_config_nested_history() -> TestResult {
run_test_std(
r#"$env.config.history.max_size = 100; $env.config.history.max_size"#,
"100",
)
}
#[test]
fn mutate_nu_config_nested_filesize() -> TestResult {
run_test_std(
r#"$env.config.filesize.unit = 'kB'; $env.config.filesize.unit"#,
"kB",
)
}
#[test]
fn mutate_nu_config_plugin() -> TestResult {
run_test_std(
r#"
$env.config.plugins = {
config: {
key1: value
key2: other
}
};
$env.config.plugins.config.key1 = 'updated'
$env.config.plugins.config.key1
"#,
"updated",
)
}
#[test]
fn reject_nu_config_plugin_non_record() -> TestResult {
fail_test(r#"$env.config.plugins = 5"#, "Type mismatch")
}
#[test]
fn mutate_nu_config_plugin_gc_default_enabled() -> TestResult {
run_test(
r#"
$env.config.plugin_gc.default.enabled = false
$env.config.plugin_gc.default.enabled
"#,
"false",
)
}
#[test]
fn mutate_nu_config_plugin_gc_default_stop_after() -> TestResult {
run_test(
r#"
$env.config.plugin_gc.default.stop_after = 20sec
$env.config.plugin_gc.default.stop_after
"#,
"20sec",
)
}
#[test]
fn mutate_nu_config_plugin_gc_default_stop_after_negative() -> TestResult {
fail_test(
r#"
$env.config.plugin_gc.default.stop_after = -1sec
$env.config.plugin_gc.default.stop_after
"#,
"expected a non-negative duration",
)
}
#[test]
fn mutate_nu_config_plugin_gc_plugins() -> TestResult {
run_test(
r#"
$env.config.plugin_gc.plugins.inc = {
enabled: true
stop_after: 0sec
}
$env.config.plugin_gc.plugins.inc.stop_after
"#,
"0sec",
)
}
#[test]
fn mutate_nu_config_history_warning() -> TestResult {
fail_test(
r#"$env.config.history.file_format = "plaintext"; $env.config.history.isolation = true"#,
"history isolation only compatible with SQLite format",
)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/repl/test_custom_commands.rs | tests/repl/test_custom_commands.rs | use crate::repl::tests::{TestResult, fail_test, run_test, run_test_contains};
use nu_test_support::nu;
use pretty_assertions::assert_eq;
use rstest::rstest;
#[test]
fn no_scope_leak1() -> TestResult {
fail_test(
"if false { let $x = 10 } else { let $x = 20 }; $x",
"Variable not found",
)
}
#[test]
fn no_scope_leak2() -> TestResult {
fail_test(
"def foo [] { $x }; def bar [] { let $x = 10; foo }; bar",
"Variable not found",
)
}
#[test]
fn no_scope_leak3() -> TestResult {
run_test(
"def foo [$x] { $x }; def bar [] { let $x = 10; foo 20}; bar",
"20",
)
}
#[test]
fn no_scope_leak4() -> TestResult {
run_test(
"def foo [$x] { $x }; def bar [] { let $x = 10; (foo 20) + $x}; bar",
"30",
)
}
#[test]
fn custom_rest_var() -> TestResult {
run_test("def foo [...x] { $x.0 + $x.1 }; foo 10 80", "90")
}
#[test]
fn def_twice_should_fail() -> TestResult {
fail_test(
r#"def foo [] { "foo" }; def foo [] { "bar" }"#,
"defined more than once",
)
}
#[test]
fn missing_parameters() -> TestResult {
fail_test(r#"def foo {}"#, "expected [ or (")
}
#[test]
fn flag_param_value() -> TestResult {
run_test(
r#"def foo [--bob: int] { $bob + 100 }; foo --bob 55"#,
"155",
)
}
#[test]
fn do_rest_args() -> TestResult {
run_test(r#"(do { |...rest| $rest } 1 2).1 + 10"#, "12")
}
#[test]
fn custom_switch1() -> TestResult {
run_test(
r#"def florb [ --dry-run ] { if ($dry_run) { "foo" } else { "bar" } }; florb --dry-run"#,
"foo",
)
}
#[rstest]
fn custom_flag_with_type_checking(
#[values(
("int", "\"3\""),
("int", "null"),
("record<i: int>", "{i: \"\"}"),
("list<int>", "[\"\"]")
)]
type_sig_value: (&str, &str),
#[values("--dry-run", "-d")] flag: &str,
) -> TestResult {
let (type_sig, value) = type_sig_value;
fail_test(
&format!("def florb [{flag}: {type_sig}] {{}}; let y = {value}; florb {flag} $y"),
"type_mismatch",
)
}
#[test]
fn custom_switch2() -> TestResult {
run_test(
r#"def florb [ --dry-run ] { if ($dry_run) { "foo" } else { "bar" } }; florb"#,
"bar",
)
}
#[test]
fn custom_switch3() -> TestResult {
run_test(
r#"def florb [ --dry-run ] { $dry_run }; florb --dry-run=false"#,
"false",
)
}
#[test]
fn custom_switch4() -> TestResult {
run_test(
r#"def florb [ --dry-run ] { $dry_run }; florb --dry-run=true"#,
"true",
)
}
#[test]
fn custom_switch5() -> TestResult {
run_test(r#"def florb [ --dry-run ] { $dry_run }; florb"#, "false")
}
#[test]
fn custom_switch6() -> TestResult {
run_test(
r#"def florb [ --dry-run ] { $dry_run }; florb --dry-run"#,
"true",
)
}
#[test]
fn custom_flag1() -> TestResult {
run_test(
r#"def florb [
--age: int = 0
--name = "foobar"
] {
($age | into string) + $name
}
florb"#,
"0foobar",
)
}
#[test]
fn custom_flag2() -> TestResult {
run_test(
r#"def florb [
--age: int
--name = "foobar"
] {
($age | into string) + $name
}
florb --age 3"#,
"3foobar",
)
}
#[test]
fn deprecated_boolean_flag() {
let actual = nu!(r#"def florb [--dry-run: bool, --another-flag] { "aaa" }; florb"#);
assert!(actual.err.contains("not allowed"));
}
#[test]
fn simple_var_closing() -> TestResult {
run_test("let $x = 10; def foo [] { $x }; foo", "10")
}
#[test]
fn predecl_check() -> TestResult {
run_test("def bob [] { sam }; def sam [] { 3 }; bob", "3")
}
#[test]
fn def_with_no_dollar() -> TestResult {
run_test("def bob [x] { $x + 3 }; bob 4", "7")
}
#[test]
fn allow_missing_optional_params() -> TestResult {
run_test(
"def foo [x?:int] { if $x != null { $x + 10 } else { 5 } }; foo",
"5",
)
}
#[test]
fn help_present_in_def() -> TestResult {
run_test_contains(
"def foo [] {}; help foo;",
"Display the help message for this command",
)
}
#[test]
fn help_not_present_in_extern() -> TestResult {
run_test(
r#"
module test {export extern "git fetch" []};
use test `git fetch`;
help git fetch | find help | to text | ansi strip
"#,
"",
)
}
#[test]
fn override_table() -> TestResult {
run_test(r#"def table [-e] { "hi" }; table"#, "hi")
}
#[test]
fn override_table_eval_file() {
let actual = nu!(r#"def table [-e] { "hi" }; table"#);
assert_eq!(actual.out, "hi");
}
// This test is disabled on Windows because they cause a stack overflow in CI (but not locally!).
// For reasons we don't understand, the Windows CI runners are prone to stack overflow.
// TODO: investigate so we can enable on Windows
#[cfg(not(target_os = "windows"))]
#[test]
fn infinite_recursion_does_not_panic() {
let actual = nu!(r#"
def bang [] { bang }; bang
"#);
assert!(actual.err.contains("Recursion limit (50) reached"));
}
// This test is disabled on Windows because they cause a stack overflow in CI (but not locally!).
// For reasons we don't understand, the Windows CI runners are prone to stack overflow.
// TODO: investigate so we can enable on Windows
#[cfg(not(target_os = "windows"))]
#[test]
fn infinite_mutual_recursion_does_not_panic() {
let actual = nu!(r#"
def bang [] { def boom [] { bang }; boom }; bang
"#);
assert!(actual.err.contains("Recursion limit (50) reached"));
}
#[test]
fn type_check_for_during_eval() -> TestResult {
fail_test(
r#"def spam [foo: string] { $foo | describe }; def outer [--foo: string] { spam $foo }; outer"#,
"can't convert nothing to string",
)
}
#[test]
fn type_check_for_during_eval2() -> TestResult {
fail_test(
r#"def spam [foo: string] { $foo | describe }; def outer [--foo: any] { spam $foo }; outer"#,
"can't convert nothing to string",
)
}
#[test]
fn empty_list_matches_list_type() -> TestResult {
let _ = run_test(
r#"def spam [foo: list<int>] { echo $foo }; spam [] | length"#,
"0",
);
run_test(
r#"def spam [foo: list<string>] { echo $foo }; spam [] | length"#,
"0",
)
}
#[test]
fn path_argument_dont_auto_expand_if_single_quoted() -> TestResult {
run_test("def spam [foo: path] { echo $foo }; spam '~/aa'", "~/aa")
}
#[test]
fn path_argument_dont_auto_expand_if_double_quoted() -> TestResult {
run_test(r#"def spam [foo: path] { echo $foo }; spam "~/aa""#, "~/aa")
}
#[test]
fn path_argument_dont_make_absolute_if_unquoted() -> TestResult {
#[cfg(windows)]
let expected = "..\\bar";
#[cfg(not(windows))]
let expected = "../bar";
run_test(
r#"def spam [foo: path] { echo $foo }; spam foo/.../bar"#,
expected,
)
}
#[test]
fn dont_allow_implicit_casting_between_glob_and_string() -> TestResult {
let _ = fail_test(
r#"def spam [foo: string] { echo $foo }; let f: glob = 'aa'; spam $f"#,
"expected string, found glob",
);
run_test(
r#"def spam [foo: glob] { echo $foo }; let f = 'aa'; spam $f"#,
"aa",
)
}
#[test]
fn allow_pass_negative_float() -> TestResult {
run_test("def spam [val: float] { $val }; spam -1.4", "-1.4")?;
run_test("def spam [val: float] { $val }; spam -2", "-2.0")
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/repl/test_stdlib.rs | tests/repl/test_stdlib.rs | use crate::repl::tests::{TestResult, fail_test, run_test_std};
#[test]
fn not_loaded() -> TestResult {
fail_test("log info", "")
}
#[test]
fn use_command() -> TestResult {
run_test_std("use std/assert; assert true; print 'it works'", "it works")
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/repl/test_bits.rs | tests/repl/test_bits.rs | use crate::repl::tests::{TestResult, fail_test, run_test};
#[test]
fn bits_and() -> TestResult {
run_test("2 | bits and 4", "0")
}
#[test]
fn bits_and_negative() -> TestResult {
run_test("-3 | bits and 5", "5")
}
#[test]
fn bits_and_list() -> TestResult {
run_test("[1 2 3 8 9 10] | bits and 2 | str join '.'", "0.2.2.0.0.2")
}
#[test]
fn bits_or() -> TestResult {
run_test("2 | bits or 3", "3")
}
#[test]
fn bits_or_negative() -> TestResult {
run_test("-3 | bits or 5", "-3")
}
#[test]
fn bits_or_list() -> TestResult {
run_test(
"[1 2 3 8 9 10] | bits or 2 | str join '.'",
"3.2.3.10.11.10",
)
}
#[test]
fn bits_xor() -> TestResult {
run_test("2 | bits xor 3", "1")
}
#[test]
fn bits_xor_negative() -> TestResult {
run_test("-3 | bits xor 5", "-8")
}
#[test]
fn bits_xor_list() -> TestResult {
run_test(
"[1 2 3 8 9 10] | bits xor 2 | into string | str join '.'",
"3.0.1.10.11.8",
)
}
#[test]
fn bits_shift_left() -> TestResult {
run_test("2 | bits shl 3", "16")
}
#[test]
fn bits_shift_left_negative_operand() -> TestResult {
fail_test("8 | bits shl -2", "positive value")
}
#[test]
fn bits_shift_left_exceeding1() -> TestResult {
// We have no type accepting more than 64 bits so guaranteed fail
fail_test("8 | bits shl 65", "more than the available bits")
}
#[test]
fn bits_shift_left_exceeding2() -> TestResult {
// Explicitly specifying 2 bytes, but 16 is already the max
fail_test(
"8 | bits shl --number-bytes 2 16",
"more than the available bits",
)
}
#[test]
fn bits_shift_left_exceeding3() -> TestResult {
// This is purely down to the current autodetect feature limiting to the smallest integer
// type thus assuming a u8
fail_test("8 | bits shl 9", "more than the available bits")
}
#[test]
fn bits_shift_left_negative() -> TestResult {
run_test("-3 | bits shl 5", "-96")
}
#[test]
fn bits_shift_left_list() -> TestResult {
run_test(
"[1 2 7 32 9 10] | bits shl 3 | str join '.'",
"8.16.56.0.72.80",
)
}
#[test]
fn bits_shift_left_binary1() -> TestResult {
run_test(
"0x[01 30 80] | bits shl 3 | format bits",
"00001001 10000100 00000000",
)
}
#[test]
fn bits_shift_left_binary2() -> TestResult {
// Whole byte case
run_test(
"0x[01 30 80] | bits shl 8 | format bits",
"00110000 10000000 00000000",
)
}
#[test]
fn bits_shift_left_binary3() -> TestResult {
// Compared to the int case this is made inclusive of the bit count
run_test(
"0x[01 30 80] | bits shl 24 | format bits",
"00000000 00000000 00000000",
)
}
#[test]
fn bits_shift_left_binary4() -> TestResult {
// Shifting by both bytes and bits
run_test(
"0x[01 30 80] | bits shl 15 | format bits",
"01000000 00000000 00000000",
)
}
#[test]
fn bits_shift_left_binary_exceeding() -> TestResult {
// Compared to the int case this is made inclusive of the bit count
fail_test("0x[01 30] | bits shl 17 | format bits", "")
}
#[test]
fn bits_shift_right() -> TestResult {
run_test("8 | bits shr 2", "2")
}
#[test]
fn bits_shift_right_negative_operand() -> TestResult {
fail_test("8 | bits shr -2", "positive value")
}
#[test]
fn bits_shift_right_exceeding1() -> TestResult {
// We have no type accepting more than 64 bits so guaranteed fail
fail_test("8 | bits shr 65", "more than the available bits")
}
#[test]
fn bits_shift_right_exceeding2() -> TestResult {
// Explicitly specifying 2 bytes, but 16 is already the max
fail_test(
"8 | bits shr --number-bytes 2 16",
"more than the available bits",
)
}
#[test]
fn bits_shift_right_exceeding3() -> TestResult {
// This is purely down to the current autodetect feature limiting to the smallest integer
// type thus assuming a u8
fail_test("8 | bits shr 9", "more than the available bits")
}
#[test]
fn bits_shift_right_negative() -> TestResult {
run_test("-32 | bits shr 2", "-8")
}
#[test]
fn bits_shift_right_list() -> TestResult {
run_test(
"[12 98 7 64 900 10] | bits shr 3 | str join '.'",
"1.12.0.8.112.1",
)
}
#[test]
fn bits_shift_right_binary1() -> TestResult {
run_test(
"0x[01 30 80] | bits shr 3 | format bits",
"00000000 00100110 00010000",
)
}
#[test]
fn bits_shift_right_binary2() -> TestResult {
// Whole byte case
run_test(
"0x[01 30 80] | bits shr 8 | format bits",
"00000000 00000001 00110000",
)
}
#[test]
fn bits_shift_right_binary3() -> TestResult {
// Compared to the int case this is made inclusive of the bit count
run_test(
"0x[01 30 80] | bits shr 24 | format bits",
"00000000 00000000 00000000",
)
}
#[test]
fn bits_shift_right_binary4() -> TestResult {
// Shifting by both bytes and bits
run_test(
"0x[01 30 80] | bits shr 15 | format bits",
"00000000 00000000 00000010",
)
}
#[test]
fn bits_shift_right_binary_exceeding() -> TestResult {
// Compared to the int case this is made inclusive of the bit count
fail_test(
"0x[01 30] | bits shr 17 | format bits",
"available bits (16)",
)
}
#[test]
fn bits_rotate_left() -> TestResult {
run_test("2 | bits rol 3", "16")
}
#[test]
fn bits_rotate_left_negative() -> TestResult {
run_test("-3 | bits rol 5", "-65")
}
#[test]
fn bits_rotate_left_list() -> TestResult {
run_test(
"[1 2 7 32 9 10] | bits rol 3 | str join '.'",
"8.16.56.1.72.80",
)
}
#[test]
fn bits_rotate_left_negative_operand() -> TestResult {
fail_test("8 | bits rol -2", "positive value")
}
#[test]
fn bits_rotate_left_exceeding1() -> TestResult {
// We have no type accepting more than 64 bits so guaranteed fail
fail_test("8 | bits rol 65", "more than the available bits (8)")
}
#[test]
fn bits_rotate_left_exceeding2() -> TestResult {
// This is purely down to the current autodetect feature limiting to the smallest integer
// type thus assuming a u8
fail_test("8 | bits rol 9", "more than the available bits (8)")
}
#[test]
fn bits_rotate_left_binary1() -> TestResult {
run_test(
"0x[01 30 80] | bits rol 3 | format bits",
"00001001 10000100 00000000",
)
}
#[test]
fn bits_rotate_left_binary2() -> TestResult {
// Whole byte case
run_test(
"0x[01 30 80] | bits rol 8 | format bits",
"00110000 10000000 00000001",
)
}
#[test]
fn bits_rotate_left_binary3() -> TestResult {
// Compared to the int case this is made inclusive of the bit count
run_test(
"0x[01 30 80] | bits rol 24 | format bits",
"00000001 00110000 10000000",
)
}
#[test]
fn bits_rotate_left_binary4() -> TestResult {
// Shifting by both bytes and bits
run_test(
"0x[01 30 80] | bits rol 15 | format bits",
"01000000 00000000 10011000",
)
}
#[test]
fn bits_rotate_right() -> TestResult {
run_test("2 | bits ror 6", "8")
}
#[test]
fn bits_rotate_right_negative() -> TestResult {
run_test("-3 | bits ror 4", "-33")
}
#[test]
fn bits_rotate_right_list() -> TestResult {
run_test(
"[1 2 7 32 23 10] | bits ror 4 | str join '.'",
"16.32.112.2.113.160",
)
}
#[test]
fn bits_rotate_right_negative_operand() -> TestResult {
fail_test("8 | bits ror -2", "positive value")
}
#[test]
fn bits_rotate_right_exceeding1() -> TestResult {
// We have no type accepting more than 64 bits so guaranteed fail
fail_test("8 | bits ror 65", "more than the available bits (8)")
}
#[test]
fn bits_rotate_right_exceeding2() -> TestResult {
// This is purely down to the current autodetect feature limiting to the smallest integer
// type thus assuming a u8
fail_test("8 | bits ror 9", "more than the available bits (8)")
}
#[test]
fn bits_rotate_right_binary1() -> TestResult {
run_test(
"0x[01 30 80] | bits ror 3 | format bits",
"00000000 00100110 00010000",
)
}
#[test]
fn bits_rotate_right_binary2() -> TestResult {
// Whole byte case
run_test(
"0x[01 30 80] | bits ror 8 | format bits",
"10000000 00000001 00110000",
)
}
#[test]
fn bits_rotate_right_binary3() -> TestResult {
// Compared to the int case this is made inclusive of the bit count
run_test(
"0x[01 30 80] | bits ror 24 | format bits",
"00000001 00110000 10000000",
)
}
#[test]
fn bits_rotate_right_binary4() -> TestResult {
// Shifting by both bytes and bits
run_test(
"0x[01 30 80] | bits ror 15 | format bits",
"01100001 00000000 00000010",
)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/repl/test_signatures.rs | tests/repl/test_signatures.rs | use crate::repl::tests::{TestResult, fail_test, run_test};
use rstest::rstest;
#[test]
fn list_annotations() -> TestResult {
let input = "def run [list: list<int>] {$list | length}; run [2 5 4]";
let expected = "3";
run_test(input, expected)
}
#[test]
fn list_annotations_unknown_prefix() -> TestResult {
let input = "def run [list: listint>] {$list | length}; run [2 5 4]";
let expected = "unknown type";
fail_test(input, expected)
}
#[test]
fn list_annotations_empty_1() -> TestResult {
let input = "def run [list: list] {$list | length}; run [2 5 4]";
let expected = "3";
run_test(input, expected)
}
#[test]
fn list_annotations_empty_2() -> TestResult {
let input = "def run [list: list<>] {$list | length}; run [2 5 4]";
let expected = "3";
run_test(input, expected)
}
#[test]
fn list_annotations_empty_3() -> TestResult {
let input = "def run [list: list< >] {$list | length}; run [2 5 4]";
let expected = "3";
run_test(input, expected)
}
#[test]
fn list_annotations_empty_4() -> TestResult {
let input = "def run [list: list<\n>] {$list | length}; run [2 5 4]";
let expected = "3";
run_test(input, expected)
}
#[test]
fn list_annotations_nested() -> TestResult {
let input = "def run [list: list<list<float>>] {$list | length}; run [ [2.0] [5.0] [4.0]]";
let expected = "3";
run_test(input, expected)
}
#[test]
fn list_annotations_unknown_inner_type() -> TestResult {
let input = "def run [list: list<str>] {$list | length}; run ['nushell' 'nunu' 'nana']";
let expected = "unknown type";
fail_test(input, expected)
}
#[test]
fn list_annotations_nested_unknown_inner() -> TestResult {
let input = "def run [list: list<list<str>>] {$list | length}; run [ [nushell] [nunu] [nana]]";
let expected = "unknown type";
fail_test(input, expected)
}
#[test]
fn list_annotations_unterminated() -> TestResult {
let input = "def run [list: list<string] {$list | length}; run [nu she ll]";
let expected = "expected closing >";
fail_test(input, expected)
}
#[test]
fn list_annotations_nested_unterminated() -> TestResult {
let input = "def run [list: list<list<>] {$list | length}; run [2 5 4]";
let expected = "expected closing >";
fail_test(input, expected)
}
#[test]
fn list_annotations_space_within_1() -> TestResult {
let input = "def run [list: list< range>] {$list | length}; run [2..32 5..<64 4..128]";
let expected = "3";
run_test(input, expected)
}
#[test]
fn list_annotations_space_within_2() -> TestResult {
let input = "def run [list: list<number >] {$list | length}; run [2 5 4]";
let expected = "3";
run_test(input, expected)
}
#[test]
fn list_annotations_space_within_3() -> TestResult {
let input = "def run [list: list< int >] {$list | length}; run [2 5 4]";
let expected = "3";
run_test(input, expected)
}
#[test]
fn list_annotations_space_before() -> TestResult {
let input = "def run [list: list <int>] {$list | length}; run [2 5 4]";
let expected = "expected valid variable name for this parameter";
fail_test(input, expected)
}
#[test]
fn list_annotations_unknown_separators() -> TestResult {
let input = "def run [list: list<int, string>] {$list | length}; run [2 5 4]";
let expected = "only one parameter allowed";
fail_test(input, expected)
}
#[test]
fn list_annotations_with_default_val_1() -> TestResult {
let input = "def run [list: list<int> = [2 5 4]] {$list | length}; run";
let expected = "3";
run_test(input, expected)
}
#[test]
fn list_annotations_with_default_val_2() -> TestResult {
let input = "def run [list: list<string> = [2 5 4]] {$list | length}; run";
let expected = "Default value wrong type";
fail_test(input, expected)
}
#[test]
fn list_annotations_with_extra_characters() -> TestResult {
let input = "def run [list: list<int>extra] {$list | length}; run [1 2 3]";
let expected = "Extra characters in the parameter name";
fail_test(input, expected)
}
#[test]
fn record_annotations_none() -> TestResult {
let input = "def run [rec: record] { $rec }; run {} | describe";
let expected = "record";
run_test(input, expected)
}
#[test]
fn record_annotations() -> TestResult {
let input = "def run [rec: record<age: int>] { $rec }; run {age: 3} | describe";
let expected = "record<age: int>";
run_test(input, expected)
}
#[test]
fn record_annotations_two_types() -> TestResult {
let input = "def run [rec: record<name: string age: int>] { $rec }; run {name: nushell age: 3} | describe";
let expected = "record<name: string, age: int>";
run_test(input, expected)
}
#[test]
fn record_annotations_two_types_comma_sep() -> TestResult {
let input = "def run [rec: record<name: string, age: int>] { $rec }; run {name: nushell age: 3} | describe";
let expected = "record<name: string, age: int>";
run_test(input, expected)
}
#[test]
fn record_annotations_key_with_no_type() -> TestResult {
let input = "def run [rec: record<name>] { $rec }; run {name: nushell} | describe";
let expected = "record<name: string>";
run_test(input, expected)
}
#[test]
fn record_annotations_two_types_one_with_no_type() -> TestResult {
let input =
"def run [rec: record<name: string, age>] { $rec }; run {name: nushell age: 3} | describe";
let expected = "record<name: string, age: int>";
run_test(input, expected)
}
#[test]
fn record_annotations_two_types_both_with_no_types() -> TestResult {
let input = "def run [rec: record<name age>] { $rec }; run {name: nushell age: 3} | describe";
let expected = "record<name: string, age: int>";
run_test(input, expected)
}
#[test]
fn record_annotations_nested() -> TestResult {
let input = "def run [
err: record<
msg: string,
label: record<
text: string
start: int,
end: int,
>>
] {
$err
}; run {
msg: 'error message'
label: {
text: 'here is the error'
start: 0
end: 69
}
} | describe";
let expected = "record<msg: string, label: record<text: string, start: int, end: int>>";
run_test(input, expected)
}
#[test]
fn record_annotations_type_inference_1() -> TestResult {
let input = "def run [rec: record<age: any>] { $rec }; run {age: 2wk} | describe";
let expected = "record<age: duration>";
run_test(input, expected)
}
#[test]
fn record_annotations_type_inference_2() -> TestResult {
let input = "def run [rec: record<size>] { $rec }; run {size: 2mb} | describe";
let expected = "record<size: filesize>";
run_test(input, expected)
}
#[test]
fn record_annotations_not_terminated() -> TestResult {
let input = "def run [rec: record<age: int] { $rec }";
let expected = "expected closing >";
fail_test(input, expected)
}
#[test]
fn record_annotations_not_terminated_inner() -> TestResult {
let input = "def run [rec: record<name: string, repos: list<string>] { $rec }";
let expected = "expected closing >";
fail_test(input, expected)
}
#[test]
fn record_annotations_no_type_after_colon() -> TestResult {
let input = "def run [rec: record<name: >] { $rec }";
let expected = "type after colon";
fail_test(input, expected)
}
#[test]
fn record_annotations_type_mismatch_key() -> TestResult {
let input = "def run [rec: record<name: string>] { $rec }; run {nme: nushell}";
let expected = "expected record<name: string>, found record<nme: string>";
fail_test(input, expected)
}
#[test]
fn record_annotations_type_mismatch_shape() -> TestResult {
let input = "def run [rec: record<age: int>] { $rec }; run {age: 2wk}";
let expected = "expected record<age: int>, found record<age: duration>";
fail_test(input, expected)
}
#[test]
fn record_annotations_with_extra_characters() -> TestResult {
let input = "def run [list: record<int>extra] {$list | length}; run [1 2 3]";
let expected = "Extra characters in the parameter name";
fail_test(input, expected)
}
#[test]
fn table_annotations_none() -> TestResult {
let input = "def run [t: table] { $t }; run [[]; []] | describe";
let expected = "table";
run_test(input, expected)
}
#[rstest]
fn table_annotations(
#[values(true, false)] list_annotation: bool,
#[values(
("age: int", "age: int", "[[age]; [3]]" ),
("name: string age: int", "name: string, age: int", "[[name, age]; [nushell, 3]]" ),
("name: string, age: int", "name: string, age: int", "[[name, age]; [nushell, 3]]" ),
("name", "name: string", "[[name]; [nushell]]"),
("name: string, age", "name: string, age: int", "[[name, age]; [nushell, 3]]"),
("name, age", "name: string, age: int", "[[name, age]; [nushell, 3]]"),
("age: any", "age: duration", "[[age]; [2wk]]"),
("size", "size: filesize", "[[size]; [2mb]]")
)]
record_annotation_data: (&str, &str, &str),
) -> TestResult {
let (record_annotation, inferred_type, data) = record_annotation_data;
let type_annotation = match list_annotation {
true => format!("list<record<{record_annotation}>>"),
false => format!("table<{record_annotation}>"),
};
let input = format!("def run [t: {type_annotation}] {{ $t }}; run {data} | describe");
let expected = format!("table<{inferred_type}>");
run_test(&input, &expected)
}
#[test]
fn table_annotations_not_terminated() -> TestResult {
let input = "def run [t: table<age: int] { $t }";
let expected = "expected closing >";
fail_test(input, expected)
}
#[test]
fn table_annotations_not_terminated_inner() -> TestResult {
let input = "def run [t: table<name: string, repos: list<string>] { $t }";
let expected = "expected closing >";
fail_test(input, expected)
}
#[test]
fn table_annotations_no_type_after_colon() -> TestResult {
let input = "def run [t: table<name: >] { $t }";
let expected = "type after colon";
fail_test(input, expected)
}
#[test]
fn table_annotations_type_mismatch_column() -> TestResult {
let input = "def run [t: table<name: string>] { $t }; run [[nme]; [nushell]]";
let expected = "expected table<name: string>, found table<nme: string>";
fail_test(input, expected)
}
#[test]
fn table_annotations_type_mismatch_shape() -> TestResult {
let input = "def run [t: table<age: int>] { $t }; run [[age]; [2wk]]";
let expected = "expected table<age: int>, found table<age: duration>";
fail_test(input, expected)
}
#[test]
fn table_annotations_with_extra_characters() -> TestResult {
let input = "def run [t: table<int>extra] {$t | length}; run [[int]; [8]]";
let expected = "Extra characters in the parameter name";
fail_test(input, expected)
}
#[rstest]
fn oneof_annotations(
#[values(
("cell-path, list<cell-path>", "a.b.c", "cell-path"),
("cell-path, list<cell-path>", "[a.b.c d.e.f]", "list<cell-path>"),
("closure, any", "{}", "closure"),
("closure, any", "{a: 1}", "record<a: int>"),
)]
annotation_data: (&str, &str, &str),
) -> TestResult {
let (types, argument, expected) = annotation_data;
let input = format!("def run [t: oneof<{types}>] {{ $t }}; run {argument} | describe");
run_test(&input, expected)
}
#[rstest]
#[case::correct_type_(run_test, "{a: 1}", "")]
#[case::correct_type_(run_test, "{a: null}", "")]
#[case::parse_time_incorrect_type(fail_test, "{a: 1.0}", "parser::type_mismatch")]
#[case::run_time_incorrect_type(fail_test, "(echo {a: 1.0})", "shell::cant_convert")]
fn oneof_type_checking(
#[case] testfn: fn(&str, &str) -> TestResult,
#[case] argument: &str,
#[case] expect: &str,
) {
let _ = testfn(
&format!(r#"def run [p: record<a: oneof<int, nothing>>] {{ }}; run {argument}"#),
expect,
);
}
#[test]
fn oneof_annotations_not_terminated() -> TestResult {
let input = "def run [t: oneof<binary, string] { $t }";
let expected = "expected closing >";
fail_test(input, expected)
}
#[test]
fn oneof_annotations_with_extra_characters() -> TestResult {
let input = "def run [t: oneof<int, string>extra] {$t}";
let expected = "Extra characters in the parameter name";
fail_test(input, expected)
}
#[rstest]
#[case("{ |a $a }")]
#[case("{ |a, b $a + $b }")]
#[case("do { |a $a } 1")]
#[case("do { |a $a } 1 2")]
fn closure_param_list_not_terminated(#[case] input: &str) -> TestResult {
fail_test(input, "unclosed |")
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/repl/test_conditionals.rs | tests/repl/test_conditionals.rs | use crate::repl::tests::{TestResult, run_test};
#[test]
fn if_test1() -> TestResult {
run_test("if true { 10 } else { 20 } ", "10")
}
#[test]
fn if_test2() -> TestResult {
run_test("if false { 10 } else { 20 } ", "20")
}
#[test]
fn simple_if() -> TestResult {
run_test("if true { 10 } ", "10")
}
#[test]
fn simple_if2() -> TestResult {
run_test("if false { 10 } ", "")
}
#[test]
fn if_cond() -> TestResult {
run_test("if 2 < 3 { 3 } ", "3")
}
#[test]
fn if_cond2() -> TestResult {
run_test("if 2 > 3 { 3 } ", "")
}
#[test]
fn if_cond3() -> TestResult {
run_test("if 2 < 3 { 5 } else { 4 } ", "5")
}
#[test]
fn if_cond4() -> TestResult {
run_test("if 2 > 3 { 5 } else { 4 } ", "4")
}
#[test]
fn if_elseif1() -> TestResult {
run_test("if 2 > 3 { 5 } else if 6 < 7 { 4 } ", "4")
}
#[test]
fn if_elseif2() -> TestResult {
run_test("if 2 < 3 { 5 } else if 6 < 7 { 4 } else { 8 } ", "5")
}
#[test]
fn if_elseif3() -> TestResult {
run_test("if 2 > 3 { 5 } else if 6 > 7 { 4 } else { 8 } ", "8")
}
#[test]
fn if_elseif4() -> TestResult {
run_test("if 2 > 3 { 5 } else if 6 < 7 { 4 } else { 8 } ", "4")
}
#[test]
fn mutation_in_else() -> TestResult {
run_test(
"mut x = 100; if 2 > 3 { $x = 200 } else { $x = 300 }; $x ",
"300",
)
}
#[test]
fn mutation_in_else2() -> TestResult {
run_test(
"mut x = 100; if 2 > 3 { $x = 200 } else if true { $x = 400 } else { $x = 300 }; $x ",
"400",
)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/repl/test_strings.rs | tests/repl/test_strings.rs | use crate::repl::tests::{TestResult, fail_test, run_test};
#[test]
fn cjk_in_substrings() -> TestResult {
run_test(
r#"let s = '[Rust 程序设计语言](title-page.md)'; let start = ($s | str index-of '('); let end = ($s | str index-of ')'); $s | str substring ($start + 1)..<($end)"#,
"title-page.md",
)
}
#[test]
fn string_not_in_string() -> TestResult {
run_test(r#"'d' not-in 'abc'"#, "true")
}
#[test]
fn string_in_string() -> TestResult {
run_test(r#"'z' in 'abc'"#, "false")
}
#[test]
fn non_string_in_string() -> TestResult {
fail_test(r#"42 in 'abc'"#, "nu::parser::operator_incompatible_types")
}
#[test]
fn string_in_record() -> TestResult {
run_test(r#""a" in ('{ "a": 13, "b": 14 }' | from json)"#, "true")
}
#[test]
fn non_string_in_record() -> TestResult {
fail_test(
r#"4 in ('{ "a": 13, "b": 14 }' | from json)"#,
"nu::shell::operator_incompatible_types",
)
}
#[test]
fn unbalance_string() -> TestResult {
fail_test(r#""aaaab"cc"#, "invalid characters")?;
fail_test(r#"'aaaab'cc"#, "invalid characters")
}
#[test]
fn string_in_valuestream() -> TestResult {
run_test(
r#"
'Hello' in ("Hello
World" | lines)"#,
"true",
)
}
#[test]
fn single_tick_interpolation() -> TestResult {
run_test(r#"$'(3 + 4)'"#, "7")
}
#[test]
fn detect_newlines() -> TestResult {
run_test("'hello\r\nworld' | lines | get 0 | str length", "5")
}
#[test]
fn case_insensitive_sort() -> TestResult {
run_test(
r#"[a, B, d, C, f] | sort -i | to json --raw"#,
"[\"a\",\"B\",\"C\",\"d\",\"f\"]",
)
}
#[test]
fn case_insensitive_sort_columns() -> TestResult {
run_test(
r#"[[version, package]; ["two", "Abc"], ["three", "abc"], ["four", "abc"]] | sort-by -i package version | to json --raw"#,
r#"[{"version":"four","package":"abc"},{"version":"three","package":"abc"},{"version":"two","package":"Abc"}]"#,
)
}
#[test]
fn raw_string() -> TestResult {
run_test(r#"r#'abcde""fghi"''''jkl'#"#, r#"abcde""fghi"''''jkl"#)?;
run_test(r#"r##'abcde""fghi"''''#jkl'##"#, r#"abcde""fghi"''''#jkl"#)?;
run_test(
r#"r###'abcde""fghi"'''##'#jkl'###"#,
r#"abcde""fghi"'''##'#jkl"#,
)?;
run_test("r#''#", "")?;
run_test(
r#"r#'a string with sharp inside # and ends with #'#"#,
"a string with sharp inside # and ends with #",
)
}
#[test]
fn raw_string_inside_parentheses() -> TestResult {
let (left, right) = ('(', ')');
run_test(
&format!(r#"{left}r#'abcde""fghi"''''jkl'#{right}"#),
r#"abcde""fghi"''''jkl"#,
)?;
run_test(
&format!(r#"{left}r##'abcde""fghi"''''#jkl'##{right}"#),
r#"abcde""fghi"''''#jkl"#,
)?;
run_test(
&format!(r#"{left}r###'abcde""fghi"'''##'#jkl'###{right}"#),
r#"abcde""fghi"'''##'#jkl"#,
)?;
run_test(&format!("{left}r#''#{right}"), "")?;
run_test(
&format!(r#"{left}r#'a string with sharp inside # and ends with #'#{right}"#),
"a string with sharp inside # and ends with #",
)
}
#[test]
fn raw_string_inside_list() -> TestResult {
let (left, right) = ('[', ']');
run_test(
&format!(r#"{left}r#'abcde""fghi"''''jkl'#{right} | get 0"#),
r#"abcde""fghi"''''jkl"#,
)?;
run_test(
&format!(r#"{left}r##'abcde""fghi"''''#jkl'##{right} | get 0"#),
r#"abcde""fghi"''''#jkl"#,
)?;
run_test(
&format!(r#"{left}r###'abcde""fghi"'''##'#jkl'###{right} | get 0"#),
r#"abcde""fghi"'''##'#jkl"#,
)?;
run_test(&format!("{left}r#''#{right} | get 0"), "")?;
run_test(
&format!(r#"{left}r#'a string with sharp inside # and ends with #'#{right} | get 0"#),
"a string with sharp inside # and ends with #",
)
}
#[test]
fn raw_string_inside_closure() -> TestResult {
let (left, right) = ('{', '}');
run_test(
&format!(r#"do {left}r#'abcde""fghi"''''jkl'#{right}"#),
r#"abcde""fghi"''''jkl"#,
)?;
run_test(
&format!(r#"do {left}r##'abcde""fghi"''''#jkl'##{right}"#),
r#"abcde""fghi"''''#jkl"#,
)?;
run_test(
&format!(r#"do {left}r###'abcde""fghi"'''##'#jkl'###{right}"#),
r#"abcde""fghi"'''##'#jkl"#,
)?;
run_test(&format!("do {left}r#''#{right}"), "")?;
run_test(
&format!(r#"do {left}r#'a string with sharp inside # and ends with #'#{right}"#),
"a string with sharp inside # and ends with #",
)
}
#[test]
fn incomplete_string() -> TestResult {
fail_test("r#abc", "expected '")?;
fail_test("r#'bc", "expected closing '#")?;
fail_test("'ab\"", "expected closing '")?;
fail_test("\"ab'", "expected closing \"")?;
fail_test(
r#"def func [] {
{
"A": ""B" # <- the quote is bad
}
}
"#,
"expected closing \"",
)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/repl/test_type_check.rs | tests/repl/test_type_check.rs | use crate::repl::tests::{TestResult, fail_test, run_test, run_test_contains};
use rstest::rstest;
#[test]
fn chained_operator_typecheck() -> TestResult {
run_test("1 != 2 and 3 != 4 and 5 != 6", "true")
}
#[test]
fn type_in_list_of_this_type() -> TestResult {
run_test(r#"42 in [41 42 43]"#, "true")
}
#[test]
fn type_in_list_of_non_this_type() -> TestResult {
fail_test(
r#"'hello' in [41 42 43]"#,
"nu::parser::operator_incompatible_types",
)
}
#[test]
fn number_int() -> TestResult {
run_test(r#"def foo [x:number] { $x }; foo 1"#, "1")
}
#[test]
fn int_record_mismatch() -> TestResult {
fail_test(r#"def foo [x:int] { $x }; foo {}"#, "expected int")
}
#[test]
fn number_float() -> TestResult {
run_test(r#"def foo [x:number] { $x }; foo 1.4"#, "1.4")
}
#[test]
fn date_minus_duration() -> TestResult {
let input = "2023-04-22 - 2day | format date %Y-%m-%d";
let expected = "2023-04-20";
run_test(input, expected)
}
#[test]
fn duration_minus_date_not_supported() -> TestResult {
fail_test(
"2day - 2023-04-22",
"nu::parser::operator_incompatible_types",
)
}
#[test]
fn date_plus_duration() -> TestResult {
let input = "2023-04-18 + 2day | format date %Y-%m-%d";
let expected = "2023-04-20";
run_test(input, expected)
}
#[test]
fn duration_plus_date() -> TestResult {
let input = "2024-11-10T00:00:00-00:00 + 4hr | format date";
let expected = "Sun, 10 Nov 2024 04:00:00 +0000";
run_test(input, expected)
}
#[test]
fn block_not_first_class_def() -> TestResult {
fail_test(
"def foo [x: block] { do $x }",
"Blocks are not support as first-class values",
)
}
#[test]
fn block_not_first_class_let() -> TestResult {
fail_test(
"let x: block = { 3 }",
"Blocks are not support as first-class values",
)
}
#[test]
fn record_subtyping() -> TestResult {
run_test(
"def test [rec: record<name: string, age: int>] { $rec | describe };
test { age: 4, name: 'John' }",
"record<age: int, name: string>",
)
}
#[test]
fn record_subtyping_2() -> TestResult {
run_test(
"def test [rec: record<name: string, age: int>] { $rec | describe };
test { age: 4, name: 'John', height: '5-9' }",
"record<age: int, name: string, height: string>",
)
}
#[test]
fn record_subtyping_3() -> TestResult {
fail_test(
"def test [rec: record<name: string, age: int>] { $rec | describe };
test { name: 'Nu' }",
"expected",
)
}
#[test]
fn record_subtyping_allows_general_record() -> TestResult {
run_test(
"def test []: record<name: string, age: int> -> string { $in; echo 'success' };
def underspecified []: nothing -> record {{name:'Douglas', age:42}};
underspecified | test",
"success",
)
}
#[test]
fn record_subtyping_allows_record_after_general_command() -> TestResult {
run_test(
"def test []: record<name: string, age: int> -> string { $in; echo 'success' };
{name:'Douglas', surname:'Adams', age:42} | select name age | test",
"success",
)
}
#[test]
fn record_subtyping_allows_general_inner() -> TestResult {
run_test(
"def merge_records [other: record<bar: int>]: record<foo: string> -> record<foo: string, bar: int> { merge $other }",
"",
)
}
#[test]
fn record_subtyping_works() -> TestResult {
run_test(
r#"def merge_records [other: record<bar: int>] { "" }; merge_records {"bar": 3, "foo": 4}"#,
"",
)
}
#[rstest]
// [ int, number ] is widened to list<number>
#[case("let n: number = 1; let foo = [ 1, $n ];", "list<number>")]
// supertype of list elements (records)
#[case("let foo = [ { a: 1 }, { a: 1, b: 2 } ];", "list<record<a: int>>")]
// [ list supertype, table ]
#[case(
"let foo = [ [ { a: 1 } ], [ [a, b]; [1, 2] ] ];",
"list<list<record<a: int>>>"
)]
// [ list, table supertype ]
#[case(
"let foo = [ [{ a: 1, b: 2 }], [ [a]; [1] ] ];",
"list<list<record<a: int>>>"
)]
// disjoint element types: empty element supertype
#[case("let foo = [[ [bar]; [1] ], [ { baz: 1 } ] ];", "list<list<record>>")]
// `bar: int` and `bar: number` are widened to table<bar: number>
#[case(
"let n: number = 1; let foo = [ [bar]; [1], [$n] ];",
"table<bar: number>"
)]
// supertype of table values (records)
#[case(
"let foo = [ [item]; [ {a: 1} ], [ {a: 1, b: 1 } ] ];",
"table<item: record<a: int>>"
)]
// disjoint table values: oneof
#[case("let foo = [ [bar]; [1], [true] ];", "table<bar: oneof<int, bool>>")]
#[test]
fn collection_supertype_inference(
#[case] assignment: &str,
#[case] expected_type: &str,
) -> TestResult {
run_test(
&format!(r#"{assignment} scope variables | where name == "$foo" | first | get type"#),
expected_type,
)
}
#[test]
fn pipeline_oneof() -> TestResult {
// Empty is compatible with oneof<nothing, ..>
run_test(
"def f []: [oneof<int, nothing> -> nothing] { describe }; f",
"nothing",
)?;
// ByteStream is compatible with oneof<binary, ..>
run_test(
"def f []: [oneof<int, binary> -> nothing] { describe }; [0x[01]] | bytes collect | f",
"binary (stream)",
)?;
// ListStream is compatible with oneof<list, ..>>
run_test(
"def f []: [oneof<string, list<int>> -> nothing] { describe }; [1] | each {} | f",
"list<int> (stream)",
)
}
#[test]
fn transpose_into_load_env() -> TestResult {
run_test(
"[[col1, col2]; [a, 10], [b, 20]] | transpose --ignore-titles -r -d | load-env; $env.a",
"10",
)
}
#[test]
fn in_variable_expression_correct_output_type() -> TestResult {
run_test(r#"def foo []: nothing -> string { 'foo' | $"($in)" }"#, "")
}
#[test]
fn in_variable_expression_wrong_output_type() -> TestResult {
fail_test(
r#"def foo []: nothing -> int { 'foo' | $"($in)" }"#,
"expected int",
)
}
#[rstest]
#[case("if true {} else { foo 1 }")]
#[case("if true {} else if (foo 1) == null { }")]
#[case("match 1 { 0 => { foo 1 } }")]
#[case("try { } catch { foo 1 }")]
/// type errors should propagate from `OneOf(Block | Closure | Expression, ..)`
fn in_oneof_block_expected_type(#[case] input: &str) -> TestResult {
let def = "def foo [bar: bool] {};";
fail_test(&format!("{def} {input}"), "expected bool")
}
#[test]
fn in_oneof_block_expected_block() -> TestResult {
fail_test("match 1 { 0 => { try 3 } }", "expected block")
}
#[test]
fn pipeline_multiple_types() -> TestResult {
// https://github.com/nushell/nushell/issues/15485
run_test_contains("{year: 2019} | into datetime | date humanize", "years ago")
}
const MULTIPLE_TYPES_DEFS: &str = "
def foo []: [int -> int, int -> string] {
if $in > 2 { 'hi' } else 4
}
def bar []: [int -> filesize, string -> string] {
if $in == 'hi' { 'meow' } else { into filesize }
}
";
#[test]
fn pipeline_multiple_types_custom() -> TestResult {
run_test(
&format!(
"{MULTIPLE_TYPES_DEFS}
5 | foo | str trim"
),
"hi",
)
}
#[test]
fn pipeline_multiple_types_propagate_string() -> TestResult {
run_test(
&format!(
"{MULTIPLE_TYPES_DEFS}
5 | foo | bar | str trim"
),
"meow",
)
}
#[test]
fn pipeline_multiple_types_propagate_int() -> TestResult {
run_test(
&format!(
"{MULTIPLE_TYPES_DEFS}
2 | foo | bar | format filesize B"
),
"4 B",
)
}
#[test]
fn pipeline_multiple_types_propagate_error() -> TestResult {
fail_test(
&format!(
"{MULTIPLE_TYPES_DEFS}
2 | foo | bar | values"
),
"parser::input_type_mismatch",
)
}
#[test]
fn array_of_wrong_types() -> TestResult {
fail_test(
"0..128 | each {} | into string | bytes collect",
"command doesn't support list<string>, record, string, or table input",
)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/parsing/mod.rs | tests/parsing/mod.rs | use nu_test_support::fs::Stub::FileWithContentToBeTrimmed;
use nu_test_support::nu;
use nu_test_support::playground::Playground;
use pretty_assertions::assert_eq;
use rstest::rstest;
#[test]
fn source_file_relative_to_file() {
let actual = nu!(cwd: "tests/parsing/samples", "
nu source_file_relative.nu
");
assert_eq!(actual.out, "5");
}
#[test]
fn source_file_relative_to_config() {
let actual = nu!("
nu --config tests/parsing/samples/source_file_relative.nu --commands ''
");
assert_eq!(actual.out, "5");
}
#[test]
fn source_const_file() {
let actual = nu!(cwd: "tests/parsing/samples",
"
const file = 'single_line.nu'
source $file
");
assert_eq!(actual.out, "5");
}
// Regression test for https://github.com/nushell/nushell/issues/17091
// Bare-word string interpolation with constants should work in `source`
#[test]
fn source_const_in_bareword_interpolation() {
Playground::setup("source_const_in_bareword_test", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"test_macos.nu",
"
print 'macos'
",
)]);
sandbox.with_files(&[FileWithContentToBeTrimmed(
"test_linux.nu",
"
print 'linux'
",
)]);
sandbox.with_files(&[FileWithContentToBeTrimmed(
"test_windows.nu",
"
print 'windows'
",
)]);
let actual = nu!(
cwd: dirs.test(),
"source test_($nu.os-info.name).nu"
);
let os_name = std::env::consts::OS;
assert_eq!(actual.out, os_name);
});
}
// Test edge cases for paths with parentheses
#[test]
fn source_path_with_literal_parens() {
Playground::setup("source_literal_parens_test", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"file(with)parens.nu",
"
print 'literal parens'
",
)]);
// Quoted path with literal parentheses should work
let actual = nu!(
cwd: dirs.test(),
r#"source "file(with)parens.nu""#
);
assert_eq!(actual.out, "literal parens");
});
}
#[test]
fn source_path_interpolation_vs_literal() {
Playground::setup("source_interp_vs_literal_test", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"file(name).nu",
"
print 'literal file'
",
)]);
sandbox.with_files(&[FileWithContentToBeTrimmed(
"file_macos.nu",
"
print 'interpolated file'
",
)]);
sandbox.with_files(&[FileWithContentToBeTrimmed(
"file_linux.nu",
"
print 'interpolated file'
",
)]);
sandbox.with_files(&[FileWithContentToBeTrimmed(
"file_windows.nu",
"
print 'interpolated file'
",
)]);
// Quoted path should treat parens as literal
let actual_quoted = nu!(
cwd: dirs.test(),
r#"source "file(name).nu""#
);
assert_eq!(actual_quoted.out, "literal file");
// Bare word with parens containing variable should interpolate
let actual_interp = nu!(
cwd: dirs.test(),
"source file_($nu.os-info.name).nu"
);
assert_eq!(actual_interp.out, "interpolated file");
});
}
#[test]
fn source_path_with_nested_parens() {
Playground::setup("source_nested_parens_test", |dirs, sandbox| {
let os_name = std::env::consts::OS;
sandbox.with_files(&[FileWithContentToBeTrimmed(
&format!("test_{}_nested.nu", os_name),
"
print 'nested parens'
",
)]);
// Nested parentheses in interpolation
let actual = nu!(
cwd: dirs.test(),
r#"source test_($nu.os-info | get name)_nested.nu"#
);
assert_eq!(actual.out, "nested parens");
});
}
#[test]
fn source_path_single_quote_no_interpolation() {
Playground::setup("source_single_quote_test", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"file($nu.os-info.name).nu",
"
print 'no interpolation'
",
)]);
// Single quotes should prevent interpolation
let actual = nu!(
cwd: dirs.test(),
r#"source 'file($nu.os-info.name).nu'"#
);
assert_eq!(actual.out, "no interpolation");
});
}
#[test]
fn source_path_backtick_no_interpolation() {
Playground::setup("source_backtick_test", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"file($nu.os-info.name).nu",
"
print 'backtick no interp'
",
)]);
// Backticks should also prevent interpolation
let actual = nu!(
cwd: dirs.test(),
r#"source `file($nu.os-info.name).nu`"#
);
assert_eq!(actual.out, "backtick no interp");
});
}
#[test]
fn source_path_dollar_interpolation() {
Playground::setup("source_dollar_interp_test", |dirs, sandbox| {
let os_name = std::env::consts::OS;
sandbox.with_files(&[FileWithContentToBeTrimmed(
&format!("test_{}.nu", os_name),
"
print 'dollar interpolation'
",
)]);
// Dollar prefix should enable interpolation in quotes
let actual = nu!(
cwd: dirs.test(),
r#"source $"test_($nu.os-info.name).nu""#
);
assert_eq!(actual.out, "dollar interpolation");
});
}
#[test]
fn source_path_mixed_parens_and_quotes() {
Playground::setup("source_mixed_parens_test", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"test(1).nu",
"
print 'test 1'
",
)]);
let os_name = std::env::consts::OS;
sandbox.with_files(&[FileWithContentToBeTrimmed(
&format!("test_{}.nu", os_name),
"
print 'test interpolated'
",
)]);
// Literal parentheses in quoted string
let actual1 = nu!(
cwd: dirs.test(),
r#"source "test(1).nu""#
);
assert_eq!(actual1.out, "test 1");
// Interpolation in bare word with constant
let actual2 = nu!(
cwd: dirs.test(),
r#"source test_($nu.os-info.name).nu"#
);
assert_eq!(actual2.out, "test interpolated");
});
}
#[test]
fn source_path_empty_parens() {
Playground::setup("source_empty_parens_test", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"file().nu",
"
print 'empty parens'
",
)]);
// Empty parentheses should be treated as literal when quoted
let actual = nu!(
cwd: dirs.test(),
r#"source "file().nu""#
);
assert_eq!(actual.out, "empty parens");
});
}
#[test]
fn source_path_unbalanced_parens_quoted() {
Playground::setup("source_unbalanced_parens_test", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"file(.nu",
"
print 'unbalanced open'
",
)]);
sandbox.with_files(&[FileWithContentToBeTrimmed(
"file).nu",
"
print 'unbalanced close'
",
)]);
// Unbalanced parentheses should work when quoted
let actual1 = nu!(
cwd: dirs.test(),
r#"source "file(.nu""#
);
assert_eq!(actual1.out, "unbalanced open");
let actual2 = nu!(
cwd: dirs.test(),
r#"source "file).nu""#
);
assert_eq!(actual2.out, "unbalanced close");
});
}
#[test]
fn source_path_multiple_interpolations() {
Playground::setup("source_multiple_interp_test", |dirs, sandbox| {
let os_name = std::env::consts::OS;
let arch = std::env::consts::ARCH;
sandbox.with_files(&[FileWithContentToBeTrimmed(
&format!("{}_{}.nu", os_name, arch),
"
print 'multiple interpolations'
",
)]);
// Multiple interpolations in one path using constants
let actual = nu!(
cwd: dirs.test(),
r#"source ($nu.os-info.name)_($nu.os-info.arch).nu"#
);
assert_eq!(actual.out, "multiple interpolations");
});
}
#[test]
fn source_path_interpolation_with_spaces() {
Playground::setup("source_interp_spaces_test", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"file with spaces.nu",
"
print 'spaces in name'
",
)]);
// Spaces in filename require quotes
let actual = nu!(
cwd: dirs.test(),
r#"const name = "file with spaces"; source $"($name).nu""#
);
assert_eq!(actual.out, "spaces in name");
});
}
#[test]
fn source_path_raw_string_no_interpolation() {
Playground::setup("source_raw_string_test", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"file($nu.os-info.name).nu",
"
print 'raw string'
",
)]);
// Raw strings should not interpolate
let actual = nu!(
cwd: dirs.test(),
r#"source r#'file($nu.os-info.name).nu'#"#
);
assert_eq!(actual.out, "raw string");
});
}
#[test]
fn source_circular() {
let actual = nu!(cwd: "tests/parsing/samples", "
nu source_circular_1.nu
");
assert!(actual.err.contains("nu::parser::circular_import"));
}
#[test]
fn run_nu_script_single_line() {
let actual = nu!(cwd: "tests/parsing/samples", "
nu single_line.nu
");
assert_eq!(actual.out, "5");
}
#[test]
fn run_nu_script_multiline_start_pipe() {
let actual = nu!(cwd: "tests/parsing/samples", "
nu multiline_start_pipe.nu
");
assert_eq!(actual.out, "4");
}
#[test]
fn run_nu_script_multiline_start_pipe_win() {
let actual = nu!(cwd: "tests/parsing/samples", "
nu multiline_start_pipe_win.nu
");
assert_eq!(actual.out, "3");
}
#[test]
fn run_nu_script_multiline_end_pipe() {
let actual = nu!(cwd: "tests/parsing/samples", "
nu multiline_end_pipe.nu
");
assert_eq!(actual.out, "2");
}
#[test]
fn run_nu_script_multiline_end_pipe_win() {
let actual = nu!(cwd: "tests/parsing/samples", "
nu multiline_end_pipe_win.nu
");
assert_eq!(actual.out, "3");
}
#[test]
fn parse_file_relative_to_parsed_file_simple() {
Playground::setup("relative_files_simple", |dirs, sandbox| {
sandbox
.mkdir("lol")
.mkdir("lol/lol")
.with_files(&[FileWithContentToBeTrimmed(
"lol/lol/lol.nu",
"
use ../lol_shell.nu
$env.LOL = (lol_shell ls)
",
)])
.with_files(&[FileWithContentToBeTrimmed(
"lol/lol_shell.nu",
r#"
export def ls [] { "lol" }
"#,
)]);
let actual = nu!(cwd: dirs.test(), "
source-env lol/lol/lol.nu;
$env.LOL
");
assert_eq!(actual.out, "lol");
})
}
#[test]
fn predecl_signature_single_inp_out_type() {
Playground::setup("predecl_signature_single_inp_out_type", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"spam1.nu",
"
def main [] { foo }
def foo []: nothing -> nothing { print 'foo' }
",
)]);
let actual = nu!(cwd: dirs.test(), "nu spam1.nu");
assert_eq!(actual.out, "foo");
})
}
#[test]
fn predecl_signature_multiple_inp_out_types() {
Playground::setup(
"predecl_signature_multiple_inp_out_types",
|dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"spam2.nu",
"
def main [] { foo }
def foo []: [nothing -> string, string -> string] { 'foo' }
",
)]);
let actual = nu!(cwd: dirs.test(), "nu spam2.nu");
assert_eq!(actual.out, "foo");
},
)
}
#[ignore]
#[test]
fn parse_file_relative_to_parsed_file() {
Playground::setup("relative_files", |dirs, sandbox| {
sandbox
.mkdir("lol")
.mkdir("lol/lol")
.with_files(&[FileWithContentToBeTrimmed(
"lol/lol/lol.nu",
"
source-env ../../foo.nu
use ../lol_shell.nu
overlay use ../../lol/lol_shell.nu
$env.LOL = $'($env.FOO) (lol_shell ls) (ls)'
",
)])
.with_files(&[FileWithContentToBeTrimmed(
"lol/lol_shell.nu",
r#"
export def ls [] { "lol" }
"#,
)])
.with_files(&[FileWithContentToBeTrimmed(
"foo.nu",
"
$env.FOO = 'foo'
",
)]);
let actual = nu!(cwd: dirs.test(), "
source-env lol/lol/lol.nu;
$env.LOL
");
assert_eq!(actual.out, "foo lol lol");
})
}
#[test]
fn parse_file_relative_to_parsed_file_dont_use_cwd_1() {
Playground::setup("relative_files", |dirs, sandbox| {
sandbox
.mkdir("lol")
.with_files(&[FileWithContentToBeTrimmed(
"lol/lol.nu",
"
source-env foo.nu
",
)])
.with_files(&[FileWithContentToBeTrimmed(
"lol/foo.nu",
"
$env.FOO = 'good'
",
)])
.with_files(&[FileWithContentToBeTrimmed(
"foo.nu",
"
$env.FOO = 'bad'
",
)]);
let actual = nu!(cwd: dirs.test(), "
source-env lol/lol.nu;
$env.FOO
");
assert_eq!(actual.out, "good");
})
}
#[test]
fn parse_file_relative_to_parsed_file_dont_use_cwd_2() {
Playground::setup("relative_files", |dirs, sandbox| {
sandbox
.mkdir("lol")
.with_files(&[FileWithContentToBeTrimmed(
"lol/lol.nu",
"
source-env foo.nu
",
)])
.with_files(&[FileWithContentToBeTrimmed(
"foo.nu",
"
$env.FOO = 'bad'
",
)]);
let actual = nu!(cwd: dirs.test(), "
source-env lol/lol.nu
");
assert!(actual.err.contains("File not found"));
})
}
#[test]
fn parse_export_env_in_module() {
let actual = nu!("
module spam { export-env { } }
");
assert!(actual.err.is_empty());
}
#[test]
fn parse_export_env_missing_block() {
let actual = nu!("
module spam { export-env }
");
assert!(actual.err.contains("missing block"));
}
#[test]
fn call_command_with_non_ascii_argument() {
let actual = nu!("
def nu-arg [--umlaut(-ö): int] {}
nu-arg -ö 42
");
assert_eq!(actual.err.len(), 0);
}
#[test]
fn parse_long_duration() {
let actual = nu!(r#"
"78.797877879789789sec" | into duration
"#);
assert_eq!(actual.out, "1min 18sec 797ms 877µs 879ns");
}
#[rstest]
#[case("def test [ --a: any = 32 ] {}")]
#[case("def test [ --a: number = 32 ] {}")]
#[case("def test [ --a: number = 32.0 ] {}")]
#[case("def test [ --a: list<any> = [ 1 2 3 ] ] {}")]
#[case("def test [ --a: record<a: int b: string> = { a: 32 b: 'qwe' c: 'wqe' } ] {}")]
#[case("def test [ --a: record<a: any b: any> = { a: 32 b: 'qwe'} ] {}")]
#[case("def test []: int -> int { 1 }")]
#[case("def test []: string -> string { 'qwe' }")]
#[case("def test []: nothing -> nothing { null }")]
#[case("def test []: list<string> -> list<string> { [] }")]
#[case("def test []: record<a: int b: int> -> record<c: int e: int> { {c: 1 e: 1} }")]
#[case("def test []: table<a: int b: int> -> table<c: int e: int> { [ {c: 1 e: 1} ] }")]
#[case("def test []: nothing -> record<c: int e: int> { {c: 1 e: 1} }")]
fn parse_function_signature(#[case] phrase: &str) {
let actual = nu!(phrase);
assert!(actual.err.is_empty());
}
#[rstest]
#[case("def test [ in ] {}")]
#[case("def test [ in: string ] {}")]
#[case("def test [ nu: int ] {}")]
#[case("def test [ env: record<> ] {}")]
#[case("def test [ --env ] {}")]
#[case("def test [ --nu: int ] {}")]
#[case("def test [ --in (-i): list<any> ] {}")]
#[case("def test [ a: string, b: int, in: table<a: int b: int> ] {}")]
#[case("def test [ env, in, nu ] {}")]
fn parse_function_signature_name_is_builtin_var(#[case] phrase: &str) {
let actual = nu!(phrase);
assert!(actual.err.contains("nu::parser::name_is_builtin_var"))
}
#[rstest]
#[case("let a: int = 1")]
#[case("let a: string = 'qwe'")]
#[case("let a: nothing = null")]
#[case("let a: list<string> = []")]
#[case("let a: record<a: int b: int> = {a: 1 b: 1}")]
#[case("let a: table<a: int b: int> = [[a b]; [1 2] [3 4]]")]
#[case("let a: record<a: record<name: string> b: int> = {a: {name: bob} b: 1}")]
fn parse_let_signature(#[case] phrase: &str) {
let actual = nu!(phrase);
assert!(actual.err.is_empty());
}
#[test]
fn parse_let_signature_missing_colon() {
let actual = nu!("let a int = 1");
assert!(actual.err.contains("nu::parser::extra_tokens"));
}
#[test]
fn parse_mut_signature_missing_colon() {
let actual = nu!("mut a record<a: int b: int> = {a: 1 b: 1}");
assert!(actual.err.contains("nu::parser::extra_tokens"));
}
#[test]
fn parse_const_signature_missing_colon() {
let actual = nu!("const a string = 'Hello World\n'");
assert!(actual.err.contains("nu::parser::extra_tokens"));
}
/// https://github.com/nushell/nushell/issues/16969
#[test]
fn wacky_range_parse() {
let actual = nu!(r#"0..(1..2 | first)"#);
assert!(actual.err.is_empty());
}
#[test]
fn wacky_range_parse_lt() {
let actual = nu!(r#"0..<(1..2 | first)"#);
assert!(actual.err.is_empty());
}
#[test]
fn wacky_range_parse_eq() {
let actual = nu!(r#"0..=(1..2 | first)"#);
assert!(actual.err.is_empty());
}
#[test]
fn wacky_range_parse_no_end() {
let actual = nu!(r#"..(1..2 | first)"#);
assert!(actual.err.is_empty());
}
#[test]
fn wacky_range_parse_regression() {
let actual = nu!(r#"1..(5)..10"#);
assert!(actual.err.is_empty());
}
#[test]
fn wacky_range_parse_comb() {
let actual = nu!(r#"1..(5..10 | first)..10"#);
assert!(actual.err.is_empty());
}
// Regression test https://github.com/nushell/nushell/issues/17146
#[test]
fn wacky_range_unmatched_paren() {
let actual = nu!(r#"') .."#);
assert!(!actual.err.is_empty());
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/plugin_persistence/mod.rs | tests/plugin_persistence/mod.rs | //! The tests in this file check the soundness of plugin persistence. When a plugin is needed by Nu,
//! it is spawned only if it was not already running. Plugins that are spawned are kept running and
//! are referenced in the engine state. Plugins can be stopped by the user if desired, but not
//! removed.
use nu_test_support::{nu, nu_with_plugins};
#[test]
fn plugin_list_shows_installed_plugins() {
let out = nu_with_plugins!(
cwd: ".",
plugins: [("nu_plugin_inc"), ("nu_plugin_custom_values")],
r#"(plugin list).name | str join ','"#
);
assert_eq!("custom_values,inc", out.out);
assert!(out.status.success());
}
#[test]
fn plugin_list_shows_installed_plugin_version() {
let out = nu_with_plugins!(
cwd: ".",
plugin: ("nu_plugin_inc"),
r#"(plugin list).version.0"#
);
assert_eq!(env!("CARGO_PKG_VERSION"), out.out);
assert!(out.status.success());
}
#[test]
fn plugin_keeps_running_after_calling_it() {
let out = nu_with_plugins!(
cwd: ".",
plugin: ("nu_plugin_inc"),
r#"
plugin stop inc
(plugin list).0.status == running | print
print ";"
"2.0.0" | inc -m | ignore
(plugin list).0.status == running | print
"#
);
assert_eq!(
"false;true", out.out,
"plugin list didn't show status = running"
);
assert!(out.status.success());
}
#[test]
fn plugin_process_exits_after_stop() {
let out = nu_with_plugins!(
cwd: ".",
plugin: ("nu_plugin_inc"),
r#"
"2.0.0" | inc -m | ignore
sleep 500ms
let pid = (plugin list).0.pid
if (ps | where pid == $pid | is-empty) {
error make {
msg: "plugin process not running initially"
}
}
plugin stop inc
let start = (date now)
mut cond = true
while $cond {
sleep 100ms
$cond = (
(ps | where pid == $pid | is-not-empty) and
((date now) - $start) < 5sec
)
}
((date now) - $start) | into int
"#
);
assert!(out.status.success());
let nanos = out.out.parse::<i64>().expect("not a number");
assert!(
nanos < 5_000_000_000,
"not stopped after more than 5 seconds: {nanos} ns"
);
}
#[test]
fn plugin_stop_can_find_by_filename() {
let result = nu_with_plugins!(
cwd: ".",
plugin: ("nu_plugin_inc"),
r#"plugin stop (plugin list | where name == inc).0.filename"#
);
assert!(result.status.success());
assert!(result.err.is_empty());
}
#[test]
fn plugin_process_exits_when_nushell_exits() {
let out = nu_with_plugins!(
cwd: ".",
plugin: ("nu_plugin_inc"),
r#"
"2.0.0" | inc -m | ignore
(plugin list).0.pid | print
"#
);
assert!(!out.out.is_empty());
assert!(out.status.success());
let pid = out.out.parse::<u32>().expect("failed to parse pid");
// use nu to check if process exists
assert_eq!(
"0",
nu!(format!("sleep 500ms; ps | where pid == {pid} | length")).out,
"plugin process {pid} is still running"
);
}
#[test]
fn plugin_commands_run_without_error() {
let out = nu_with_plugins!(
cwd: ".",
plugins: [
("nu_plugin_inc"),
("nu_plugin_example"),
("nu_plugin_custom_values"),
],
r#"
"2.0.0" | inc -m | ignore
example seq 1 10 | ignore
custom-value generate | ignore
"#
);
assert!(out.err.is_empty());
assert!(out.status.success());
}
#[test]
fn plugin_commands_run_multiple_times_without_error() {
let out = nu_with_plugins!(
cwd: ".",
plugins: [
("nu_plugin_inc"),
("nu_plugin_example"),
("nu_plugin_custom_values"),
],
r#"
["2.0.0" "2.1.0" "2.2.0"] | each { inc -m } | print
example seq 1 10 | ignore
custom-value generate | ignore
example seq 1 20 | ignore
custom-value generate2 | ignore
"#
);
assert!(out.err.is_empty());
assert!(out.status.success());
}
#[test]
fn multiple_plugin_commands_run_with_the_same_plugin_pid() {
let out = nu_with_plugins!(
cwd: ".",
plugin: ("nu_plugin_custom_values"),
r#"
custom-value generate | ignore
(plugin list).0.pid | print
print ";"
custom-value generate2 | ignore
(plugin list).0.pid | print
"#
);
assert!(out.status.success());
let pids: Vec<&str> = out.out.split(';').collect();
assert_eq!(2, pids.len());
assert_eq!(pids[0], pids[1]);
}
#[test]
fn plugin_pid_changes_after_stop_then_run_again() {
let out = nu_with_plugins!(
cwd: ".",
plugin: ("nu_plugin_custom_values"),
r#"
custom-value generate | ignore
(plugin list).0.pid | print
print ";"
plugin stop custom_values
custom-value generate2 | ignore
(plugin list).0.pid | print
"#
);
assert!(out.status.success());
let pids: Vec<&str> = out.out.split(';').collect();
assert_eq!(2, pids.len());
assert_ne!(pids[0], pids[1]);
}
#[test]
fn custom_values_can_still_be_passed_to_plugin_after_stop() {
let out = nu_with_plugins!(
cwd: ".",
plugin: ("nu_plugin_custom_values"),
r#"
let cv = custom-value generate
plugin stop custom_values
$cv | custom-value update
"#
);
assert!(!out.out.is_empty());
assert!(out.err.is_empty());
assert!(out.status.success());
}
#[test]
fn custom_values_can_still_be_collapsed_after_stop() {
// print causes a collapse (ToBaseValue) call.
let out = nu_with_plugins!(
cwd: ".",
plugin: ("nu_plugin_custom_values"),
r#"
let cv = custom-value generate
plugin stop custom_values
$cv | print
"#
);
assert!(!out.out.is_empty());
assert!(out.err.is_empty());
assert!(out.status.success());
}
#[test]
fn plugin_gc_can_be_configured_to_stop_plugins_immediately() {
// I know the test is to stop "immediately", but if we actually check immediately it could
// lead to a race condition. Using 100ms sleep just because with contention we don't really
// know for sure how long this could take
let out = nu_with_plugins!(
cwd: ".",
plugin: ("nu_plugin_inc"),
r#"
$env.config.plugin_gc = { default: { stop_after: 0sec } }
"2.3.0" | inc -M
sleep 100ms
(plugin list | where name == inc).0.status == running
"#
);
assert!(out.status.success());
assert_eq!("false", out.out, "with config as default");
let out = nu_with_plugins!(
cwd: ".",
plugin: ("nu_plugin_inc"),
r#"
$env.config.plugin_gc = {
plugins: {
inc: { stop_after: 0sec }
}
}
"2.3.0" | inc -M
sleep 100ms
(plugin list | where name == inc).0.status == running
"#
);
assert!(out.status.success());
assert_eq!("false", out.out, "with inc-specific config");
}
#[test]
fn plugin_gc_can_be_configured_to_stop_plugins_after_delay() {
let out = nu_with_plugins!(
cwd: ".",
plugin: ("nu_plugin_inc"),
r#"
$env.config.plugin_gc = { default: { stop_after: 50ms } }
"2.3.0" | inc -M
let start = (date now)
mut cond = true
while $cond {
sleep 100ms
$cond = (
(plugin list | where name == inc).0.status == running and
((date now) - $start) < 5sec
)
}
((date now) - $start) | into int
"#
);
assert!(out.status.success());
let nanos = out.out.parse::<i64>().expect("not a number");
assert!(
nanos < 5_000_000_000,
"with config as default: more than 5 seconds: {nanos} ns"
);
let out = nu_with_plugins!(
cwd: ".",
plugin: ("nu_plugin_inc"),
r#"
$env.config.plugin_gc = {
plugins: {
inc: { stop_after: 50ms }
}
}
"2.3.0" | inc -M
let start = (date now)
mut cond = true
while $cond {
sleep 100ms
$cond = (
(plugin list | where name == inc).0.status == running and
((date now) - $start) < 5sec
)
}
((date now) - $start) | into int
"#
);
assert!(out.status.success());
let nanos = out.out.parse::<i64>().expect("not a number");
assert!(
nanos < 5_000_000_000,
"with inc-specific config: more than 5 seconds: {nanos} ns"
);
}
#[test]
fn plugin_gc_can_be_configured_as_disabled() {
let out = nu_with_plugins!(
cwd: ".",
plugin: ("nu_plugin_inc"),
r#"
$env.config.plugin_gc = { default: { enabled: false, stop_after: 0sec } }
"2.3.0" | inc -M
(plugin list | where name == inc).0.status == running
"#
);
assert!(out.status.success());
assert_eq!("true", out.out, "with config as default");
let out = nu_with_plugins!(
cwd: ".",
plugin: ("nu_plugin_inc"),
r#"
$env.config.plugin_gc = {
default: { enabled: true, stop_after: 0sec }
plugins: {
inc: { enabled: false, stop_after: 0sec }
}
}
"2.3.0" | inc -M
(plugin list | where name == inc).0.status == running
"#
);
assert!(out.status.success());
assert_eq!("true", out.out, "with inc-specific config");
}
#[test]
fn plugin_gc_can_be_disabled_by_plugin() {
let out = nu_with_plugins!(
cwd: ".",
plugin: ("nu_plugin_example"),
r#"
example disable-gc
$env.config.plugin_gc = { default: { stop_after: 0sec } }
example one 1 foo | ignore # ensure we've run the plugin with the new config
sleep 100ms
(plugin list | where name == example).0.status == running
"#
);
assert!(out.status.success());
assert_eq!("true", out.out);
}
#[test]
fn plugin_gc_does_not_stop_plugin_while_stream_output_is_active() {
let out = nu_with_plugins!(
cwd: ".",
plugin: ("nu_plugin_example"),
r#"
$env.config.plugin_gc = { default: { stop_after: 10ms } }
# This would exceed the configured time
example seq 1 500 | each { |n| sleep 1ms; $n } | length | print
"#
);
assert!(out.status.success());
assert_eq!("500", out.out);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/hooks/mod.rs | tests/hooks/mod.rs | use nu_test_support::{nu, nu_repl_code};
use pretty_assertions::assert_eq;
fn env_change_hook_code_list(name: &str, code_list: &[&str]) -> String {
let mut list = String::new();
for code in code_list.iter() {
list.push_str("{ code: ");
list.push_str(code);
list.push_str(" }\n");
}
format!(
"$env.config = {{
hooks: {{
env_change: {{
{name} : [
{list}
]
}}
}}
}}"
)
}
fn env_change_hook(name: &str, code: &str) -> String {
format!(
"$env.config = {{
hooks: {{
env_change: {{
{name}: [{code}]
}}
}}
}}"
)
}
fn env_change_hook_code(name: &str, code: &str) -> String {
format!(
"$env.config = {{
hooks: {{
env_change: {{
{name}: [{{
code: {code}
}}]
}}
}}
}}"
)
}
fn env_change_hook_code_condition(name: &str, condition: &str, code: &str) -> String {
format!(
"$env.config = {{
hooks: {{
env_change: {{
{name}: [{{
condition: {condition}
code: {code}
}}]
}}
}}
}}"
)
}
fn pre_prompt_hook(code: &str) -> String {
format!(
"$env.config = {{
hooks: {{
pre_prompt: [{code}]
}}
}}"
)
}
fn pre_prompt_hook_code(code: &str) -> String {
format!(
"$env.config = {{
hooks: {{
pre_prompt: [{{
code: {code}
}}]
}}
}}"
)
}
fn pre_execution_hook(code: &str) -> String {
format!(
"$env.config = {{
hooks: {{
pre_execution: [{code}]
}}
}}"
)
}
fn pre_execution_hook_code(code: &str) -> String {
format!(
"$env.config = {{
hooks: {{
pre_execution: [{{
code: {code}
}}]
}}
}}"
)
}
#[test]
fn env_change_define_command() {
let inp = &[
&env_change_hook_code("FOO", r#"'def foo [] { "got foo!" }'"#),
"$env.FOO = 1",
"foo",
];
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual_repl.err, "");
assert_eq!(actual_repl.out, "got foo!");
}
#[test]
fn env_change_define_variable() {
let inp = &[
&env_change_hook_code("FOO", r#"'let x = "spam"'"#),
"$env.FOO = 1",
"$x",
];
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual_repl.err, "");
assert_eq!(actual_repl.out, "spam");
}
#[test]
fn env_change_define_env_var() {
let inp = &[
&env_change_hook_code("FOO", r#"'$env.SPAM = "spam"'"#),
"$env.FOO = 1",
"$env.SPAM",
];
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual_repl.err, "");
assert_eq!(actual_repl.out, "spam");
}
#[test]
fn env_change_define_alias() {
let inp = &[
&env_change_hook_code("FOO", r#"'alias spam = echo "spam"'"#),
"$env.FOO = 1",
"spam",
];
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual_repl.err, "");
assert_eq!(actual_repl.out, "spam");
}
#[test]
fn env_change_simple_block_preserve_env_var() {
let inp = &[
&env_change_hook("FOO", r#"{|| $env.SPAM = "spam" }"#),
"$env.FOO = 1",
"$env.SPAM",
];
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual_repl.err, "");
assert_eq!(actual_repl.out, "spam");
}
#[test]
fn env_change_simple_block_list_shadow_env_var() {
let inp = &[
&env_change_hook(
"FOO",
r#"[
{|| $env.SPAM = "foo" }
{|| $env.SPAM = "spam" }
]"#,
),
"$env.FOO = 1",
"$env.SPAM",
];
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual_repl.err, "");
assert_eq!(actual_repl.out, "spam");
}
#[test]
fn env_change_block_preserve_env_var() {
let inp = &[
&env_change_hook_code("FOO", r#"{|| $env.SPAM = "spam" }"#),
"$env.FOO = 1",
"$env.SPAM",
];
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual_repl.err, "");
assert_eq!(actual_repl.out, "spam");
}
#[test]
fn pre_prompt_define_command() {
let inp = &[
&pre_prompt_hook_code(r#"'def foo [] { "got foo!" }'"#),
"foo",
];
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual_repl.err, "");
assert_eq!(actual_repl.out, "got foo!");
}
#[test]
fn pre_prompt_simple_block_preserve_env_var() {
let inp = &[&pre_prompt_hook(r#"{|| $env.SPAM = "spam" }"#), "$env.SPAM"];
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual_repl.err, "");
assert_eq!(actual_repl.out, "spam");
}
#[test]
fn pre_prompt_simple_block_list_shadow_env_var() {
let inp = &[
&pre_prompt_hook(
r#"[
{|| $env.SPAM = "foo" }
{|| $env.SPAM = "spam" }
]"#,
),
"$env.SPAM",
];
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual_repl.err, "");
assert_eq!(actual_repl.out, "spam");
}
#[test]
fn pre_prompt_block_preserve_env_var() {
let inp = &[
&pre_prompt_hook_code(r#"{|| $env.SPAM = "spam" }"#),
"$env.SPAM",
];
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual_repl.err, "");
assert_eq!(actual_repl.out, "spam");
}
#[test]
fn pre_execution_define_command() {
let inp = &[
&pre_execution_hook_code(r#"'def foo [] { "got foo!" }'"#),
"foo",
];
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual_repl.err, "");
assert_eq!(actual_repl.out, "got foo!");
}
#[test]
fn pre_execution_simple_block_preserve_env_var() {
let inp = &[
&pre_execution_hook(r#"{|| $env.SPAM = "spam" }"#),
"$env.SPAM",
];
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual_repl.err, "");
assert_eq!(actual_repl.out, "spam");
}
#[test]
fn pre_execution_simple_block_list_shadow_env_var() {
let inp = &[
&pre_execution_hook(
r#"[
{|| $env.SPAM = "foo" }
{|| $env.SPAM = "spam" }
]"#,
),
"$env.SPAM",
];
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual_repl.err, "");
assert_eq!(actual_repl.out, "spam");
}
#[test]
fn pre_execution_block_preserve_env_var() {
let inp = &[
&pre_execution_hook_code(r#"{|| $env.SPAM = "spam" }"#),
"$env.SPAM",
];
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual_repl.err, "");
assert_eq!(actual_repl.out, "spam");
}
#[test]
fn pre_execution_commandline() {
let inp = &[
&pre_execution_hook_code("{|| $env.repl_commandline = (commandline) }"),
"$env.repl_commandline",
];
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual_repl.err, "");
assert_eq!(actual_repl.out, "$env.repl_commandline");
}
#[test]
fn env_change_shadow_command() {
let inp = &[
&env_change_hook_code_list(
"FOO",
&[
r#"'def foo [] { "got spam!" }'"#,
r#"'def foo [] { "got foo!" }'"#,
],
),
"$env.FOO = 1",
"foo",
];
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual_repl.err, "");
assert_eq!(actual_repl.out, "got foo!");
}
#[test]
fn env_change_block_dont_preserve_command() {
let inp = &[
&env_change_hook_code("FOO", r#"{|| def foo [] { "foo" } }"#),
"$env.FOO = 1",
"foo",
];
let actual_repl = nu!(nu_repl_code(inp));
#[cfg(windows)]
assert_ne!(actual_repl.out, "foo");
#[cfg(not(windows))]
assert!(actual_repl.err.contains("external_command"));
}
#[test]
fn env_change_block_condition_pwd() {
let inp = &[
&env_change_hook_code_condition(
"PWD",
"{|before, after| ($after | path basename) == samples }",
"'source-env .nu-env'",
),
"cd samples",
"$env.SPAM",
];
let actual_repl = nu!(cwd: "tests/hooks", nu_repl_code(inp));
assert_eq!(actual_repl.err, "");
assert_eq!(actual_repl.out, "spam");
}
#[test]
fn env_change_block_condition_correct_args() {
let inp = &[
"$env.FOO = 1",
&env_change_hook_code_condition(
"FOO",
"{|before, after| $before == 1 and $after == 2}",
"{|before, after| $env.SPAM = ($before == 1 and $after == 2) }",
),
"",
"$env.FOO = 2",
"$env.SPAM",
];
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual_repl.err, "");
assert_eq!(actual_repl.out, "true");
}
#[test]
fn env_change_dont_panic_with_many_args() {
let inp = &[
&env_change_hook_code("FOO", "{ |a, b, c| $env.SPAM = 'spam' }"),
"$env.FOO = 1",
"",
];
let actual_repl = nu!(nu_repl_code(inp));
assert!(actual_repl.err.contains("incompatible_parameters"));
assert_eq!(actual_repl.out, "");
}
#[test]
fn err_hook_wrong_env_type_1() {
let inp = &[
"$env.config = {
hooks: {
env_change: {
FOO : 1
}
}
}",
"$env.FOO = 1",
"",
];
let actual_repl = nu!(nu_repl_code(inp));
dbg!(&actual_repl.err);
assert!(actual_repl.err.contains("Type mismatch"));
assert_eq!(actual_repl.out, "");
}
#[test]
fn err_hook_wrong_env_type_2() {
let inp = &[
r#"$env.config = {
hooks: {
env_change: "print spam"
}
}"#,
"",
];
let actual_repl = nu!(nu_repl_code(inp));
assert!(actual_repl.err.contains("Type mismatch"));
assert_eq!(actual_repl.out, "");
}
#[test]
fn err_hook_wrong_env_type_3() {
let inp = &[
"$env.config = {
hooks: {
env_change: {
FOO : {
code: 1
}
}
}
}",
"$env.FOO = 1",
"",
];
let actual_repl = nu!(nu_repl_code(inp));
assert!(actual_repl.err.contains("Type mismatch"));
assert_eq!(actual_repl.out, "");
}
#[test]
fn err_hook_non_boolean_condition_output() {
let inp = &[
r#"$env.config = {
hooks: {
env_change: {
FOO : {
condition: {|| "foo" }
code: "print spam"
}
}
}
}"#,
"$env.FOO = 1",
"",
];
let actual_repl = nu!(nu_repl_code(inp));
assert!(actual_repl.err.contains("Type mismatch"));
assert_eq!(actual_repl.out, "");
}
#[test]
fn err_hook_non_condition_not_a_block() {
let inp = &[
r#"$env.config = {
hooks: {
env_change: {
FOO : {
condition: "foo"
code: "print spam"
}
}
}
}"#,
"$env.FOO = 1",
"",
];
let actual_repl = nu!(nu_repl_code(inp));
assert!(actual_repl.err.contains("Type mismatch"));
assert_eq!(actual_repl.out, "");
}
#[test]
fn err_hook_parse_error() {
let inp = &[
r#"$env.config = {
hooks: {
env_change: {
FOO: [{
code: "def foo { 'foo' }"
}]
}
}
}"#,
"$env.FOO = 1",
"",
];
let actual_repl = nu!(nu_repl_code(inp));
assert!(actual_repl.err.contains("source code has errors"));
assert_eq!(actual_repl.out, "");
}
#[test]
fn env_change_overlay() {
let inp = &[
"module test { export-env { $env.BAR = 2 } }",
&env_change_hook_code("FOO", "'overlay use test'"),
"$env.FOO = 1",
"$env.BAR",
];
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual_repl.out, "2");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/overlays/mod.rs | tests/overlays/mod.rs | use nu_test_support::fs::Stub::{FileWithContent, FileWithContentToBeTrimmed};
use nu_test_support::playground::Playground;
use nu_test_support::{nu, nu_repl_code};
use pretty_assertions::assert_eq;
#[test]
fn add_overlay() {
let inp = &[
r#"module spam { export def foo [] { "foo" } }"#,
"overlay use spam",
"foo",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual.out, "foo");
assert_eq!(actual_repl.out, "foo");
}
#[test]
fn add_overlay_as_new_name() {
let inp = &[
r#"module spam { export def foo [] { "foo" } }"#,
"overlay use spam as spam_new",
"foo",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual.out, "foo");
assert_eq!(actual_repl.out, "foo");
}
#[test]
fn add_overlay_twice() {
let inp = &[
r#"module spam { export def foo [] { "foo" } }"#,
"overlay use spam",
"overlay use spam",
"foo",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual.out, "foo");
assert_eq!(actual_repl.out, "foo");
}
#[test]
fn add_prefixed_overlay() {
let inp = &[
r#"module spam { export def foo [] { "foo" } }"#,
"overlay use --prefix spam",
"spam foo",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual.out, "foo");
assert_eq!(actual_repl.out, "foo");
}
#[test]
fn add_prefixed_overlay_twice() {
let inp = &[
r#"module spam { export def foo [] { "foo" } }"#,
"overlay use --prefix spam",
"overlay use --prefix spam",
"spam foo",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual.out, "foo");
assert_eq!(actual_repl.out, "foo");
}
#[test]
fn add_prefixed_overlay_mismatch_1() {
let inp = &[
r#"module spam { export def foo [] { "foo" } }"#,
"overlay use --prefix spam",
"overlay use spam",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert!(actual.err.contains("exists with a prefix"));
// Why doesn't the REPL test work with the previous expected output
assert!(actual_repl.err.contains("overlay_prefix_mismatch"));
}
#[test]
fn add_prefixed_overlay_mismatch_2() {
let inp = &[
r#"module spam { export def foo [] { "foo" } }"#,
"overlay use spam",
"overlay use --prefix spam",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert!(actual.err.contains("exists without a prefix"));
// Why doesn't the REPL test work with the previous expected output
assert!(actual_repl.err.contains("overlay_prefix_mismatch"));
}
#[test]
fn prefixed_overlay_keeps_custom_decl() {
let inp = &[
r#"module spam { export def foo [] { "foo" } }"#,
"overlay use --prefix spam",
r#"def bar [] { "bar" }"#,
"overlay hide --keep-custom spam",
"bar",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual.out, "bar");
assert_eq!(actual_repl.out, "bar");
}
#[test]
fn def_before_overlay_use_should_work() {
let inp = &[
r#"def something [] { "example" }"#,
r#"module spam { }"#,
"overlay use spam",
r#"def bar [] { "bar" }"#,
"overlay hide spam",
"bar",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert!(actual.err.contains("Command `bar` not found"));
assert!(actual_repl.err.contains("Command `bar` not found"));
}
#[test]
fn define_module_before_overlay_inside_func_should_work() {
let inp = &[
r#"
def main [] {
module spam { export def foo [] { "foo" } }
overlay use spam
def bar [] { "bar" }
overlay hide spam
bar # Returns bar
};"#,
"main",
];
let actual = nu!(&inp.join("; "));
assert!(actual.err.contains("Command `bar` not found"));
}
#[test]
fn add_overlay_env() {
let inp = &[
r#"module spam { export-env { $env.FOO = "foo" } }"#,
"overlay use spam",
"$env.FOO",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual.out, "foo");
assert_eq!(actual_repl.out, "foo");
}
#[test]
fn add_prefixed_overlay_env_no_prefix() {
let inp = &[
r#"module spam { export-env { $env.FOO = "foo" } }"#,
"overlay use --prefix spam",
"$env.FOO",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual.out, "foo");
assert_eq!(actual_repl.out, "foo");
}
#[test]
fn add_overlay_from_file_decl() {
let inp = &["overlay use samples/spam.nu", "foo"];
let actual = nu!(cwd: "tests/overlays", &inp.join("; "));
let actual_repl = nu!(cwd: "tests/overlays", nu_repl_code(inp));
assert_eq!(actual.out, "foo");
assert_eq!(actual_repl.out, "foo");
}
#[test]
fn add_overlay_from_const_file_decl() {
let inp = &["const file = 'samples/spam.nu'", "overlay use $file", "foo"];
let actual = nu!(cwd: "tests/overlays", &inp.join("; "));
assert_eq!(actual.out, "foo");
}
#[test]
fn add_overlay_from_const_module_name_decl() {
let inp = &[
r#"module spam { export def foo [] { "foo" } }"#,
"const mod = 'spam'",
"overlay use $mod",
"foo",
];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "foo");
}
#[test]
fn new_overlay_from_const_name() {
let inp = &[
"const mod = 'spam'",
"overlay new $mod",
"overlay list | last | get name",
];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "spam");
}
#[test]
fn hide_overlay_from_const_name() {
let inp = &[
"const mod = 'spam'",
"overlay new $mod",
"overlay hide $mod",
"overlay list | where active == true | get name | str join ' '",
];
let actual = nu!(&inp.join("; "));
assert!(!actual.out.contains("spam"));
}
// This one tests that the `nu_repl()` loop works correctly
#[test]
fn add_overlay_from_file_decl_cd() {
let inp = &["cd samples", "overlay use spam.nu", "foo"];
let actual_repl = nu!(cwd: "tests/overlays", nu_repl_code(inp));
assert_eq!(actual_repl.out, "foo");
}
#[test]
fn add_overlay_from_file_alias() {
let inp = &["overlay use samples/spam.nu", "bar"];
let actual = nu!(cwd: "tests/overlays", &inp.join("; "));
let actual_repl = nu!(cwd: "tests/overlays", nu_repl_code(inp));
assert_eq!(actual.out, "bar");
assert_eq!(actual_repl.out, "bar");
}
#[test]
fn add_overlay_from_file_env() {
let inp = &["overlay use samples/spam.nu", "$env.BAZ"];
let actual = nu!(cwd: "tests/overlays", &inp.join("; "));
let actual_repl = nu!(cwd: "tests/overlays", nu_repl_code(inp));
assert_eq!(actual.out, "baz");
assert_eq!(actual_repl.out, "baz");
}
#[test]
fn add_overlay_scoped() {
let inp = &[
r#"module spam { export def foo [] { "foo" } }"#,
"do { overlay use spam }",
"foo",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert!(!actual.err.is_empty());
#[cfg(windows)]
assert_ne!(actual_repl.out, "foo");
#[cfg(not(windows))]
assert!(!actual_repl.err.is_empty());
}
#[test]
fn update_overlay_from_module() {
let inp = &[
r#"module spam { export def foo [] { "foo" } }"#,
"overlay use spam",
r#"module spam { export def foo [] { "bar" } }"#,
"overlay use spam",
"foo",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual.out, "bar");
assert_eq!(actual_repl.out, "bar");
}
#[test]
fn update_overlay_from_module_env() {
let inp = &[
r#"module spam { export-env { $env.FOO = "foo" } }"#,
"overlay use spam",
r#"module spam { export-env { $env.FOO = "bar" } }"#,
"overlay use spam",
"$env.FOO",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual.out, "bar");
assert_eq!(actual_repl.out, "bar");
}
#[test]
fn overlay_use_do_not_eval_twice() {
let inp = &[
r#"module spam { export-env { $env.FOO = "foo" } }"#,
"overlay use spam",
r#"$env.FOO = "bar""#,
"overlay hide spam",
"overlay use spam",
"$env.FOO",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual.out, "bar");
assert_eq!(actual_repl.out, "bar");
}
#[test]
fn hide_overlay() {
let inp = &[
r#"module spam { export def foo [] { "foo" } }"#,
"overlay use spam",
"overlay hide spam",
"foo",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert!(!actual.err.is_empty());
#[cfg(windows)]
assert_ne!(actual_repl.out, "foo");
#[cfg(not(windows))]
assert!(!actual_repl.err.is_empty());
}
#[test]
fn hide_last_overlay() {
let inp = &[
r#"module spam { export def foo [] { "foo" } }"#,
"overlay use spam",
"overlay hide",
"foo",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert!(!actual.err.is_empty());
#[cfg(windows)]
assert_ne!(actual_repl.out, "foo");
#[cfg(not(windows))]
assert!(!actual_repl.err.is_empty());
}
#[test]
fn hide_overlay_scoped() {
let inp = &[
r#"module spam { export def foo [] { "foo" } }"#,
"overlay use spam",
"do { overlay hide spam }",
"foo",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual.out, "foo");
assert_eq!(actual_repl.out, "foo");
}
#[test]
fn hide_overlay_env() {
let inp = &[
r#"module spam { export-env { $env.FOO = "foo" } }"#,
"overlay use spam",
"overlay hide spam",
"$env.FOO",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert!(actual.err.contains("not_found"));
assert!(actual_repl.err.contains("not_found"));
}
#[test]
fn hide_overlay_scoped_env() {
let inp = &[
r#"module spam { export-env { $env.FOO = "foo" } }"#,
"overlay use spam",
"do { overlay hide spam }",
"$env.FOO",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual.out, "foo");
assert_eq!(actual_repl.out, "foo");
}
#[test]
fn list_default_overlay() {
let inp = &["overlay list | last | get name"];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual.out, "zero");
assert_eq!(actual_repl.out, "zero");
}
#[test]
fn list_last_overlay() {
let inp = &[
r#"module spam { export def foo [] { "foo" } }"#,
"overlay use spam",
"overlay list | last | get name",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual.out, "spam");
assert_eq!(actual_repl.out, "spam");
}
#[test]
fn list_overlay_scoped() {
let inp = &[
r#"module spam { export def foo [] { "foo" } }"#,
"overlay use spam",
"do { overlay list | last | get name }",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual.out, "spam");
assert_eq!(actual_repl.out, "spam");
}
#[test]
fn hide_overlay_discard_decl() {
let inp = &[
"overlay use samples/spam.nu",
r#"def bagr [] { "bagr" }"#,
"overlay hide spam",
"bagr",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert!(!actual.err.is_empty());
#[cfg(windows)]
assert_ne!(actual_repl.out, "bagr");
#[cfg(not(windows))]
assert!(!actual_repl.err.is_empty());
}
#[test]
fn hide_overlay_discard_alias() {
let inp = &[
"overlay use samples/spam.nu",
r#"alias bagr = echo "bagr""#,
"overlay hide spam",
"bagr",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert!(!actual.err.is_empty());
#[cfg(windows)]
assert_ne!(actual_repl.out, "bagr");
#[cfg(not(windows))]
assert!(!actual_repl.err.is_empty());
}
#[test]
fn hide_overlay_discard_env() {
let inp = &[
"overlay use samples/spam.nu",
"$env.BAGR = 'bagr'",
"overlay hide spam",
"$env.BAGR",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert!(actual.err.contains("not_found"));
assert!(actual_repl.err.contains("not_found"));
}
#[test]
fn hide_overlay_keep_decl() {
let inp = &[
"overlay use samples/spam.nu",
r#"def bagr [] { "bagr" }"#,
"overlay hide --keep-custom spam",
"bagr",
];
let actual = nu!(cwd: "tests/overlays", &inp.join("; "));
let actual_repl = nu!(cwd: "tests/overlays", nu_repl_code(inp));
assert!(actual.out.contains("bagr"));
assert!(actual_repl.out.contains("bagr"));
}
#[test]
fn hide_overlay_keep_alias() {
let inp = &[
"overlay use samples/spam.nu",
"alias bagr = echo 'bagr'",
"overlay hide --keep-custom spam",
"bagr",
];
let actual = nu!(cwd: "tests/overlays", &inp.join("; "));
let actual_repl = nu!(cwd: "tests/overlays", nu_repl_code(inp));
assert!(actual.out.contains("bagr"));
assert!(actual_repl.out.contains("bagr"));
}
#[test]
fn hide_overlay_dont_keep_env() {
let inp = &[
"overlay use samples/spam.nu",
"$env.BAGR = 'bagr'",
"overlay hide --keep-custom spam",
"$env.BAGR",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert!(actual.err.contains("not_found"));
assert!(actual_repl.err.contains("not_found"));
}
#[test]
fn hide_overlay_dont_keep_overwritten_decl() {
let inp = &[
"overlay use samples/spam.nu",
"def foo [] { 'bar' }",
"overlay hide --keep-custom spam",
"foo",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert!(!actual.err.is_empty());
#[cfg(windows)]
assert_ne!(actual_repl.out, "bagr");
#[cfg(not(windows))]
assert!(!actual_repl.err.is_empty());
}
#[test]
fn hide_overlay_dont_keep_overwritten_alias() {
let inp = &[
"overlay use samples/spam.nu",
"alias bar = echo `baz`",
"overlay hide --keep-custom spam",
"bar",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert!(!actual.err.is_empty());
#[cfg(windows)]
assert_ne!(actual_repl.out, "bagr");
#[cfg(not(windows))]
assert!(!actual_repl.err.is_empty());
}
#[test]
fn hide_overlay_dont_keep_overwritten_env() {
let inp = &[
"overlay use samples/spam.nu",
"$env.BAZ = 'bagr'",
"overlay hide --keep-custom spam",
"$env.BAZ",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert!(actual.err.contains("not_found"));
assert!(actual_repl.err.contains("not_found"));
}
#[test]
fn hide_overlay_keep_decl_in_latest_overlay() {
let inp = &[
"overlay use samples/spam.nu",
"def bagr [] { 'bagr' }",
"module eggs { }",
"overlay use eggs",
"overlay hide --keep-custom spam",
"bagr",
];
let actual = nu!(cwd: "tests/overlays", &inp.join("; "));
let actual_repl = nu!(cwd: "tests/overlays", nu_repl_code(inp));
assert!(actual.out.contains("bagr"));
assert!(actual_repl.out.contains("bagr"));
}
#[test]
fn hide_overlay_keep_alias_in_latest_overlay() {
let inp = &[
"overlay use samples/spam.nu",
"alias bagr = echo 'bagr'",
"module eggs { }",
"overlay use eggs",
"overlay hide --keep-custom spam",
"bagr",
];
let actual = nu!(cwd: "tests/overlays", &inp.join("; "));
let actual_repl = nu!(cwd: "tests/overlays", nu_repl_code(inp));
assert!(actual.out.contains("bagr"));
assert!(actual_repl.out.contains("bagr"));
}
#[test]
fn hide_overlay_dont_keep_env_in_latest_overlay() {
let inp = &[
"overlay use samples/spam.nu",
"$env.BAGR = 'bagr'",
"module eggs { }",
"overlay use eggs",
"overlay hide --keep-custom spam",
"$env.BAGR",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert!(actual.err.contains("not_found"));
assert!(actual_repl.err.contains("not_found"));
}
#[test]
fn preserve_overrides() {
let inp = &[
"overlay use samples/spam.nu",
r#"def foo [] { "new-foo" }"#,
"overlay hide spam",
"overlay use spam",
"foo",
];
let actual = nu!(cwd: "tests/overlays", &inp.join("; "));
let actual_repl = nu!(cwd: "tests/overlays", nu_repl_code(inp));
assert_eq!(actual.out, "new-foo");
assert_eq!(actual_repl.out, "new-foo");
}
#[test]
fn reset_overrides() {
let inp = &[
"overlay use samples/spam.nu",
r#"def foo [] { "new-foo" }"#,
"overlay hide spam",
"overlay use samples/spam.nu",
"foo",
];
let actual = nu!(cwd: "tests/overlays", &inp.join("; "));
let actual_repl = nu!(cwd: "tests/overlays", nu_repl_code(inp));
assert_eq!(actual.out, "foo");
assert_eq!(actual_repl.out, "foo");
}
#[test]
fn overlay_new() {
let inp = &["overlay new spam", "overlay list | last | get name"];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual.out, "spam");
assert_eq!(actual_repl.out, "spam");
}
#[test]
fn overlay_keep_pwd() {
let inp = &[
"overlay new spam",
"cd samples",
"overlay hide --keep-env [ PWD ] spam",
"$env.PWD | path basename",
];
let actual = nu!(cwd: "tests/overlays", &inp.join("; "));
let actual_repl = nu!(cwd: "tests/overlays", nu_repl_code(inp));
assert_eq!(actual.out, "samples");
assert_eq!(actual_repl.out, "samples");
}
#[test]
fn overlay_reactivate_with_nufile_should_not_change_pwd() {
let inp = &[
"overlay use spam.nu",
"cd ..",
"overlay hide --keep-env [ PWD ] spam",
"cd samples",
"overlay use spam.nu",
"$env.PWD | path basename",
];
let actual = nu!(cwd: "tests/overlays/samples", &inp.join("; "));
let actual_repl = nu!(cwd: "tests/overlays/samples", nu_repl_code(inp));
assert_eq!(actual.out, "samples");
assert_eq!(actual_repl.out, "samples");
}
#[test]
fn overlay_reactivate_with_module_name_should_change_pwd() {
let inp = &[
"overlay use spam.nu",
"cd ..",
"overlay hide --keep-env [ PWD ] spam",
"cd samples",
"overlay use spam",
"$env.PWD | path basename",
];
let actual = nu!(cwd: "tests/overlays/samples", &inp.join("; "));
let actual_repl = nu!(cwd: "tests/overlays/samples", nu_repl_code(inp));
assert_eq!(actual.out, "overlays");
assert_eq!(actual_repl.out, "overlays");
}
#[test]
fn overlay_wrong_rename_type() {
let inp = &["module spam {}", "overlay use spam as { echo foo }"];
let actual = nu!(&inp.join("; "));
assert!(actual.err.contains("parse_mismatch"));
}
#[test]
fn overlay_add_renamed() {
let inp = &[
r#"module spam { export def foo [] { "foo" } }"#,
"overlay use spam as eggs --prefix",
"eggs foo",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual.out, "foo");
assert_eq!(actual_repl.out, "foo");
}
#[test]
fn overlay_add_renamed_const() {
let inp = &[
r#"module spam { export def foo [] { "foo" } }"#,
"const name = 'spam'",
"const new_name = 'eggs'",
"overlay use $name as $new_name --prefix",
"eggs foo",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual.out, "foo");
assert_eq!(actual_repl.out, "foo");
}
#[test]
fn overlay_add_renamed_from_file() {
let inp = &["overlay use samples/spam.nu as eggs --prefix", "eggs foo"];
let actual = nu!(cwd: "tests/overlays", &inp.join("; "));
let actual_repl = nu!(cwd: "tests/overlays", nu_repl_code(inp));
assert_eq!(actual.out, "foo");
assert_eq!(actual_repl.out, "foo");
}
#[test]
fn overlay_cant_rename_existing_overlay() {
let inp = &[
r#"module spam { export def foo [] { "foo" } }"#,
"overlay use spam",
"overlay hide spam",
"overlay use spam as eggs",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert!(actual.err.contains("cant_add_overlay_help"));
assert!(actual_repl.err.contains("cant_add_overlay_help"));
}
#[test]
fn overlay_can_add_renamed_overlay() {
let inp = &[
r#"module spam { export def foo [] { "foo" } }"#,
"overlay use spam as eggs --prefix",
"overlay use spam --prefix",
"(spam foo) + (eggs foo)",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual.out, "foofoo");
assert_eq!(actual_repl.out, "foofoo");
}
#[test]
fn overlay_hide_renamed_overlay() {
let inp = &[
r#"module spam { export def foo-command-which-does-not-conflict [] { "foo" } }"#,
"overlay use spam as eggs",
"overlay hide eggs",
"foo-command-which-does-not-conflict",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert!(actual.err.contains("external_command"));
assert!(actual_repl.err.contains("external_command"));
}
#[test]
fn overlay_hide_restore_hidden_env() {
let inp = &[
"$env.foo = 'bar'",
"overlay new aa",
"hide-env foo",
"overlay hide aa",
"$env.foo",
];
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual_repl.out, "bar");
}
#[test]
fn overlay_hide_dont_restore_hidden_env_which_is_introduce_currently() {
let inp = &[
"overlay new aa",
"$env.foo = 'bar'",
"hide-env foo", // hide the env in overlay `aa`
"overlay hide aa",
"'foo' in $env",
];
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual_repl.out, "false");
}
#[test]
fn overlay_hide_and_add_renamed_overlay() {
let inp = &[
r#"module spam { export def foo [] { "foo" } }"#,
"overlay use spam as eggs",
"overlay hide eggs",
"overlay use eggs",
"foo",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual.out, "foo");
assert_eq!(actual_repl.out, "foo");
}
#[test]
fn overlay_use_export_env() {
let inp = &[
"module spam { export-env { $env.FOO = 'foo' } }",
"overlay use spam",
"$env.FOO",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual.out, "foo");
assert_eq!(actual_repl.out, "foo");
}
#[test]
fn overlay_use_export_env_config_affected() {
let inp = &[
"mut out = []",
"$env.config.filesize.unit = 'metric'",
"$out ++= [(20MB | into string)]",
"module spam { export-env { $env.config.filesize.unit = 'binary' } }",
"overlay use spam",
"$out ++= [(20MiB | into string)]",
r#"$out | to json --raw"#,
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual.out, r#"["20.0 MB","20.0 MiB"]"#);
assert_eq!(actual_repl.out, r#"["20.0 MB","20.0 MiB"]"#);
}
#[test]
fn overlay_hide_config_affected() {
let inp = &[
"mut out = []",
"$env.config.filesize.unit = 'metric'",
"$out ++= [(20MB | into string)]",
"module spam { export-env { $env.config.filesize.unit = 'binary' } }",
"overlay use spam",
"$out ++= [(20MiB | into string)]",
"overlay hide",
"$out ++= [(20MB | into string)]",
r#"$out | to json --raw"#,
];
// Can't hide overlay within the same source file
// let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
// assert_eq!(actual.out, r#"["20.0 MB","20.0 MiB","20.0 MB"]"#);
assert_eq!(actual_repl.out, r#"["20.0 MB","20.0 MiB","20.0 MB"]"#);
}
#[test]
fn overlay_use_after_hide_config_affected() {
let inp = &[
"mut out = []",
"$env.config.filesize.unit = 'metric'",
"$out ++= [(20MB | into string)]",
"module spam { export-env { $env.config.filesize.unit = 'binary' } }",
"overlay use spam",
"$out ++= [(20MiB | into string)]",
"overlay hide",
"$out ++= [(20MB | into string)]",
"overlay use spam",
"$out ++= [(20MiB | into string)]",
r#"$out | to json --raw"#,
];
// Can't hide overlay within the same source file
// let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
// assert_eq!(actual.out, r#"["20.0 MB","20.0 MiB","20.0 MB"]"#);
assert_eq!(
actual_repl.out,
r#"["20.0 MB","20.0 MiB","20.0 MB","20.0 MiB"]"#
);
}
#[test]
fn overlay_use_export_env_hide() {
let inp = &[
"$env.FOO = 'foo'",
"module spam { export-env { hide-env FOO } }",
"overlay use spam",
"$env.FOO",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert!(actual.err.contains("not_found"));
assert!(actual_repl.err.contains("not_found"));
}
#[test]
fn overlay_use_do_cd() {
Playground::setup("overlay_use_do_cd", |dirs, sandbox| {
sandbox
.mkdir("test1/test2")
.with_files(&[FileWithContentToBeTrimmed(
"test1/test2/spam.nu",
"
export-env { cd test1/test2 }
",
)]);
let inp = &[
"overlay use test1/test2/spam.nu",
"$env.PWD | path basename",
];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "test2");
})
}
#[test]
fn overlay_use_do_cd_file_relative() {
Playground::setup("overlay_use_do_cd_file_relative", |dirs, sandbox| {
sandbox
.mkdir("test1/test2")
.with_files(&[FileWithContentToBeTrimmed(
"test1/test2/spam.nu",
"
export-env { cd ($env.FILE_PWD | path join '..') }
",
)]);
let inp = &[
"overlay use test1/test2/spam.nu",
"$env.PWD | path basename",
];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "test1");
})
}
#[test]
fn overlay_use_dont_cd_overlay() {
Playground::setup("overlay_use_dont_cd_overlay", |dirs, sandbox| {
sandbox
.mkdir("test1/test2")
.with_files(&[FileWithContentToBeTrimmed(
"test1/test2/spam.nu",
"
export-env {
overlay new spam
cd test1/test2
overlay hide spam
}
",
)]);
let inp = &["source-env test1/test2/spam.nu", "$env.PWD | path basename"];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "overlay_use_dont_cd_overlay");
})
}
#[test]
fn overlay_use_find_scoped_module() {
Playground::setup("overlay_use_find_module_scoped", |dirs, _| {
let inp = "
do {
module spam { }
overlay use spam
overlay list | last | get name
}
";
let actual = nu!(cwd: dirs.test(), inp);
assert_eq!(actual.out, "spam");
})
}
#[test]
fn overlay_preserve_hidden_env_1() {
let inp = &[
"overlay new spam",
"$env.FOO = 'foo'",
"overlay new eggs",
"$env.FOO = 'bar'",
"hide-env FOO",
"overlay use eggs",
"$env.FOO",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual.out, "foo");
assert_eq!(actual_repl.out, "foo");
}
#[test]
fn overlay_preserve_hidden_env_2() {
let inp = &[
"overlay new spam",
"$env.FOO = 'foo'",
"overlay hide spam",
"overlay new eggs",
"$env.FOO = 'bar'",
"hide-env FOO",
"overlay hide eggs",
"overlay use spam",
"overlay use eggs",
"$env.FOO",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual.out, "foo");
assert_eq!(actual_repl.out, "foo");
}
#[test]
fn overlay_reset_hidden_env() {
let inp = &[
"overlay new spam",
"$env.FOO = 'foo'",
"overlay new eggs",
"$env.FOO = 'bar'",
"hide-env FOO",
"module eggs { export-env { $env.FOO = 'bar' } }",
"overlay use eggs",
"$env.FOO",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual.out, "bar");
assert_eq!(actual_repl.out, "bar");
}
#[ignore = "TODO: For this to work, we'd need to make predecls respect overlays"]
#[test]
fn overlay_preserve_hidden_decl() {
let inp = &[
"overlay new spam",
"def foo [] { 'foo' }",
"overlay new eggs",
"def foo [] { 'bar' }",
"hide foo",
"overlay use eggs",
"foo",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual.out, "foo");
assert_eq!(actual_repl.out, "foo");
}
#[ignore = "TODO: For this to work, we'd need to make predecls respect overlays"]
#[test]
fn overlay_preserve_hidden_alias() {
let inp = &[
"overlay new spam",
"alias foo = echo 'foo'",
"overlay new eggs",
"alias foo = echo 'bar'",
"hide foo",
"overlay use eggs",
"foo",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert_eq!(actual.out, "foo");
assert_eq!(actual_repl.out, "foo");
}
#[test]
fn overlay_trim_single_quote() {
let inp = &[
r#"module spam { export def foo [] { "foo" } }"#,
"overlay use 'spam'",
"overlay list | last | get name",
];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "spam");
}
#[test]
fn overlay_trim_single_quote_hide() {
let inp = &[
r#"module spam { export def foo [] { "foo" } }"#,
"overlay use 'spam'",
"overlay hide spam ",
"foo",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert!(!actual.err.is_empty());
#[cfg(windows)]
assert_ne!(actual_repl.out, "foo");
#[cfg(not(windows))]
assert!(!actual_repl.err.is_empty());
}
#[test]
fn overlay_trim_double_quote() {
let inp = &[
r#"module spam { export def foo [] { "foo" } }"#,
r#"overlay use "spam" "#,
"overlay list | last | get name",
];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "spam");
}
#[test]
fn overlay_trim_double_quote_hide() {
let inp = &[
r#"module spam { export def foo [] { "foo" } }"#,
r#"overlay use "spam" "#,
"overlay hide spam ",
"foo",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert!(!actual.err.is_empty());
#[cfg(windows)]
assert_ne!(actual_repl.out, "foo");
#[cfg(not(windows))]
assert!(!actual_repl.err.is_empty());
}
#[test]
fn overlay_use_and_restore_older_env_vars() {
let inp = &[
"module spam {
export-env {
let old_baz = $env.BAZ;
$env.BAZ = $old_baz + 'baz'
}
}",
"$env.BAZ = 'baz'",
"overlay use spam",
"overlay hide spam",
"$env.BAZ = 'new-baz'",
"overlay use --reload spam",
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | true |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/plugins/config.rs | tests/plugins/config.rs | use nu_test_support::nu_with_plugins;
#[test]
fn none() {
let actual = nu_with_plugins!(
cwd: "tests",
plugin: ("nu_plugin_example"),
"example config"
);
assert!(actual.err.contains("No config sent"));
}
#[test]
fn some() {
let actual = nu_with_plugins!(
cwd: "tests",
plugin: ("nu_plugin_example"),
r#"
$env.config = {
plugins: {
example: {
path: "some/path",
nested: {
bool: true,
string: "Hello Example!"
}
}
}
}
example config
"#
);
assert!(actual.out.contains("some/path"));
assert!(actual.out.contains("Hello Example!"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/plugins/stream.rs | tests/plugins/stream.rs | use rstest::rstest;
use nu_test_support::nu_with_plugins;
use pretty_assertions::assert_eq;
#[test]
fn seq_produces_stream() {
let actual = nu_with_plugins!(
cwd: "tests/fixtures/formats",
plugin: ("nu_plugin_example"),
"example seq 1 5 | describe"
);
assert_eq!(actual.out, "list<int> (stream)");
}
#[test]
fn seq_describe_no_collect_succeeds_without_error() {
// This tests to ensure that there's no error if the stream is suddenly closed
// Test several times, because this can cause different errors depending on what is written
// when the engine stops running, especially if there's partial output
for _ in 0..10 {
let actual = nu_with_plugins!(
cwd: "tests/fixtures/formats",
plugin: ("nu_plugin_example"),
"example seq 1 5 | describe --no-collect"
);
assert_eq!(actual.out, "stream");
assert_eq!(actual.err, "");
}
}
#[test]
fn seq_stream_collects_to_correct_list() {
let actual = nu_with_plugins!(
cwd: "tests/fixtures/formats",
plugin: ("nu_plugin_example"),
"example seq 1 5 | to json --raw"
);
assert_eq!(actual.out, "[1,2,3,4,5]");
let actual = nu_with_plugins!(
cwd: "tests/fixtures/formats",
plugin: ("nu_plugin_example"),
"example seq 1 0 | to json --raw"
);
assert_eq!(actual.out, "[]");
}
#[test]
fn seq_big_stream() {
// Testing big streams helps to ensure there are no deadlocking bugs
let actual = nu_with_plugins!(
cwd: "tests/fixtures/formats",
plugin: ("nu_plugin_example"),
"example seq 1 100000 | length"
);
assert_eq!(actual.out, "100000");
}
#[test]
fn sum_accepts_list_of_int() {
let actual = nu_with_plugins!(
cwd: "tests/fixtures/formats",
plugin: ("nu_plugin_example"),
"[1 2 3] | example sum"
);
assert_eq!(actual.out, "6");
}
#[test]
fn sum_accepts_list_of_float() {
let actual = nu_with_plugins!(
cwd: "tests/fixtures/formats",
plugin: ("nu_plugin_example"),
"[1.0 2.0 3.5] | example sum"
);
assert_eq!(actual.out, "6.5");
}
#[test]
fn sum_accepts_stream_of_int() {
let actual = nu_with_plugins!(
cwd: "tests/fixtures/formats",
plugin: ("nu_plugin_example"),
"seq 1 5 | example sum"
);
assert_eq!(actual.out, "15");
}
#[test]
fn sum_accepts_stream_of_float() {
let actual = nu_with_plugins!(
cwd: "tests/fixtures/formats",
plugin: ("nu_plugin_example"),
"seq 1 5 | into float | example sum"
);
assert_eq!(actual.out, "15.0");
}
#[test]
fn sum_big_stream() {
// Testing big streams helps to ensure there are no deadlocking bugs
let actual = nu_with_plugins!(
cwd: "tests/fixtures/formats",
plugin: ("nu_plugin_example"),
"seq 1 100000 | example sum"
);
assert_eq!(actual.out, "5000050000");
}
#[test]
fn collect_bytes_accepts_list_of_string() {
let actual = nu_with_plugins!(
cwd: "tests/fixtures/formats",
plugin: ("nu_plugin_example"),
"[a b] | example collect-bytes"
);
assert_eq!(actual.out, "ab");
}
#[test]
fn collect_bytes_accepts_list_of_binary() {
let actual = nu_with_plugins!(
cwd: "tests/fixtures/formats",
plugin: ("nu_plugin_example"),
"[0x[41] 0x[42]] | example collect-bytes"
);
assert_eq!(actual.out, "AB");
}
#[test]
fn collect_bytes_produces_byte_stream() {
let actual = nu_with_plugins!(
cwd: "tests/fixtures/formats",
plugin: ("nu_plugin_example"),
"[a b c] | example collect-bytes | describe"
);
assert_eq!(actual.out, "byte stream");
}
#[test]
fn collect_bytes_big_stream() {
// This in particular helps to ensure that a big stream can be both read and written at the same
// time without deadlocking
let actual = nu_with_plugins!(
cwd: "tests/fixtures/formats",
plugin: ("nu_plugin_example"),
r#"(
seq 1 10000 |
each {|i| ($i | into string) ++ (char newline) } |
example collect-bytes |
lines |
length
)"#
);
assert_eq!(actual.out, "10000");
}
#[test]
fn for_each_prints_on_stderr() {
let actual = nu_with_plugins!(
cwd: "tests/fixtures/formats",
plugin: ("nu_plugin_example"),
"[a b c] | example for-each { $in }"
);
assert_eq!(actual.err, "a\nb\nc\n");
}
#[test]
fn generate_sequence() {
let actual = nu_with_plugins!(
cwd: "tests/fixtures/formats",
plugin: ("nu_plugin_example"),
"example generate 0 { |i| if $i <= 10 { {out: $i, next: ($i + 2)} } } | to json --raw"
);
assert_eq!(actual.out, "[0,2,4,6,8,10]");
}
#[rstest]
#[timeout(std::time::Duration::from_secs(6))]
fn echo_interactivity_on_slow_pipelines() {
// This test works by putting 0 on the upstream immediately, followed by 1 after 10 seconds.
// If values aren't streamed to the plugin as they become available, `example echo` won't emit
// anything until both 0 and 1 are available. The desired behavior is that `example echo` gets
// the 0 immediately, which is consumed by `first`, allowing the pipeline to terminate early.
let actual = nu_with_plugins!(
cwd: "tests/fixtures/formats",
plugin: ("nu_plugin_example"),
r#"[1] | each { |n| sleep 10sec; $n } | prepend 0 | example echo | first"#
);
assert_eq!(actual.out, "0");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/plugins/core_inc.rs | tests/plugins/core_inc.rs | use nu_test_support::fs::Stub::FileWithContent;
use nu_test_support::nu_with_plugins;
use nu_test_support::playground::Playground;
use pretty_assertions::assert_eq;
#[test]
fn chooses_highest_increment_if_given_more_than_one() {
let actual = nu_with_plugins!(
cwd: "tests/fixtures/formats",
plugin: ("nu_plugin_inc"),
"open cargo_sample.toml | inc package.version --major --minor | get package.version"
);
assert_eq!(actual.out, "1.0.0");
let actual = nu_with_plugins!(
cwd: "tests/fixtures/formats",
plugin: ("nu_plugin_inc"),
// Regardless of order of arguments
"open cargo_sample.toml | inc package.version --minor --major | get package.version"
);
assert_eq!(actual.out, "1.0.0");
}
#[test]
fn by_one_with_field_passed() {
Playground::setup("plugin_inc_test_1", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
"sample.toml",
r#"
[package]
edition = "2018"
"#,
)]);
let actual = nu_with_plugins!(
cwd: dirs.test(),
plugin: ("nu_plugin_inc"),
"open sample.toml | inc package.edition | get package.edition"
);
assert_eq!(actual.out, "2019");
})
}
#[test]
fn by_one_with_no_field_passed() {
Playground::setup("plugin_inc_test_2", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
"sample.toml",
r#"
[package]
contributors = "2"
"#,
)]);
let actual = nu_with_plugins!(
cwd: dirs.test(),
plugin: ("nu_plugin_inc"),
"open sample.toml | get package.contributors | inc"
);
assert_eq!(actual.out, "3");
})
}
#[test]
fn semversion_major_inc() {
Playground::setup("plugin_inc_test_3", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
"sample.toml",
r#"
[package]
version = "0.1.3"
"#,
)]);
let actual = nu_with_plugins!(
cwd: dirs.test(),
plugin: ("nu_plugin_inc"),
"open sample.toml | inc package.version -M | get package.version"
);
assert_eq!(actual.out, "1.0.0");
})
}
#[test]
fn semversion_minor_inc() {
Playground::setup("plugin_inc_test_4", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
"sample.toml",
r#"
[package]
version = "0.1.3"
"#,
)]);
let actual = nu_with_plugins!(
cwd: dirs.test(),
plugin: ("nu_plugin_inc"),
"open sample.toml | inc package.version --minor | get package.version"
);
assert_eq!(actual.out, "0.2.0");
})
}
#[test]
fn semversion_patch_inc() {
Playground::setup("plugin_inc_test_5", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
"sample.toml",
r#"
[package]
version = "0.1.3"
"#,
)]);
let actual = nu_with_plugins!(
cwd: dirs.test(),
plugin: ("nu_plugin_inc"),
"open sample.toml | inc package.version --patch | get package.version"
);
assert_eq!(actual.out, "0.1.4");
})
}
#[test]
fn semversion_without_passing_field() {
Playground::setup("plugin_inc_test_6", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
"sample.toml",
r#"
[package]
version = "0.1.3"
"#,
)]);
let actual = nu_with_plugins!(
cwd: dirs.test(),
plugin: ("nu_plugin_inc"),
"open sample.toml | get package.version | inc --patch"
);
assert_eq!(actual.out, "0.1.4");
})
}
#[test]
fn explicit_flag() {
Playground::setup("plugin_inc_test_6", |dirs, _| {
let actual = nu_with_plugins!(
cwd: dirs.test(),
plugin: ("nu_plugin_inc"),
"'0.1.2' | inc --major=false --minor=true --patch=false"
);
assert_eq!(actual.out, "0.2.0");
})
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/plugins/register.rs | tests/plugins/register.rs | use nu_test_support::nu_with_plugins;
use nu_test_support::playground::Playground;
#[test]
fn help() {
Playground::setup("help", |dirs, _| {
let actual = nu_with_plugins!(
cwd: dirs.test(),
plugin: ("nu_plugin_example"),
"example one --help"
);
assert!(actual.out.contains("test example 1"));
assert!(actual.out.contains("Extra description for example one"));
})
}
#[test]
fn search_terms() {
Playground::setup("search_terms", |dirs, _| {
let actual = nu_with_plugins!(
cwd: dirs.test(),
plugin: ("nu_plugin_example"),
r#"help commands | where name == "example one" | echo $"search terms: ($in.search_terms)""#
);
assert!(actual.out.contains("search terms: [example]"));
})
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/plugins/custom_values.rs | tests/plugins/custom_values.rs | use nu_test_support::{nu_with_plugins, playground::Playground};
use pretty_assertions::assert_eq;
#[test]
fn can_get_custom_value_from_plugin_and_instantly_collapse_it() {
let actual = nu_with_plugins!(
cwd: "tests",
plugin: ("nu_plugin_custom_values"),
"custom-value generate"
);
assert_eq!(actual.out, "I used to be a custom value! My data was (abc)");
}
#[test]
fn can_get_custom_value_from_plugin_and_pass_it_over() {
let actual = nu_with_plugins!(
cwd: "tests",
plugin: ("nu_plugin_custom_values"),
"custom-value generate | custom-value update"
);
assert_eq!(
actual.out,
"I used to be a custom value! My data was (abcxyz)"
);
}
#[test]
fn can_get_custom_value_from_plugin_and_pass_it_over_as_an_argument() {
let actual = nu_with_plugins!(
cwd: "tests",
plugin: ("nu_plugin_custom_values"),
"custom-value update-arg (custom-value generate)"
);
assert_eq!(
actual.out,
"I used to be a custom value! My data was (abcxyz)"
);
}
#[test]
fn can_generate_and_updated_multiple_types_of_custom_values() {
let actual = nu_with_plugins!(
cwd: "tests",
plugin: ("nu_plugin_custom_values"),
"custom-value generate2 | custom-value update"
);
assert_eq!(
actual.out,
"I used to be a DIFFERENT custom value! (xyzabc)"
);
}
#[test]
fn can_generate_custom_value_and_pass_through_closure() {
let actual = nu_with_plugins!(
cwd: "tests",
plugin: ("nu_plugin_custom_values"),
"custom-value generate2 { custom-value update }"
);
assert_eq!(
actual.out,
"I used to be a DIFFERENT custom value! (xyzabc)"
);
}
#[test]
fn can_get_describe_plugin_custom_values() {
let actual = nu_with_plugins!(
cwd: "tests",
plugin: ("nu_plugin_custom_values"),
"custom-value generate | describe"
);
assert_eq!(actual.out, "CoolCustomValue");
}
#[test]
fn can_get_plugin_custom_value_int_cell_path() {
let zero_index = nu_with_plugins!(
cwd: "tests",
plugin: ("nu_plugin_custom_values"),
"(custom-value generate).0"
);
assert_eq!(zero_index.out, "abc");
let one_index = nu_with_plugins!(
cwd: "tests",
plugin: ("nu_plugin_custom_values"),
"(custom-value generate).1"
);
assert!(one_index.err.contains("nu::shell::access_beyond_end"));
let one_index_optional = nu_with_plugins!(
cwd: "tests",
plugin: ("nu_plugin_custom_values"),
"(custom-value generate).1? | describe"
);
assert_eq!(one_index_optional.out, "nothing");
}
#[test]
fn can_get_plugin_custom_value_string_cell_path() {
let cool = nu_with_plugins!(
cwd: "tests",
plugin: ("nu_plugin_custom_values"),
"(custom-value generate).cool"
);
assert_eq!(cool.out, "abc");
let meh = nu_with_plugins!(
cwd: "tests",
plugin: ("nu_plugin_custom_values"),
"(custom-value generate).meh"
);
assert!(meh.err.contains("nu::shell::column_not_found"));
let meh_optional = nu_with_plugins!(
cwd: "tests",
plugin: ("nu_plugin_custom_values"),
"(custom-value generate).meh? | describe"
);
assert_eq!(meh_optional.out, "nothing");
let cool_capitalized_sensitive = nu_with_plugins!(
cwd: "tests",
plugin: ("nu_plugin_custom_values"),
"(custom-value generate).COOL"
);
assert!(
cool_capitalized_sensitive
.err
.contains("nu::shell::column_not_found")
);
let cool_capitalized_insensitive = nu_with_plugins!(
cwd: "tests",
plugin: ("nu_plugin_custom_values"),
"(custom-value generate).COOL!"
);
assert_eq!(cool_capitalized_insensitive.out, "abc");
}
#[test]
fn can_sort_plugin_custom_values() {
let actual = nu_with_plugins!(
cwd: "tests",
plugin: ("nu_plugin_custom_values"),
"[(custom-value generate | custom-value update) (custom-value generate)] | sort | each { print } | ignore"
);
assert_eq!(
actual.out,
"I used to be a custom value! My data was (abc)\
I used to be a custom value! My data was (abcxyz)"
);
}
#[test]
fn can_append_plugin_custom_values() {
let actual = nu_with_plugins!(
cwd: "tests",
plugin: ("nu_plugin_custom_values"),
"(custom-value generate) ++ (custom-value generate)"
);
assert_eq!(
actual.out,
"I used to be a custom value! My data was (abcabc)"
);
}
// There are currently no custom values defined by the engine that aren't hidden behind an extra
// feature
#[cfg(feature = "sqlite")]
#[test]
fn fails_if_passing_engine_custom_values_to_plugins() {
let actual = nu_with_plugins!(
cwd: "tests/fixtures/formats",
plugin: ("nu_plugin_custom_values"),
"open sample.db | custom-value update"
);
assert!(
actual
.err
.contains("`SQLiteDatabase` cannot be sent to plugin")
);
assert!(
actual
.err
.contains("the `custom_values` plugin does not support this kind of value")
);
}
#[test]
fn fails_if_passing_custom_values_across_plugins() {
let actual = nu_with_plugins!(
cwd: "tests",
plugins: [
("nu_plugin_custom_values"),
("nu_plugin_inc")
],
"custom-value generate | inc --major"
);
assert!(
actual
.err
.contains("`CoolCustomValue` cannot be sent to plugin")
);
assert!(
actual
.err
.contains("the `inc` plugin does not support this kind of value")
);
}
#[test]
fn drop_check_custom_value_prints_message_on_drop() {
let actual = nu_with_plugins!(
cwd: "tests",
plugin: ("nu_plugin_custom_values"),
// We build an array with the value copied twice to verify that it only gets dropped once
"do { |v| [$v $v] } (custom-value drop-check 'Hello') | ignore"
);
assert_eq!(actual.err, "DropCheckValue was dropped: Hello\n");
assert!(actual.status.success());
}
#[test]
fn handle_make_then_get_success() {
// The drop notification must wait until the `handle get` call has finished in order for this
// to succeed
let actual = nu_with_plugins!(
cwd: "tests",
plugin: ("nu_plugin_custom_values"),
"42 | custom-value handle make | custom-value handle get"
);
assert_eq!(actual.out, "42");
assert!(actual.status.success());
}
#[test]
fn handle_update_several_times_doesnt_deadlock() {
// Do this in a loop to try to provoke a deadlock on drop
for _ in 0..10 {
let actual = nu_with_plugins!(
cwd: "tests",
plugin: ("nu_plugin_custom_values"),
r#"
"hEllO" |
custom-value handle make |
custom-value handle update { str upcase } |
custom-value handle update { str downcase } |
custom-value handle update { str title-case } |
custom-value handle get
"#
);
assert_eq!(actual.out, "Hello");
assert!(actual.status.success());
}
}
#[test]
fn custom_value_in_example_is_rendered() {
let actual = nu_with_plugins!(
cwd: "tests",
plugin: ("nu_plugin_custom_values"),
"custom-value generate --help"
);
assert!(
actual
.out
.contains("I used to be a custom value! My data was (abc)")
);
assert!(actual.status.success());
}
#[test]
fn custom_value_into_string() {
let actual = nu_with_plugins!(
cwd: "tests",
plugin: ("nu_plugin_custom_values"),
"custom-value generate | into string"
);
assert_eq!(actual.out, "I used to be a custom value! My data was (abc)");
}
#[test]
fn save_custom_values() {
Playground::setup("save custom values", |_, playground| {
let actual_unimplemented = nu_with_plugins!(
cwd: playground.cwd(),
plugin: ("nu_plugin_custom_values"),
"custom-value generate | save file"
);
assert!(
actual_unimplemented
.err
.contains("Custom value does not implement `save`")
);
nu_with_plugins!(
cwd: playground.cwd(),
plugin: ("nu_plugin_custom_values"),
"custom-value generate2 | save file"
);
let file_path = playground.cwd().join("file");
let content = std::fs::read_to_string(file_path).unwrap();
assert_eq!(content, "xyz"); // "xyz" is the content when using generate2
});
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/plugins/env.rs | tests/plugins/env.rs | use nu_test_support::nu_with_plugins;
#[test]
fn get_env_by_name() {
let result = nu_with_plugins!(
cwd: ".",
plugin: ("nu_plugin_example"),
r#"
$env.FOO = 'bar'
example env FOO | print
$env.FOO = 'baz'
example env FOO | print
"#
);
assert!(result.status.success());
assert_eq!("barbaz", result.out);
}
#[test]
fn get_envs() {
let result = nu_with_plugins!(
cwd: ".",
plugin: ("nu_plugin_example"),
"$env.BAZ = 'foo'; example env | get BAZ"
);
assert!(result.status.success());
assert_eq!("foo", result.out);
}
#[test]
fn get_current_dir() {
let cwd = std::env::current_dir()
.expect("failed to get current dir")
.join("tests")
.to_string_lossy()
.into_owned();
let result = nu_with_plugins!(
cwd: ".",
plugin: ("nu_plugin_example"),
"cd tests; example env --cwd"
);
assert!(result.status.success());
#[cfg(not(windows))]
assert_eq!(cwd, result.out);
#[cfg(windows)]
{
// cwd == r"e:\Study\Nushell", while result.out == r"E:\Study\Nushell"
assert_eq!(
cwd.chars().next().unwrap().to_ascii_uppercase(),
result.out.chars().next().unwrap().to_ascii_uppercase()
);
assert_eq!(cwd[1..], result.out[1..]);
}
}
#[test]
fn set_env() {
let result = nu_with_plugins!(
cwd: ".",
plugin: ("nu_plugin_example"),
"example env NUSHELL_OPINION --set=rocks; $env.NUSHELL_OPINION"
);
assert!(result.status.success());
assert_eq!("rocks", result.out);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/plugins/nu_plugin_nu_example.rs | tests/plugins/nu_plugin_nu_example.rs | use assert_cmd::Command;
#[test]
fn call() {
// Add the `nu` binaries to the path env
let path_env = std::env::join_paths(
std::iter::once(nu_test_support::fs::binaries().into()).chain(
std::env::var_os(nu_test_support::NATIVE_PATH_ENV_VAR)
.as_deref()
.map(std::env::split_paths)
.into_iter()
.flatten(),
),
)
.expect("failed to make path var");
let assert = Command::new(nu_test_support::fs::executable_path())
.env(nu_test_support::NATIVE_PATH_ENV_VAR, path_env)
.args([
"--no-config-file",
"--no-std-lib",
"--plugins",
&format!(
"[crates{0}nu_plugin_nu_example{0}nu_plugin_nu_example.nu]",
std::path::MAIN_SEPARATOR
),
"--commands",
"nu_plugin_nu_example 4242 teststring",
])
.assert()
.success();
let output = assert.get_output();
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stdout.contains("one"));
assert!(stdout.contains("two"));
assert!(stdout.contains("three"));
assert!(stderr.contains("name: nu_plugin_nu_example"));
assert!(stderr.contains("4242"));
assert!(stderr.contains("teststring"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/plugins/mod.rs | tests/plugins/mod.rs | mod call_decl;
mod config;
mod core_inc;
mod custom_values;
mod env;
mod formats;
mod nu_plugin_nu_example;
mod register;
mod registry_file;
mod stream;
mod stress_internals;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/plugins/stress_internals.rs | tests/plugins/stress_internals.rs | use std::{sync::mpsc, time::Duration};
use nu_test_support::nu_with_plugins;
fn ensure_stress_env_vars_unset() {
for (key, _) in std::env::vars_os() {
if key.to_string_lossy().starts_with("STRESS_") {
panic!("Test is running in a dirty environment: {key:?} is set");
}
}
}
#[test]
fn test_stdio() {
ensure_stress_env_vars_unset();
let result = nu_with_plugins!(
cwd: ".",
plugin: ("nu_plugin_stress_internals"),
"stress_internals"
);
assert!(result.status.success());
assert!(result.out.contains("local_socket_path: None"));
}
#[test]
fn test_local_socket() {
ensure_stress_env_vars_unset();
let result = nu_with_plugins!(
cwd: ".",
envs: vec![
("STRESS_ADVERTISE_LOCAL_SOCKET", "1"),
],
plugin: ("nu_plugin_stress_internals"),
"stress_internals"
);
assert!(result.status.success());
// Should be run once in stdio mode
assert!(result.err.contains("--stdio"));
// And then in local socket mode
assert!(result.err.contains("--local-socket"));
assert!(result.out.contains("local_socket_path: Some"));
}
#[test]
fn test_failing_local_socket_fallback() {
ensure_stress_env_vars_unset();
let result = nu_with_plugins!(
cwd: ".",
envs: vec![
("STRESS_ADVERTISE_LOCAL_SOCKET", "1"),
("STRESS_REFUSE_LOCAL_SOCKET", "1"),
],
plugin: ("nu_plugin_stress_internals"),
"stress_internals"
);
assert!(result.status.success());
// Count the number of times we do stdio/local socket
let mut count_stdio = 0;
let mut count_local_socket = 0;
for line in result.err.split('\n') {
if line.contains("--stdio") {
count_stdio += 1;
}
if line.contains("--local-socket") {
count_local_socket += 1;
}
}
// Should be run once in local socket mode
assert_eq!(1, count_local_socket, "count of --local-socket");
// Should be run twice in stdio mode, due to the fallback
assert_eq!(2, count_stdio, "count of --stdio");
// In the end it should not be running in local socket mode, but should succeed
assert!(result.out.contains("local_socket_path: None"));
}
#[test]
fn test_exit_before_hello_stdio() {
ensure_stress_env_vars_unset();
// This can deadlock if not handled properly, so we try several times and timeout
for _ in 0..5 {
let (tx, rx) = mpsc::channel();
std::thread::spawn(move || {
let result = nu_with_plugins!(
cwd: ".",
envs: vec![
("STRESS_EXIT_BEFORE_HELLO", "1"),
],
plugin: ("nu_plugin_stress_internals"),
"stress_internals"
);
let _ = tx.send(result);
});
let result = rx
.recv_timeout(Duration::from_secs(15))
.expect("timed out. probably a deadlock");
assert!(!result.status.success());
}
}
#[test]
fn test_exit_early_stdio() {
ensure_stress_env_vars_unset();
let result = nu_with_plugins!(
cwd: ".",
envs: vec![
("STRESS_EXIT_EARLY", "1"),
],
plugin: ("nu_plugin_stress_internals"),
"stress_internals"
);
assert!(!result.status.success());
assert!(result.err.contains("--stdio"));
}
#[test]
fn test_exit_early_local_socket() {
ensure_stress_env_vars_unset();
let result = nu_with_plugins!(
cwd: ".",
envs: vec![
("STRESS_ADVERTISE_LOCAL_SOCKET", "1"),
("STRESS_EXIT_EARLY", "1"),
],
plugin: ("nu_plugin_stress_internals"),
"stress_internals"
);
assert!(!result.status.success());
assert!(result.err.contains("--local-socket"));
}
#[test]
fn test_wrong_version() {
ensure_stress_env_vars_unset();
let result = nu_with_plugins!(
cwd: ".",
envs: vec![
("STRESS_WRONG_VERSION", "1"),
],
plugin: ("nu_plugin_stress_internals"),
"stress_internals"
);
assert!(!result.status.success());
assert!(result.err.contains("version"));
assert!(result.err.contains("0.0.0"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/plugins/call_decl.rs | tests/plugins/call_decl.rs | use nu_test_support::nu_with_plugins;
#[test]
fn call_to_json() {
let result = nu_with_plugins!(
cwd: ".",
plugin: ("nu_plugin_example"),
r#"
[42] | example call-decl 'to json' {indent: 4}
"#
);
assert!(result.status.success());
// newlines are removed from test output
assert_eq!("[ 42]", result.out);
}
#[test]
fn call_reduce() {
let result = nu_with_plugins!(
cwd: ".",
plugin: ("nu_plugin_example"),
r#"
[1 2 3] | example call-decl 'reduce' {fold: 10} { |it, acc| $it + $acc }
"#
);
assert!(result.status.success());
assert_eq!("16", result.out);
}
#[test]
fn call_scope_variables() {
let result = nu_with_plugins!(
cwd: ".",
plugin: ("nu_plugin_example"),
r#"
let test_var = 10
example call-decl 'scope variables' | where name == '$test_var' | length
"#
);
assert!(result.status.success());
assert_eq!("1", result.out);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/plugins/registry_file.rs | tests/plugins/registry_file.rs | use std::{fs::File, path::PathBuf};
use nu_protocol::{PluginRegistryFile, PluginRegistryItem, PluginRegistryItemData};
use nu_test_support::{fs::Stub, nu, nu_with_plugins, playground::Playground};
fn example_plugin_path() -> PathBuf {
nu_test_support::commands::ensure_plugins_built();
let bins_path = nu_test_support::fs::binaries();
nu_path::canonicalize_with(
if cfg!(windows) {
"nu_plugin_example.exe"
} else {
"nu_plugin_example"
},
bins_path,
)
.expect("nu_plugin_example not found")
}
fn valid_plugin_item_data() -> PluginRegistryItemData {
PluginRegistryItemData::Valid {
metadata: Default::default(),
commands: vec![],
}
}
#[test]
fn plugin_add_then_restart_nu() {
let result = nu_with_plugins!(
cwd: ".",
plugins: [],
&format!("
plugin add '{}'
(
^$nu.current-exe
--config $nu.config-path
--env-config $nu.env-path
--plugin-config $nu.plugin-path
--commands 'plugin list --engine | get name | to json --raw'
)
", example_plugin_path().display())
);
assert!(result.status.success());
assert_eq!(r#"["example"]"#, result.out);
}
#[test]
fn plugin_add_in_nu_plugin_dirs_const() {
let example_plugin_path = example_plugin_path();
let dirname = example_plugin_path.parent().expect("no parent");
let filename = example_plugin_path
.file_name()
.expect("no file_name")
.to_str()
.expect("not utf-8");
let result = nu_with_plugins!(
cwd: ".",
plugins: [],
&format!(
r#"
$env.NU_PLUGIN_DIRS = null
const NU_PLUGIN_DIRS = ['{0}']
plugin add '{1}'
(
^$nu.current-exe
--config $nu.config-path
--env-config $nu.env-path
--plugin-config $nu.plugin-path
--commands 'plugin list --engine | get name | to json --raw'
)
"#,
dirname.display(),
filename
)
);
assert!(result.status.success());
assert_eq!(r#"["example"]"#, result.out);
}
#[test]
fn plugin_add_in_nu_plugin_dirs_env() {
let example_plugin_path = example_plugin_path();
let dirname = example_plugin_path.parent().expect("no parent");
let filename = example_plugin_path
.file_name()
.expect("no file_name")
.to_str()
.expect("not utf-8");
let result = nu_with_plugins!(
cwd: ".",
plugins: [],
&format!(
r#"
$env.NU_PLUGIN_DIRS = ['{0}']
plugin add '{1}'
(
^$nu.current-exe
--config $nu.config-path
--env-config $nu.env-path
--plugin-config $nu.plugin-path
--commands 'plugin list --engine | get name | to json --raw'
)
"#,
dirname.display(),
filename
)
);
assert!(result.status.success());
assert_eq!(r#"["example"]"#, result.out);
}
#[test]
fn plugin_add_to_custom_path() {
let example_plugin_path = example_plugin_path();
Playground::setup("plugin add to custom path", |dirs, _playground| {
let result = nu!(
cwd: dirs.test(),
&format!("
plugin add --plugin-config test-plugin-file.msgpackz '{}'
", example_plugin_path.display())
);
assert!(result.status.success());
let contents = PluginRegistryFile::read_from(
File::open(dirs.test().join("test-plugin-file.msgpackz"))
.expect("failed to open plugin file"),
None,
)
.expect("failed to read plugin file");
assert_eq!(1, contents.plugins.len());
assert_eq!("example", contents.plugins[0].name);
})
}
#[test]
fn plugin_add_creates_missing_parent_directories() {
let example_plugin_path = example_plugin_path();
Playground::setup("plugin add creates parent dirs", |dirs, _playground| {
// Use a nested path where parent directories don't exist
let nested_path = "nested/dirs/test-plugin-file.msgpackz";
let result = nu!(
cwd: dirs.test(),
&format!("
plugin add --plugin-config {} '{}'
", nested_path, example_plugin_path.display())
);
// Should succeed instead of failing
assert!(result.status.success());
// Verify the parent directories were actually created
assert!(dirs.test().join("nested/dirs").exists());
// Verify the plugin file was created with correct contents
let contents = PluginRegistryFile::read_from(
File::open(dirs.test().join(nested_path)).expect("failed to open plugin file"),
None,
)
.expect("failed to read plugin file");
assert_eq!(1, contents.plugins.len());
assert_eq!("example", contents.plugins[0].name);
})
}
#[test]
fn plugin_rm_then_restart_nu() {
let example_plugin_path = example_plugin_path();
Playground::setup("plugin rm from custom path", |dirs, playground| {
playground.with_files(&[
Stub::FileWithContent("config.nu", ""),
Stub::FileWithContent("env.nu", ""),
]);
let file = File::create(dirs.test().join("test-plugin-file.msgpackz"))
.expect("failed to create file");
let mut contents = PluginRegistryFile::new();
contents.upsert_plugin(PluginRegistryItem {
name: "example".into(),
filename: example_plugin_path,
shell: None,
data: valid_plugin_item_data(),
});
contents.upsert_plugin(PluginRegistryItem {
name: "foo".into(),
// this doesn't exist, but it should be ok
filename: dirs.test().join("nu_plugin_foo").into(),
shell: None,
data: valid_plugin_item_data(),
});
contents
.write_to(file, None)
.expect("failed to write plugin file");
assert_cmd::Command::new(nu_test_support::fs::executable_path())
.current_dir(dirs.test())
.args([
"--no-std-lib",
"--config",
"config.nu",
"--env-config",
"env.nu",
"--plugin-config",
"test-plugin-file.msgpackz",
"--commands",
"plugin rm example",
])
.assert()
.success()
.stderr("");
assert_cmd::Command::new(nu_test_support::fs::executable_path())
.current_dir(dirs.test())
.args([
"--no-std-lib",
"--config",
"config.nu",
"--env-config",
"env.nu",
"--plugin-config",
"test-plugin-file.msgpackz",
"--commands",
"plugin list --engine | get name | to json --raw",
])
.assert()
.success()
.stdout("[\"foo\"]\n");
})
}
#[test]
fn plugin_rm_not_found() {
let result = nu_with_plugins!(
cwd: ".",
plugins: [],
r#"
plugin rm example
"#
);
assert!(!result.status.success());
assert!(result.err.contains("example"));
}
#[test]
fn plugin_rm_from_custom_path() {
let example_plugin_path = example_plugin_path();
Playground::setup("plugin rm from custom path", |dirs, _playground| {
let file = File::create(dirs.test().join("test-plugin-file.msgpackz"))
.expect("failed to create file");
let mut contents = PluginRegistryFile::new();
contents.upsert_plugin(PluginRegistryItem {
name: "example".into(),
filename: example_plugin_path,
shell: None,
data: valid_plugin_item_data(),
});
contents.upsert_plugin(PluginRegistryItem {
name: "foo".into(),
// this doesn't exist, but it should be ok
filename: dirs.test().join("nu_plugin_foo").into(),
shell: None,
data: valid_plugin_item_data(),
});
contents
.write_to(file, None)
.expect("failed to write plugin file");
let result = nu!(
cwd: dirs.test(),
"plugin rm --plugin-config test-plugin-file.msgpackz example",
);
assert!(result.status.success());
assert!(result.err.trim().is_empty());
// Check the contents after running
let contents = PluginRegistryFile::read_from(
File::open(dirs.test().join("test-plugin-file.msgpackz")).expect("failed to open file"),
None,
)
.expect("failed to read file");
assert!(!contents.plugins.iter().any(|p| p.name == "example"));
// Shouldn't remove anything else
assert!(contents.plugins.iter().any(|p| p.name == "foo"));
})
}
#[test]
fn plugin_rm_using_filename() {
let example_plugin_path = example_plugin_path();
Playground::setup("plugin rm using filename", |dirs, _playground| {
let file = File::create(dirs.test().join("test-plugin-file.msgpackz"))
.expect("failed to create file");
let mut contents = PluginRegistryFile::new();
contents.upsert_plugin(PluginRegistryItem {
name: "example".into(),
filename: example_plugin_path.clone(),
shell: None,
data: valid_plugin_item_data(),
});
contents.upsert_plugin(PluginRegistryItem {
name: "foo".into(),
// this doesn't exist, but it should be ok
filename: dirs.test().join("nu_plugin_foo").into(),
shell: None,
data: valid_plugin_item_data(),
});
contents
.write_to(file, None)
.expect("failed to write plugin file");
let result = nu!(
cwd: dirs.test(),
&format!(
"plugin rm --plugin-config test-plugin-file.msgpackz '{}'",
example_plugin_path.display()
)
);
assert!(result.status.success());
assert!(result.err.trim().is_empty());
// Check the contents after running
let contents = PluginRegistryFile::read_from(
File::open(dirs.test().join("test-plugin-file.msgpackz")).expect("failed to open file"),
None,
)
.expect("failed to read file");
assert!(!contents.plugins.iter().any(|p| p.name == "example"));
// Shouldn't remove anything else
assert!(contents.plugins.iter().any(|p| p.name == "foo"));
})
}
/// Running nu with a test plugin file that fails to parse on one plugin should just cause a warning
/// but the others should be loaded
#[test]
fn warning_on_invalid_plugin_item() {
let example_plugin_path = example_plugin_path();
Playground::setup("warning on invalid plugin item", |dirs, playground| {
playground.with_files(&[
Stub::FileWithContent("config.nu", ""),
Stub::FileWithContent("env.nu", ""),
]);
let file = File::create(dirs.test().join("test-plugin-file.msgpackz"))
.expect("failed to create file");
let mut contents = PluginRegistryFile::new();
contents.upsert_plugin(PluginRegistryItem {
name: "example".into(),
filename: example_plugin_path,
shell: None,
data: valid_plugin_item_data(),
});
contents.upsert_plugin(PluginRegistryItem {
name: "badtest".into(),
// this doesn't exist, but it should be ok
filename: dirs.test().join("nu_plugin_badtest").into(),
shell: None,
data: PluginRegistryItemData::Invalid,
});
contents
.write_to(file, None)
.expect("failed to write plugin file");
let result = assert_cmd::Command::new(nu_test_support::fs::executable_path())
.current_dir(dirs.test())
.args([
"--no-std-lib",
"--config",
"config.nu",
"--env-config",
"env.nu",
"--plugin-config",
"test-plugin-file.msgpackz",
"--commands",
"plugin list --engine | get name | to json --raw",
])
.output()
.expect("failed to run nu");
let out = String::from_utf8_lossy(&result.stdout).trim().to_owned();
let err = String::from_utf8_lossy(&result.stderr).trim().to_owned();
println!("=== stdout\n{out}\n=== stderr\n{err}");
// The code should still execute successfully
assert!(result.status.success());
// The "example" plugin should be unaffected
assert_eq!(r#"["example"]"#, out);
// The warning should be in there
assert!(err.contains("registered plugin data"));
assert!(err.contains("badtest"));
})
}
#[test]
fn plugin_use_error_not_found() {
Playground::setup("plugin use error not found", |dirs, playground| {
playground.with_files(&[
Stub::FileWithContent("config.nu", ""),
Stub::FileWithContent("env.nu", ""),
]);
// Make an empty msgpackz
let file = File::create(dirs.test().join("plugin.msgpackz"))
.expect("failed to open plugin.msgpackz");
PluginRegistryFile::default()
.write_to(file, None)
.expect("failed to write empty registry file");
let output = assert_cmd::Command::new(nu_test_support::fs::executable_path())
.current_dir(dirs.test())
.args(["--config", "config.nu"])
.args(["--env-config", "env.nu"])
.args(["--plugin-config", "plugin.msgpackz"])
.args(["--commands", "plugin use custom_values"])
.output()
.expect("failed to run nu");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("Plugin not found"));
})
}
#[test]
fn plugin_shows_up_in_default_plugin_list_after_add() {
let example_plugin_path = example_plugin_path();
let result = nu_with_plugins!(
cwd: ".",
plugins: [],
&format!(r#"
plugin add '{}'
plugin list | get status | to json --raw
"#, example_plugin_path.display())
);
assert!(result.status.success());
assert_eq!(r#"["added"]"#, result.out);
}
#[test]
fn plugin_shows_removed_after_removing() {
let example_plugin_path = example_plugin_path();
let result = nu_with_plugins!(
cwd: ".",
plugins: [],
&format!(r#"
plugin add '{}'
plugin list | get status | to json --raw
(
^$nu.current-exe
--config $nu.config-path
--env-config $nu.env-path
--plugin-config $nu.plugin-path
--commands 'plugin rm example; plugin list | get status | to json --raw'
)
"#, example_plugin_path.display())
);
assert!(result.status.success());
assert_eq!(r#"["removed"]"#, result.out);
}
#[test]
fn plugin_add_and_then_use() {
let example_plugin_path = example_plugin_path();
let result = nu_with_plugins!(
cwd: ".",
plugins: [],
&format!(r#"
plugin add '{}'
(
^$nu.current-exe
--config $nu.config-path
--env-config $nu.env-path
--plugin-config $nu.plugin-path
--commands 'plugin use example; plugin list --engine | get name | to json --raw'
)
"#, example_plugin_path.display())
);
assert!(result.status.success());
assert_eq!(r#"["example"]"#, result.out);
}
#[test]
fn plugin_add_and_then_use_by_filename() {
let example_plugin_path = example_plugin_path();
let result = nu_with_plugins!(
cwd: ".",
plugins: [],
&format!(r#"
plugin add '{0}'
(
^$nu.current-exe
--config $nu.config-path
--env-config $nu.env-path
--plugin-config $nu.plugin-path
--commands 'plugin use '{0}'; plugin list --engine | get name | to json --raw'
)
"#, example_plugin_path.display())
);
assert!(result.status.success());
assert_eq!(r#"["example"]"#, result.out);
}
#[test]
fn plugin_add_then_use_with_custom_path() {
let example_plugin_path = example_plugin_path();
Playground::setup("plugin add to custom path", |dirs, _playground| {
let result_add = nu!(
cwd: dirs.test(),
&format!("
plugin add --plugin-config test-plugin-file.msgpackz '{}'
", example_plugin_path.display())
);
assert!(result_add.status.success());
let result_use = nu!(
cwd: dirs.test(),
r#"
plugin use --plugin-config test-plugin-file.msgpackz example
plugin list --engine | get name | to json --raw
"#
);
assert!(result_use.status.success());
assert_eq!(r#"["example"]"#, result_use.out);
})
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/plugins/formats/vcf.rs | tests/plugins/formats/vcf.rs | use nu_test_support::fs::Stub::{FileWithContent, FileWithContentToBeTrimmed};
use nu_test_support::nu_with_plugins;
use nu_test_support::playground::Playground;
use pretty_assertions::assert_eq;
#[test]
fn infers_types() {
Playground::setup("filter_from_vcf_test_1", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"contacts.vcf",
r"
BEGIN:VCARD
VERSION:3.0
FN:John Doe
N:Doe;John;;;
EMAIL;TYPE=INTERNET:john.doe99@gmail.com
item1.ORG:'Alpine Ski Resort'
item1.X-ABLabel:Other
item2.TITLE:'Ski Instructor'
item2.X-ABLabel:Other
BDAY:19001106
NOTE:Facebook: john.doe.3\nWebsite: \nHometown: Cleveland\, Ohio
CATEGORIES:myContacts
END:VCARD
BEGIN:VCARD
VERSION:3.0
FN:Alex Smith
N:Smith;Alex;;;
TEL;TYPE=CELL:(890) 123-4567
CATEGORIES:Band,myContacts
END:VCARD
",
)]);
let cwd = dirs.test();
let actual = nu_with_plugins!(
cwd: cwd,
plugin: ("nu_plugin_formats"),
"open contacts.vcf | length"
);
assert_eq!(actual.out, "2");
})
}
#[test]
fn from_vcf_text_to_table() {
Playground::setup("filter_from_vcf_test_2", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"contacts.txt",
r"
BEGIN:VCARD
VERSION:3.0
FN:John Doe
N:Doe;John;;;
EMAIL;TYPE=INTERNET:john.doe99@gmail.com
item1.ORG:'Alpine Ski Resort'
item1.X-ABLabel:Other
item2.TITLE:'Ski Instructor'
item2.X-ABLabel:Other
BDAY:19001106
NOTE:Facebook: john.doe.3\nWebsite: \nHometown: Cleveland\, Ohio
CATEGORIES:myContacts
END:VCARD
",
)]);
let cwd = dirs.test();
let actual = nu_with_plugins!(
cwd: cwd,
plugin: ("nu_plugin_formats"),
r#"
open contacts.txt
| from vcf
| get properties.0
| where name == "EMAIL"
| first
| get value
"#
);
assert_eq!(actual.out, "john.doe99@gmail.com");
})
}
#[test]
fn from_vcf_text_with_linebreak_to_table() {
Playground::setup("filter_from_vcf_test_3", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
"contacts.txt",
r"BEGIN:VCARD
VERSION:3.0
FN:John Doe
N:Doe;John;;;
EMAIL;TYPE=INTERNET:john.doe99
@gmail.com
item1.ORG:'Alpine Ski Resort'
item1.X-ABLabel:Other
item2.TITLE:'Ski Instructor'
item2.X-ABLabel:Other
BDAY:19001106
NOTE:Facebook: john.doe.3\nWebsite: \nHometown: Cleveland\, Ohio
CATEGORIES:myContacts
END:VCARD",
)]);
let cwd = dirs.test();
let actual = nu_with_plugins!(
cwd: cwd,
plugin: ("nu_plugin_formats"),
r#"
open contacts.txt
| from vcf
| get properties.0
| where name == "EMAIL"
| first
| get value
"#
);
assert_eq!(actual.out, "john.doe99@gmail.com");
})
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/plugins/formats/ics.rs | tests/plugins/formats/ics.rs | use nu_test_support::fs::Stub::{FileWithContent, FileWithContentToBeTrimmed};
use nu_test_support::nu_with_plugins;
use nu_test_support::playground::Playground;
use pretty_assertions::assert_eq;
#[test]
fn infers_types() {
Playground::setup("filter_from_ics_test_1", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"calendar.ics",
r#"
BEGIN:VCALENDAR
PRODID:-//Google Inc//Google Calendar 70.9054//EN
VERSION:2.0
BEGIN:VEVENT
DTSTART:20171007T200000Z
DTEND:20171007T233000Z
DTSTAMP:20200319T182138Z
UID:4l80f6dcovnriq38g57g07btid@google.com
CREATED:20170719T202915Z
DESCRIPTION:
LAST-MODIFIED:20170930T190808Z
LOCATION:
SEQUENCE:1
STATUS:CONFIRMED
SUMMARY:Maryland Game
TRANSP:TRANSPARENT
END:VEVENT
BEGIN:VEVENT
DTSTART:20171002T010000Z
DTEND:20171002T020000Z
DTSTAMP:20200319T182138Z
UID:2v61g7mij4s7ieoubm3sjpun5d@google.com
CREATED:20171001T180103Z
DESCRIPTION:
LAST-MODIFIED:20171001T180103Z
LOCATION:
SEQUENCE:0
STATUS:CONFIRMED
SUMMARY:Halloween Wars
TRANSP:OPAQUE
END:VEVENT
END:VCALENDAR
"#,
)]);
let cwd = dirs.test();
let actual = nu_with_plugins!(
cwd: cwd,
plugin: ("nu_plugin_formats"),
"open calendar.ics | get events.0 | length"
);
assert_eq!(actual.out, "2");
})
}
#[test]
fn from_ics_text_to_table() {
Playground::setup("filter_from_ics_test_2", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"calendar.txt",
r#"
BEGIN:VCALENDAR
BEGIN:VEVENT
DTSTART:20171007T200000Z
DTEND:20171007T233000Z
DTSTAMP:20200319T182138Z
UID:4l80f6dcovnriq38g57g07btid@google.com
CREATED:20170719T202915Z
DESCRIPTION:
LAST-MODIFIED:20170930T190808Z
LOCATION:
SEQUENCE:1
STATUS:CONFIRMED
SUMMARY:Maryland Game
TRANSP:TRANSPARENT
END:VEVENT
END:VCALENDAR
"#,
)]);
let cwd = dirs.test();
let actual = nu_with_plugins!(
cwd: cwd,
plugin: ("nu_plugin_formats"),
r#"
open calendar.txt
| from ics
| get events.0
| get properties.0
| where name == "SUMMARY"
| first
| get value
"#
);
assert_eq!(actual.out, "Maryland Game");
})
}
#[test]
fn from_ics_text_with_linebreak_to_table() {
Playground::setup("filter_from_ics_test_3", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
"calendar.txt",
r#"BEGIN:VCALENDAR
BEGIN:VEVENT
DTSTART:20171007T200000Z
DTEND:20171007T233000Z
DTSTAMP:20200319T182138Z
UID:4l80f6dcovnriq38g57g07btid@google.com
CREATED:20170719T202915Z
DESCRIPTION:
LAST-MODIFIED:20170930T190808Z
LOCATION:The Restaurant n
ear the
Belltower
SEQUENCE:1
STATUS:CONFIRMED
SUMMARY:Dinner
TRANSP:TRANSPARENT
END:VEVENT
END:VCALENDAR"#,
)]);
let cwd = dirs.test();
let actual = nu_with_plugins!(
cwd: cwd,
plugin: ("nu_plugin_formats"),
r#"
open calendar.txt
| from ics
| get events.0
| get properties.0
| where name == "LOCATION"
| first
| get value
"#
);
assert_eq!(actual.out, "The Restaurant near the Belltower");
})
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/plugins/formats/ini.rs | tests/plugins/formats/ini.rs | use nu_test_support::fs::Stub::FileWithContentToBeTrimmed;
use nu_test_support::nu_with_plugins;
use nu_test_support::playground::Playground;
use pretty_assertions::assert_eq;
const TEST_CWD: &str = "tests/fixtures/formats";
#[test]
fn parses_ini() {
let actual = nu_with_plugins!(
cwd: TEST_CWD,
plugin: ("nu_plugin_formats"),
"open sample.ini | to nuon"
);
assert_eq!(
actual.out,
r#"{SectionOne: {key: value, integer: "1234", real: "3.14", "string1": "Case 1", "string2": "Case 2"}, SectionTwo: {key: "new value", integer: "5678", real: "3.14", "string1": "Case 1", "string2": "Case 2", "string3": "Case 3"}}"#
)
}
#[test]
fn parses_utf16_ini() {
let actual = nu_with_plugins!(
cwd: TEST_CWD,
plugin: ("nu_plugin_formats"),
"open ./utf16.ini --raw | decode utf-16 | from ini | get '.ShellClassInfo' | get IconIndex"
);
assert_eq!(actual.out, "-236")
}
#[test]
fn read_ini_with_missing_session() {
Playground::setup("from ini with missiong session", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"some_missing.ini",
r#"
min-width=450
max-width=820
[normal]
sound-file=/usr/share/sounds/freedesktop/stereo/dialog-information.oga
[critical]
border-color=FAB387ff
default-timeout=20
sound-file=/usr/share/sounds/freedesktop/stereo/dialog-warning.oga
"#,
)]);
let cwd = dirs.test();
let actual = nu_with_plugins!(
cwd: cwd,
plugin: ("nu_plugin_formats"),
r#"open some_missing.ini | get "".min-width "#
);
assert_eq!(actual.out, "450");
})
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/plugins/formats/mod.rs | tests/plugins/formats/mod.rs | mod eml;
mod ics;
mod ini;
mod vcf;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/plugins/formats/eml.rs | tests/plugins/formats/eml.rs | use nu_test_support::nu_with_plugins;
use pretty_assertions::assert_eq;
const TEST_CWD: &str = "tests/fixtures/formats";
// Note: the tests can only run successfully if nushell binary is in `target/debug/`
// The To field in this email is just "to@example.com", which gets parsed out as the Address. The Name is empty.
#[test]
fn from_eml_get_to_field() {
let actual = nu_with_plugins!(
cwd: TEST_CWD,
plugin: ("nu_plugin_formats"),
"open sample.eml | get To.Address"
);
assert_eq!(actual.out, "to@example.com");
let actual = nu_with_plugins!(
cwd: TEST_CWD,
plugin: ("nu_plugin_formats"),
"open sample.eml | get To | get Name"
);
assert_eq!(actual.out, "");
}
// The Reply-To field in this email is "replyto@example.com" <replyto@example.com>, meaning both the Name and Address values are identical.
#[test]
fn from_eml_get_replyto_field() {
let actual = nu_with_plugins!(
cwd: TEST_CWD,
plugin: ("nu_plugin_formats"),
"open sample.eml | get Reply-To | get Address"
);
assert_eq!(actual.out, "replyto@example.com");
let actual = nu_with_plugins!(
cwd: TEST_CWD,
plugin: ("nu_plugin_formats"),
"open sample.eml | get Reply-To | get Name"
);
assert_eq!(actual.out, "replyto@example.com");
}
#[test]
fn from_eml_get_subject_field() {
let actual = nu_with_plugins!(
cwd: TEST_CWD,
plugin: ("nu_plugin_formats"),
"open sample.eml | get Subject"
);
assert_eq!(actual.out, "Test Message");
}
#[test]
fn from_eml_get_another_header_field() {
let actual = nu_with_plugins!(
cwd: TEST_CWD,
plugin: ("nu_plugin_formats"),
"open sample.eml | get MIME-Version"
);
assert_eq!(actual.out, "1.0");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/eval/mod.rs | tests/eval/mod.rs | use fancy_regex::Regex;
use nu_test_support::{nu, playground::Playground};
#[test]
fn record_with_redefined_key() {
let actual = nu!("{x: 1, x: 2}");
assert!(actual.err.contains("redefined"));
}
#[test]
fn run_file_parse_error() {
let actual = nu!(
cwd: "tests/fixtures/eval",
"nu script.nu"
);
assert!(actual.err.contains("unknown type"));
}
enum ExpectedOut<'a> {
/// Equals a string exactly
Eq(&'a str),
/// Matches a regex
Matches(&'a str),
/// Produces an error (match regex)
Error(&'a str),
/// Drops a file that contains these contents
FileEq(&'a str, &'a str),
}
use self::ExpectedOut::*;
fn test_eval(source: &str, expected_out: ExpectedOut) {
Playground::setup("test_eval", |dirs, _playground| {
let actual = nu!(
cwd: dirs.test(),
source,
);
match expected_out {
Eq(eq) => {
assert_eq!(actual.out, eq);
assert!(actual.status.success());
}
Matches(regex) => {
let compiled_regex = Regex::new(regex).expect("regex failed to compile");
assert!(
compiled_regex.is_match(&actual.out).unwrap_or(false),
"eval out does not match: {}\n{}",
regex,
actual.out,
);
assert!(actual.status.success());
}
Error(regex) => {
let compiled_regex = Regex::new(regex).expect("regex failed to compile");
assert!(
compiled_regex.is_match(&actual.err).unwrap_or(false),
"eval err does not match: {regex}"
);
assert!(!actual.status.success());
}
FileEq(path, contents) => {
let read_contents =
std::fs::read_to_string(dirs.test().join(path)).expect("failed to read file");
assert_eq!(read_contents.trim(), contents);
assert!(actual.status.success());
}
}
});
}
#[test]
fn literal_bool() {
test_eval("true", Eq("true"))
}
#[test]
fn literal_int() {
test_eval("1", Eq("1"))
}
#[test]
fn literal_float() {
test_eval("1.5", Eq("1.5"))
}
#[test]
fn literal_filesize() {
test_eval("30MB", Eq("30.0 MB"))
}
#[test]
fn literal_duration() {
test_eval("30ms", Eq("30ms"))
}
#[test]
fn literal_binary() {
test_eval("0x[1f 2f f0]", Matches("Length.*1f.*2f.*f0"))
}
#[test]
fn literal_closure() {
test_eval("{||}", Matches("closure_"))
}
#[test]
fn literal_closure_to_nuon() {
test_eval("{||} | to nuon --serialize", Eq("\"{||}\""))
}
#[test]
fn literal_closure_to_json() {
test_eval("{||} | to json --serialize", Eq("\"{||}\""))
}
#[test]
fn literal_closure_to_toml() {
test_eval("{a: {||}} | to toml --serialize", Eq("a = \"{||}\""))
}
#[test]
fn literal_closure_to_yaml() {
test_eval("{||} | to yaml --serialize", Eq("'{||}'"))
}
#[test]
fn literal_range() {
test_eval("0..2..10", Matches("10"))
}
#[test]
fn literal_list() {
test_eval("[foo bar baz]", Matches("foo.*bar.*baz"))
}
#[test]
fn literal_record() {
test_eval("{foo: bar, baz: quux}", Matches("foo.*bar.*baz.*quux"))
}
#[test]
fn literal_table() {
test_eval("[[a b]; [1 2] [3 4]]", Matches("a.*b.*1.*2.*3.*4"))
}
#[test]
fn literal_string() {
test_eval(r#""foobar""#, Eq("foobar"))
}
#[test]
fn literal_raw_string() {
test_eval(r#"r#'bazquux'#"#, Eq("bazquux"))
}
#[test]
fn literal_date() {
test_eval("2020-01-01T00:00:00Z", Matches("2020"))
}
#[test]
fn literal_nothing() {
test_eval("null", Eq(""))
}
#[test]
fn list_spread() {
test_eval("[foo bar ...[baz quux]] | length", Eq("4"))
}
#[test]
fn record_spread() {
test_eval("{foo: bar ...{baz: quux}} | columns | length", Eq("2"))
}
#[test]
fn binary_op_example() {
test_eval(
"(([1 2] ++ [3 4]) == [1 2 3 4]) and (([1] ++ [2 3 4]) == [1 2 3 4])",
Eq("true"),
)
}
#[test]
fn range_from_expressions() {
test_eval("(1 + 1)..(2 + 2)", Matches("2.*3.*4"))
}
#[test]
fn list_from_expressions() {
test_eval(
"[('foo' | str upcase) ('BAR' | str downcase)]",
Matches("FOO.*bar"),
)
}
#[test]
fn record_from_expressions() {
test_eval("{('foo' | str upcase): 42}", Matches("FOO.*42"))
}
#[test]
fn call_spread() {
test_eval(
"echo foo bar ...[baz quux nushell]",
Matches("foo.*bar.*baz.*quux.*nushell"),
)
}
#[test]
fn call_flag() {
test_eval("print -e message", Eq("")) // should not be visible on stdout
}
#[test]
fn call_named() {
test_eval("10.123 | into string --decimals 1", Eq("10.1"))
}
#[test]
fn external_call() {
test_eval("nu --testbin cococo foo=bar baz", Eq("foo=bar baz"))
}
#[test]
fn external_call_redirect_pipe() {
test_eval(
"nu --testbin cococo foo=bar baz | str upcase",
Eq("FOO=BAR BAZ"),
)
}
#[test]
fn external_call_redirect_capture() {
test_eval(
"echo (nu --testbin cococo foo=bar baz) | str upcase",
Eq("FOO=BAR BAZ"),
)
}
#[test]
fn external_call_redirect_file() {
test_eval(
"nu --testbin cococo hello out> hello.txt",
FileEq("hello.txt", "hello"),
)
}
#[test]
fn let_variable() {
test_eval("let foo = 'test'; print $foo", Eq("test"))
}
#[test]
fn let_variable_mutate_error() {
test_eval(
"let foo = 'test'; $foo = 'bar'; print $foo",
Error("immutable"),
)
}
#[test]
fn constant() {
test_eval("const foo = 1 + 2; print $foo", Eq("3"))
}
#[test]
fn constant_assign_error() {
test_eval(
"const foo = 1 + 2; $foo = 4; print $foo",
Error("immutable"),
)
}
#[test]
fn mut_variable() {
test_eval("mut foo = 'test'; $foo = 'bar'; print $foo", Eq("bar"))
}
#[test]
fn mut_variable_append_assign() {
test_eval(
"mut foo = 'test'; $foo ++= 'bar'; print $foo",
Eq("testbar"),
)
}
#[test]
fn bind_in_variable_to_input() {
test_eval("3 | (4 + $in)", Eq("7"))
}
#[test]
fn if_true() {
test_eval("if true { 'foo' }", Eq("foo"))
}
#[test]
fn if_false() {
test_eval("if false { 'foo' } | describe", Eq("nothing"))
}
#[test]
fn if_else_true() {
test_eval("if 5 > 3 { 'foo' } else { 'bar' }", Eq("foo"))
}
#[test]
fn if_else_false() {
test_eval("if 5 < 3 { 'foo' } else { 'bar' }", Eq("bar"))
}
#[test]
fn match_empty_fallthrough() {
test_eval("match 42 { }; 'pass'", Eq("pass"))
}
#[test]
fn match_value() {
test_eval("match 1 { 1 => 'pass', 2 => 'fail' }", Eq("pass"))
}
#[test]
fn match_value_default() {
test_eval(
"match 3 { 1 => 'fail1', 2 => 'fail2', _ => 'pass' }",
Eq("pass"),
)
}
#[test]
fn match_value_fallthrough() {
test_eval("match 3 { 1 => 'fail1', 2 => 'fail2' }", Eq(""))
}
#[test]
fn match_variable() {
test_eval(
"match 'pass' { $s => { print $s }, _ => { print 'fail' } }",
Eq("pass"),
)
}
#[test]
fn match_variable_in_list() {
test_eval("match [fail pass] { [$f, $p] => { print $p } }", Eq("pass"))
}
#[test]
fn match_passthrough_input() {
test_eval(
"'yes' | match [pass fail] { [$p, ..] => (collect { |y| $y ++ $p }) }",
Eq("yespass"),
)
}
#[test]
fn while_mutate_var() {
test_eval("mut x = 2; while $x > 0 { print $x; $x -= 1 }", Eq("21"))
}
#[test]
fn for_list() {
test_eval("for v in [1 2 3] { print ($v * 2) }", Eq(r"246"))
}
#[test]
fn for_seq() {
test_eval("for v in (seq 1 4) { print ($v * 2) }", Eq("2468"))
}
#[test]
fn early_return() {
test_eval("do { return 'foo'; 'bar' }", Eq("foo"))
}
#[test]
fn early_return_from_if() {
test_eval("do { if true { return 'pass' }; 'fail' }", Eq("pass"))
}
#[test]
fn early_return_from_loop() {
test_eval("do { loop { return 'pass' } }", Eq("pass"))
}
#[test]
fn early_return_from_while() {
test_eval(
"do { let x = true; while $x { return 'pass' } }",
Eq("pass"),
)
}
#[test]
fn early_return_from_for() {
test_eval("do { for x in [pass fail] { return $x } }", Eq("pass"))
}
#[test]
fn try_no_catch() {
test_eval("try { error make { msg: foo } }; 'pass'", Eq("pass"))
}
#[test]
fn try_catch_no_var() {
test_eval(
"try { error make { msg: foo } } catch { 'pass' }",
Eq("pass"),
)
}
#[test]
fn try_catch_var() {
test_eval(
"try { error make { msg: foo } } catch { |err| $err.msg }",
Eq("foo"),
)
}
#[test]
fn try_catch_with_non_literal_closure_no_var() {
test_eval(
r#"
let error_handler = { || "pass" }
try { error make { msg: foobar } } catch $error_handler
"#,
Eq("pass"),
)
}
#[test]
fn try_catch_with_non_literal_closure() {
test_eval(
r#"
let error_handler = { |err| $err.msg }
try { error make { msg: foobar } } catch $error_handler
"#,
Eq("foobar"),
)
}
#[test]
fn try_catch_external() {
test_eval(
r#"try { nu -c 'exit 1' } catch { $env.LAST_EXIT_CODE }"#,
Eq("1"),
)
}
#[test]
fn row_condition() {
test_eval(
"[[a b]; [1 2] [3 4]] | where a < 3 | to nuon",
Eq("[[a, b]; [1, 2]]"),
)
}
#[test]
fn custom_command() {
test_eval(
r#"
def cmd [a: int, b: string = 'fail', ...c: string, --x: int] { $"($a)($b)($c)($x)" }
cmd 42 pass foo --x 30
"#,
Eq("42pass[foo]30"),
)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/modules/mod.rs | tests/modules/mod.rs | use nu_test_support::fs::Stub::{FileWithContent, FileWithContentToBeTrimmed};
use nu_test_support::playground::Playground;
use nu_test_support::{nu, nu_repl_code};
use pretty_assertions::assert_eq;
use rstest::rstest;
#[test]
fn module_private_import_decl() {
Playground::setup("module_private_import_decl", |dirs, sandbox| {
sandbox
.with_files(&[FileWithContentToBeTrimmed(
"main.nu",
"
use spam.nu foo-helper
export def foo [] { foo-helper }
",
)])
.with_files(&[FileWithContentToBeTrimmed(
"spam.nu",
r#"
def get-foo [] { "foo" }
export def foo-helper [] { get-foo }
"#,
)]);
let inp = &["use main.nu foo", "foo"];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "foo");
})
}
#[test]
fn module_private_import_alias() {
Playground::setup("module_private_import_alias", |dirs, sandbox| {
sandbox
.with_files(&[FileWithContentToBeTrimmed(
"main.nu",
"
use spam.nu foo-helper
export def foo [] { foo-helper }
",
)])
.with_files(&[FileWithContentToBeTrimmed(
"spam.nu",
r#"
export alias foo-helper = echo "foo"
"#,
)]);
let inp = &["use main.nu foo", "foo"];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "foo");
})
}
#[test]
fn module_private_import_decl_not_public() {
Playground::setup("module_private_import_decl_not_public", |dirs, sandbox| {
sandbox
.with_files(&[FileWithContentToBeTrimmed(
"main.nu",
"
use spam.nu foo-helper
",
)])
.with_files(&[FileWithContentToBeTrimmed(
"spam.nu",
r#"
def get-foo [] { "foo" }
export def foo-helper [] { get-foo }
"#,
)]);
let inp = &["use main.nu foo", "foo-helper"];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert!(!actual.err.is_empty());
})
}
#[test]
fn module_public_import_decl() {
Playground::setup("module_public_import_decl", |dirs, sandbox| {
sandbox
.with_files(&[FileWithContentToBeTrimmed(
"main.nu",
"
export use spam.nu foo
",
)])
.with_files(&[FileWithContentToBeTrimmed(
"spam.nu",
r#"
def foo-helper [] { "foo" }
export def foo [] { foo-helper }
"#,
)]);
let inp = &["use main.nu foo", "foo"];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "foo");
})
}
#[test]
fn module_public_import_alias() {
Playground::setup("module_public_import_alias", |dirs, sandbox| {
sandbox
.with_files(&[FileWithContentToBeTrimmed(
"main.nu",
"
export use spam.nu foo
",
)])
.with_files(&[FileWithContentToBeTrimmed(
"spam.nu",
r#"
export alias foo = echo "foo"
"#,
)]);
let inp = &["use main.nu foo", "foo"];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "foo");
})
}
#[test]
fn module_nested_imports() {
Playground::setup("module_nested_imports", |dirs, sandbox| {
sandbox
.with_files(&[FileWithContentToBeTrimmed(
"main.nu",
"
export use spam.nu [ foo bar ]
",
)])
.with_files(&[FileWithContentToBeTrimmed(
"spam.nu",
"
export use spam2.nu [ foo bar ]
",
)])
.with_files(&[FileWithContentToBeTrimmed(
"spam2.nu",
"
export use spam3.nu [ foo bar ]
",
)])
.with_files(&[FileWithContentToBeTrimmed(
"spam3.nu",
r#"
export def foo [] { "foo" }
export alias bar = echo "bar"
"#,
)]);
let inp1 = &["use main.nu foo", "foo"];
let inp2 = &["use main.nu bar", "bar"];
let actual = nu!(cwd: dirs.test(), &inp1.join("; "));
assert_eq!(actual.out, "foo");
let actual = nu!(cwd: dirs.test(), &inp2.join("; "));
assert_eq!(actual.out, "bar");
})
}
#[test]
fn module_nested_imports_in_dirs() {
Playground::setup("module_nested_imports_in_dirs", |dirs, sandbox| {
sandbox
.mkdir("spam")
.mkdir("spam/spam2")
.mkdir("spam/spam3")
.with_files(&[FileWithContentToBeTrimmed(
"main.nu",
"
export use spam/spam.nu [ foo bar ]
",
)])
.with_files(&[FileWithContentToBeTrimmed(
"spam/spam.nu",
"
export use spam2/spam2.nu [ foo bar ]
",
)])
.with_files(&[FileWithContentToBeTrimmed(
"spam/spam2/spam2.nu",
"
export use ../spam3/spam3.nu [ foo bar ]
",
)])
.with_files(&[FileWithContentToBeTrimmed(
"spam/spam3/spam3.nu",
r#"
export def foo [] { "foo" }
export alias bar = echo "bar"
"#,
)]);
let inp1 = &["use main.nu foo", "foo"];
let inp2 = &["use main.nu bar", "bar"];
let actual = nu!(cwd: dirs.test(), &inp1.join("; "));
assert_eq!(actual.out, "foo");
let actual = nu!(cwd: dirs.test(), &inp2.join("; "));
assert_eq!(actual.out, "bar");
})
}
#[test]
fn module_public_import_decl_prefixed() {
Playground::setup("module_public_import_decl", |dirs, sandbox| {
sandbox
.with_files(&[FileWithContentToBeTrimmed(
"main.nu",
"
export use spam.nu
",
)])
.with_files(&[FileWithContentToBeTrimmed(
"spam.nu",
r#"
def foo-helper [] { "foo" }
export def foo [] { foo-helper }
"#,
)]);
let inp = &["use main.nu", "main spam foo"];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "foo");
})
}
#[test]
fn module_nested_imports_in_dirs_prefixed() {
Playground::setup("module_nested_imports_in_dirs", |dirs, sandbox| {
sandbox
.mkdir("spam")
.mkdir("spam/spam2")
.mkdir("spam/spam3")
.with_files(&[FileWithContentToBeTrimmed(
"main.nu",
r#"
export use spam/spam.nu [ "spam2 foo" "spam2 spam3 bar" ]
"#,
)])
.with_files(&[FileWithContentToBeTrimmed(
"spam/spam.nu",
"
export use spam2/spam2.nu
",
)])
.with_files(&[FileWithContentToBeTrimmed(
"spam/spam2/spam2.nu",
"
export use ../spam3/spam3.nu
export use ../spam3/spam3.nu foo
",
)])
.with_files(&[FileWithContentToBeTrimmed(
"spam/spam3/spam3.nu",
r#"
export def foo [] { "foo" }
export alias bar = echo "bar"
"#,
)]);
let inp1 = &["use main.nu", "main spam2 foo"];
let inp2 = &[r#"use main.nu "spam2 spam3 bar""#, "spam2 spam3 bar"];
let actual = nu!(cwd: dirs.test(), &inp1.join("; "));
assert_eq!(actual.out, "foo");
let actual = nu!(cwd: dirs.test(), &inp2.join("; "));
assert_eq!(actual.out, "bar");
})
}
#[test]
fn module_import_env_1() {
Playground::setup("module_import_env_1", |dirs, sandbox| {
sandbox
.with_files(&[FileWithContentToBeTrimmed(
"main.nu",
"
export-env { source-env spam.nu }
export def foo [] { $env.FOO_HELPER }
",
)])
.with_files(&[FileWithContentToBeTrimmed(
"spam.nu",
r#"
export-env { $env.FOO_HELPER = "foo" }
"#,
)]);
let inp = &["source-env main.nu", "use main.nu foo", "foo"];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "foo");
})
}
#[test]
fn module_import_env_2() {
Playground::setup("module_import_env_2", |dirs, sandbox| {
sandbox
.with_files(&[FileWithContentToBeTrimmed(
"main.nu",
"
export-env { source-env spam.nu }
",
)])
.with_files(&[FileWithContentToBeTrimmed(
"spam.nu",
r#"
export-env { $env.FOO = "foo" }
"#,
)]);
let inp = &["source-env main.nu", "$env.FOO"];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "foo");
})
}
#[test]
fn module_cyclical_imports_0() {
Playground::setup("module_cyclical_imports_0", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"spam.nu",
"
use eggs.nu
",
)]);
let inp = &["module eggs { use spam.nu }"];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert!(actual.err.contains("Module not found"));
})
}
#[test]
fn module_cyclical_imports_1() {
Playground::setup("module_cyclical_imports_1", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"spam.nu",
"
use spam.nu
",
)]);
let inp = &["use spam.nu"];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert!(actual.err.contains("cyclical"));
})
}
#[test]
fn module_cyclical_imports_2() {
Playground::setup("module_cyclical_imports_2", |dirs, sandbox| {
sandbox
.with_files(&[FileWithContentToBeTrimmed(
"spam.nu",
"
use eggs.nu
",
)])
.with_files(&[FileWithContentToBeTrimmed(
"eggs.nu",
"
use spam.nu
",
)]);
let inp = &["use spam.nu"];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert!(actual.err.contains("cyclical"));
})
}
#[test]
fn module_cyclical_imports_3() {
Playground::setup("module_cyclical_imports_3", |dirs, sandbox| {
sandbox
.with_files(&[FileWithContentToBeTrimmed(
"spam.nu",
"
use eggs.nu
",
)])
.with_files(&[FileWithContentToBeTrimmed(
"eggs.nu",
"
use bacon.nu
",
)])
.with_files(&[FileWithContentToBeTrimmed(
"bacon.nu",
"
use spam.nu
",
)]);
let inp = &["use spam.nu"];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert!(actual.err.contains("cyclical"));
})
}
#[test]
fn module_import_const_file() {
Playground::setup("module_import_const_file", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"spam.nu",
r#"
export def foo [] { "foo" }
"#,
)]);
let inp = &["const file = 'spam.nu'", "use $file foo", "foo"];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "foo");
})
}
#[test]
fn module_import_const_module_name() {
Playground::setup("module_import_const_file", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"spam.nu",
r#"
export def foo [] { "foo" }
"#,
)]);
let inp = &[
r#"module spam { export def foo [] { "foo" } }"#,
"const mod = 'spam'",
"use $mod foo",
"foo",
];
let actual = nu!(cwd: dirs.test(), &inp.join("; "));
assert_eq!(actual.out, "foo");
})
}
#[test]
fn module_valid_def_name() {
let inp = &[r#"module spam { def spam [] { "spam" } }"#];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "");
}
#[test]
fn module_invalid_def_name() {
let inp = &[r#"module spam { export def spam [] { "spam" } }"#];
let actual = nu!(&inp.join("; "));
assert!(actual.err.contains("named_as_module"));
}
#[test]
fn module_valid_alias_name_1() {
let inp = &[r#"module spam { alias spam = echo "spam" }"#];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "");
}
#[test]
fn module_valid_alias_name_2() {
let inp = &[r#"module spam { alias main = echo "spam" }"#];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "");
}
#[test]
fn module_invalid_alias_name() {
let inp = &[r#"module spam { export alias spam = echo "spam" }"#];
let actual = nu!(&inp.join("; "));
assert!(actual.err.contains("named_as_module"));
}
#[test]
fn module_main_alias_not_allowed() {
let inp = &["module spam { export alias main = echo 'spam' }"];
let actual = nu!(&inp.join("; "));
assert!(actual.err.contains("export_main_alias_not_allowed"));
}
#[test]
fn module_valid_known_external_name() {
let inp = &["module spam { extern spam [] }"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "");
}
#[test]
fn module_invalid_known_external_name() {
let inp = &["module spam { export extern spam [] }"];
let actual = nu!(&inp.join("; "));
assert!(actual.err.contains("named_as_module"));
}
#[test]
fn main_inside_module_is_main() {
let inp = &[
"module spam {
export def main [] { 'foo' };
export def foo [] { main }
}",
"use spam foo",
"foo",
];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "foo");
}
#[test]
fn module_as_file() {
let inp = &["module samples/spam.nu", "use spam foo", "foo"];
let actual = nu!(cwd: "tests/modules", &inp.join("; "));
assert_eq!(actual.out, "foo");
}
#[test]
fn export_module_as_file() {
let inp = &["export module samples/spam.nu", "use spam foo", "foo"];
let actual = nu!(cwd: "tests/modules", &inp.join("; "));
assert_eq!(actual.out, "foo");
}
#[test]
fn deep_import_patterns() {
let module_decl = "
module spam {
export module eggs {
export module beans {
export def foo [] { 'foo' };
export def bar [] { 'bar' }
};
};
}
";
let inp = &[module_decl, "use spam", "spam eggs beans foo"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "foo");
let inp = &[module_decl, "use spam eggs", "eggs beans foo"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "foo");
let inp = &[module_decl, "use spam eggs beans", "beans foo"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "foo");
let inp = &[module_decl, "use spam eggs beans foo", "foo"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "foo");
}
#[rstest]
fn deep_import_aliased_external_args(
#[values(
"use spam; spam eggs beans foo bar",
"use spam eggs; eggs beans foo bar",
"use spam eggs beans; beans foo bar",
"use spam eggs beans foo; foo bar"
)]
input: &str,
) {
let module_decl = "
module spam {
export module eggs {
export module beans {
export alias foo = ^echo
}
}
}
";
let actual = nu!(format!("{module_decl}; {input}"));
assert_eq!(actual.out, "bar");
}
#[test]
fn module_dir() {
let import = "use samples/spam";
let inp = &[import, "spam"];
let actual = nu!(cwd: "tests/modules", &inp.join("; "));
assert_eq!(actual.out, "spam");
let inp = &[import, "spam foo"];
let actual = nu!(cwd: "tests/modules", &inp.join("; "));
assert_eq!(actual.out, "foo");
let inp = &[import, "spam bar"];
let actual = nu!(cwd: "tests/modules", &inp.join("; "));
assert_eq!(actual.out, "bar");
let inp = &[import, "spam foo baz"];
let actual = nu!(cwd: "tests/modules", &inp.join("; "));
assert_eq!(actual.out, "foobaz");
let inp = &[import, "spam bar baz"];
let actual = nu!(cwd: "tests/modules", &inp.join("; "));
assert_eq!(actual.out, "barbaz");
let inp = &[import, "spam baz"];
let actual = nu!(cwd: "tests/modules", &inp.join("; "));
assert_eq!(actual.out, "spambaz");
}
#[test]
fn module_dir_deep() {
let import = "use samples/spam";
let inp = &[import, "spam bacon"];
let actual_repl = nu!(cwd: "tests/modules", &inp.join("; "));
assert_eq!(actual_repl.out, "bacon");
let inp = &[import, "spam bacon foo"];
let actual_repl = nu!(cwd: "tests/modules", &inp.join("; "));
assert_eq!(actual_repl.out, "bacon foo");
let inp = &[import, "spam bacon beans"];
let actual_repl = nu!(cwd: "tests/modules", &inp.join("; "));
assert_eq!(actual_repl.out, "beans");
let inp = &[import, "spam bacon beans foo"];
let actual_repl = nu!(cwd: "tests/modules", &inp.join("; "));
assert_eq!(actual_repl.out, "beans foo");
}
#[test]
fn module_dir_import_twice_no_panic() {
let import = "use samples/spam";
let inp = &[import, import, "spam"];
let actual_repl = nu!(cwd: "tests/modules", nu_repl_code(inp));
assert_eq!(actual_repl.out, "spam");
}
#[test]
fn module_dir_missing_mod_nu() {
let inp = &["use samples/missing_mod_nu"];
let actual = nu!(cwd: "tests/modules", &inp.join("; "));
assert!(actual.err.contains("module_missing_mod_nu_file"));
}
#[test]
fn allowed_local_module() {
let inp = &["module spam { module spam {} }"];
let actual = nu!(&inp.join("; "));
assert!(actual.err.is_empty());
}
#[test]
fn not_allowed_submodule() {
let inp = &["module spam { export module spam {} }"];
let actual = nu!(&inp.join("; "));
assert!(actual.err.contains("named_as_module"));
}
#[test]
fn module_self_name() {
let inp = &[
"module spam { export module mod { export def main [] { 'spam' } } }",
"use spam",
"spam",
];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "spam");
}
#[test]
fn module_self_name_main_not_allowed() {
let inp = &[
"module spam {
export def main [] { 'main spam' };
export module mod {
export def main [] { 'mod spam' }
}
}",
"use spam",
"spam",
];
let actual = nu!(&inp.join("; "));
assert!(actual.err.contains("module_double_main"));
let inp = &[
"module spam {
export module mod {
export def main [] { 'mod spam' }
};
export def main [] { 'main spam' }
}",
"use spam",
"spam",
];
let actual = nu!(&inp.join("; "));
assert!(actual.err.contains("module_double_main"));
}
#[test]
fn module_main_not_found() {
let inp = &["module spam {}", "use spam main"];
let actual = nu!(&inp.join("; "));
assert!(actual.err.contains("export_not_found"));
let inp = &["module spam {}", "use spam [ main ]"];
let actual = nu!(&inp.join("; "));
assert!(actual.err.contains("export_not_found"));
}
#[test]
fn nested_list_export_works() {
let module = r#"
module spam {
export module eggs {
export def bacon [] { 'bacon' }
}
export def sausage [] { 'sausage' }
}
"#;
let inp = &[module, "use spam [sausage eggs]", "eggs bacon"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "bacon");
}
#[test]
fn reload_submodules() {
Playground::setup("reload_submodule_changed_file", |dirs, sandbox| {
sandbox.with_files(&[
FileWithContent("voice.nu", r#"export module animals.nu"#),
FileWithContent("animals.nu", "export def cat [] { 'meow'}"),
]);
let inp = [
"use voice.nu",
r#""export def cat [] {'woem'}" | save -f animals.nu"#,
"use voice.nu",
"(voice animals cat) == 'woem'",
];
let actual = nu!(cwd: dirs.test(), nu_repl_code(&inp));
assert_eq!(actual.out, "true");
// should also verify something unchanged if `use voice`.
let inp = [
"use voice.nu",
r#""export def cat [] {'meow'}" | save -f animals.nu"#,
"use voice",
"(voice animals cat) == 'woem'",
];
let actual = nu!(cwd: dirs.test(), nu_repl_code(&inp));
assert_eq!(actual.out, "true");
// should also works if we use members directly.
sandbox.with_files(&[
FileWithContent("voice.nu", r#"export module animals.nu"#),
FileWithContent("animals.nu", "export def cat [] { 'meow'}"),
]);
let inp = [
"use voice.nu animals cat",
r#""export def cat [] {'woem'}" | save -f animals.nu"#,
"use voice.nu animals cat",
"(cat) == 'woem'",
];
let actual = nu!(cwd: dirs.test(), nu_repl_code(&inp));
assert_eq!(actual.out, "true");
});
}
#[test]
fn use_submodules() {
Playground::setup("use_submodules", |dirs, sandbox| {
sandbox.with_files(&[
FileWithContent("voice.nu", r#"export use animals.nu"#),
FileWithContent("animals.nu", "export def cat [] { 'meow'}"),
]);
let inp = [
"use voice.nu",
r#""export def cat [] {'woem'}" | save -f animals.nu"#,
"use voice.nu",
"(voice animals cat) == 'woem'",
];
let actual = nu!(cwd: dirs.test(), nu_repl_code(&inp));
assert_eq!(actual.out, "true");
// should also verify something unchanged if `use voice`.
let inp = [
"use voice.nu",
r#""export def cat [] {'meow'}" | save -f animals.nu"#,
"use voice",
"(voice animals cat) == 'woem'",
];
let actual = nu!(cwd: dirs.test(), nu_repl_code(&inp));
assert_eq!(actual.out, "true");
// also verify something is changed when using members.
sandbox.with_files(&[
FileWithContent("voice.nu", r#"export use animals.nu cat"#),
FileWithContent("animals.nu", "export def cat [] { 'meow'}"),
]);
let inp = [
"use voice.nu",
r#""export def cat [] {'woem'}" | save -f animals.nu"#,
"use voice.nu",
"(voice cat) == 'woem'",
];
let actual = nu!(cwd: dirs.test(), nu_repl_code(&inp));
assert_eq!(actual.out, "true");
sandbox.with_files(&[
FileWithContent("voice.nu", r#"export use animals.nu *"#),
FileWithContent("animals.nu", "export def cat [] { 'meow'}"),
]);
let inp = [
"use voice.nu",
r#""export def cat [] {'woem'}" | save -f animals.nu"#,
"use voice.nu",
"(voice cat) == 'woem'",
];
let actual = nu!(cwd: dirs.test(), nu_repl_code(&inp));
assert_eq!(actual.out, "true");
sandbox.with_files(&[
FileWithContent("voice.nu", r#"export use animals.nu [cat]"#),
FileWithContent("animals.nu", "export def cat [] { 'meow'}"),
]);
let inp = [
"use voice.nu",
r#""export def cat [] {'woem'}" | save -f animals.nu"#,
"use voice.nu",
"(voice cat) == 'woem'",
];
let actual = nu!(cwd: dirs.test(), nu_repl_code(&inp));
assert_eq!(actual.out, "true");
});
}
#[test]
fn use_nested_submodules() {
Playground::setup("use_submodules", |dirs, sandbox| {
sandbox.with_files(&[
FileWithContent("voice.nu", r#"export use animals.nu"#),
FileWithContent("animals.nu", r#"export use nested_animals.nu"#),
FileWithContent("nested_animals.nu", "export def cat [] { 'meow'}"),
]);
let inp = [
"use voice.nu",
r#""export def cat [] {'woem'}" | save -f nested_animals.nu"#,
"use voice.nu",
"(voice animals nested_animals cat) == 'woem'",
];
let actual = nu!(cwd: dirs.test(), nu_repl_code(&inp));
assert_eq!(actual.out, "true");
sandbox.with_files(&[
FileWithContent("voice.nu", r#"export use animals.nu"#),
FileWithContent("animals.nu", r#"export use nested_animals.nu cat"#),
FileWithContent("nested_animals.nu", "export def cat [] { 'meow'}"),
]);
let inp = [
"use voice.nu",
r#""export def cat [] {'woem'}" | save -f nested_animals.nu"#,
"use voice.nu",
"(voice animals cat) == 'woem'",
];
let actual = nu!(cwd: dirs.test(), nu_repl_code(&inp));
assert_eq!(actual.out, "true");
sandbox.with_files(&[
FileWithContent("animals.nu", r#"export use nested_animals.nu cat"#),
FileWithContent("nested_animals.nu", "export def cat [] { 'meow' }"),
]);
let inp = [
"module voice { export module animals.nu }",
"use voice",
r#""export def cat [] {'woem'}" | save -f nested_animals.nu"#,
"use voice.nu",
"(voice animals cat) == 'woem'",
];
let actual = nu!(cwd: dirs.test(), nu_repl_code(&inp));
assert_eq!(actual.out, "true");
})
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/const_/mod.rs | tests/const_/mod.rs | use nu_test_support::nu;
use pretty_assertions::assert_eq;
use rstest::rstest;
const MODULE_SETUP: &str = r#"
module spam {
export const X = 'x'
export module eggs {
export const E = 'e'
export module bacon {
export const viking = 'eats'
export module none {}
}
}
}
"#;
#[test]
fn const_bool() {
let inp = &["const x = false", "$x"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "false");
}
#[test]
fn const_int() {
let inp = &["const x = 10", "$x"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "10");
}
#[test]
fn const_float() {
let inp = &["const x = 1.234", "$x"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "1.234");
}
#[test]
fn const_binary() {
let inp = &["const x = 0x[12]", "$x"];
let actual = nu!(&inp.join("; "));
assert!(actual.out.contains("12"));
}
#[test]
fn const_datetime() {
let inp = &["const x = 2021-02-27T13:55:40+00:00", "$x"];
let actual = nu!(&inp.join("; "));
assert!(actual.out.contains("Sat, 27 Feb 2021 13:55:40"));
}
#[test]
fn const_list() {
let inp = &["const x = [ a b c ]", "$x | describe"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "list<string>");
}
#[test]
fn const_record() {
let inp = &["const x = { a: 10, b: 20, c: 30 }", "$x | describe"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "record<a: int, b: int, c: int>");
}
#[test]
fn const_table() {
let inp = &[
"const x = [[a b c]; [10 20 30] [100 200 300]]",
"$x | describe",
];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "table<a: int, b: int, c: int>");
}
#[test]
fn const_invalid_table() {
let inp = &["const x = [[a b a]; [10 20 30] [100 200 300]]"];
let actual = nu!(&inp.join("; "));
assert!(actual.err.contains("column_defined_twice"));
}
#[test]
fn const_string() {
let inp = &[r#"const x = "abc""#, "$x"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "abc");
}
#[test]
fn const_string_interpolation_var() {
let actual = nu!(r#"const x = 2; const s = $"($x)"; $s"#);
assert_eq!(actual.out, "2");
}
#[test]
fn const_string_interpolation_date() {
let actual = nu!(r#"const s = $"(2021-02-27T13:55:40+00:00)"; $s"#);
assert!(actual.out.contains("Sat, 27 Feb 2021 13:55:40 +0000"));
}
#[test]
fn const_string_interpolation_filesize() {
let actual = nu!(r#"const s = $"(2kB)"; $s"#);
assert_eq!(actual.out, "2.0 kB");
}
#[test]
fn const_nothing() {
let inp = &["const x = null", "$x | describe"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "nothing");
}
#[rstest]
#[case(&["const x = not false", "$x"], "true")]
#[case(&["const x = false", "const y = not $x", "$y"], "true")]
#[case(&["const x = not false", "const y = not $x", "$y"], "false")]
fn const_unary_operator(#[case] inp: &[&str], #[case] expect: &str) {
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, expect);
}
#[rstest]
#[case(&["const x = 1 + 2", "$x"], "3")]
#[case(&["const x = 1 * 2", "$x"], "2")]
#[case(&["const x = 4 / 2", "$x"], "2.0")]
#[case(&["const x = 4 mod 3", "$x"], "1")]
#[case(&["const x = 5.0 / 2.0", "$x"], "2.5")]
#[case(&[r#"const x = "a" + "b" "#, "$x"], "ab")]
#[case(&[r#"const x = "a" ++ "b" "#, "$x"], "ab")]
#[case(&[r#"const x = [1,2] ++ [3]"#, "$x | describe"], "list<int>")]
#[case(&[r#"const x = 0x[1,2] ++ 0x[3]"#, "$x | describe"], "binary")]
#[case(&["const x = 1 < 2", "$x"], "true")]
#[case(&["const x = (3 * 200) > (2 * 100)", "$x"], "true")]
#[case(&["const x = (3 * 200) < (2 * 100)", "$x"], "false")]
#[case(&["const x = (3 * 200) == (2 * 300)", "$x"], "true")]
fn const_binary_operator(#[case] inp: &[&str], #[case] expect: &str) {
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, expect);
}
#[rstest]
#[case(&["const x = 1 / 0", "$x"], "division by zero")]
#[case(&["const x = 10 ** 10000000", "$x"], "pow operation overflowed")]
#[case(&["const x = 2 ** 62 * 2", "$x"], "multiply operation overflowed")]
#[case(&["const x = 1 ++ 0", "$x"], "nu::parser::operator_unsupported_type")]
fn const_operator_error(#[case] inp: &[&str], #[case] expect: &str) {
let actual = nu!(&inp.join("; "));
assert!(actual.err.contains(expect));
}
#[rstest]
#[case(&["const x = (1..3)", "$x | math sum"], "6")]
#[case(&["const x = (1..3)", "$x | describe"], "range")]
fn const_range(#[case] inp: &[&str], #[case] expect: &str) {
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, expect);
}
#[test]
fn const_subexpression_supported() {
let inp = &["const x = ('spam')", "$x"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "spam");
}
#[test]
fn const_command_supported() {
let inp = &["const x = ('spam' | str length)", "$x"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "4");
}
#[test]
fn const_command_unsupported() {
let inp = &["const x = (loop { break })"];
let actual = nu!(&inp.join("; "));
assert!(actual.err.contains("not_a_const_command"));
}
#[test]
fn const_in_scope() {
let inp = &["do { const x = 'x'; $x }"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "x");
}
#[test]
fn not_a_const_help() {
let actual = nu!("const x = ('abc' | str length -h)");
assert!(actual.err.contains("not_a_const_help"));
}
#[test]
fn complex_const_export() {
let inp = &[MODULE_SETUP, "use spam", "$spam.X"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "x");
let inp = &[MODULE_SETUP, "use spam", "$spam.eggs.E"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "e");
let inp = &[MODULE_SETUP, "use spam", "$spam.eggs.bacon.viking"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "eats");
let inp = &[MODULE_SETUP, "use spam", "'none' in $spam.eggs.bacon"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "false");
}
#[test]
fn only_nested_module_have_const() {
let setup = r#"
module spam {
export module eggs {
export module bacon {
export const viking = 'eats'
export module none {}
}
}
}
"#;
let inp = &[setup, "use spam", "$spam.eggs.bacon.viking"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "eats");
let inp = &[setup, "use spam", "'none' in $spam.eggs.bacon"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "false");
}
#[test]
fn complex_const_glob_export() {
let inp = &[MODULE_SETUP, "use spam *", "$X"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "x");
let inp = &[MODULE_SETUP, "use spam *", "$eggs.E"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "e");
let inp = &[MODULE_SETUP, "use spam *", "$eggs.bacon.viking"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "eats");
let inp = &[MODULE_SETUP, "use spam *", "'none' in $eggs.bacon"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "false");
}
#[test]
fn complex_const_drill_export() {
let inp = &[MODULE_SETUP, "use spam eggs bacon none", "$none"];
let actual = nu!(&inp.join("; "));
assert!(actual.err.contains("variable not found"));
}
#[test]
fn complex_const_list_export() {
let inp = &[
MODULE_SETUP,
"use spam [X eggs]",
"[$X $eggs.E] | str join ''",
];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "xe");
}
#[test]
fn exported_const_is_const() {
let module1 = "module foo {
export def main [] { 'foo' }
}";
let module2 = "module spam {
export const MOD_NAME = 'foo'
}";
let inp = &[module1, module2, "use spam", "use $spam.MOD_NAME", "foo"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "foo");
}
#[test]
fn const_captures_work() {
let module = "module spam {
export const X = 'x'
const Y = 'y'
export-env { $env.SPAM = $X + $Y }
export def main [] { $X + $Y }
}";
let inp = &[module, "use spam", "$env.SPAM"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "xy");
let inp = &[module, "use spam", "spam"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "xy");
}
#[test]
fn const_captures_in_closures_work() {
let module = "module foo {
const a = 'world'
export def bar [] {
'hello ' + $a
}
}";
let inp = &[module, "use foo", "do { foo bar }"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "hello world");
}
#[test]
fn complex_const_overlay_use() {
let inp = &[MODULE_SETUP, "overlay use spam", "$X"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "x");
let inp = &[MODULE_SETUP, "overlay use spam", "$eggs.E"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "e");
let inp = &[MODULE_SETUP, "overlay use spam", "$eggs.bacon.viking"];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "eats");
let inp = &[
MODULE_SETUP,
"overlay use spam",
"($eggs.bacon not-has 'none')",
];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "true");
}
#[ignore = "TODO: `overlay hide` should be possible to use after `overlay use` in the same source unit."]
#[test]
fn overlay_use_hide_in_single_source_unit() {
let inp = &[MODULE_SETUP, "overlay use spam", "overlay hide", "$eggs"];
let actual = nu!(&inp.join("; "));
assert!(actual.err.contains("nu::parser::variable_not_found"));
}
// const implementations of commands without dedicated tests
#[test]
fn describe_const() {
let actual = nu!("const x = ('abc' | describe); $x");
assert_eq!(actual.out, "string");
}
#[test]
fn ignore_const() {
let actual = nu!(r#"const x = ("spam" | ignore); $x == null"#);
assert_eq!(actual.out, "true");
}
#[test]
fn version_const() {
let actual = nu!("const x = (version); $x");
assert!(actual.err.is_empty());
}
#[test]
fn if_const() {
let actual = nu!("const x = (if 2 < 3 { 'yes!' }); $x");
assert_eq!(actual.out, "yes!");
let actual = nu!("const x = (if 5 < 3 { 'yes!' } else { 'no!' }); $x");
assert_eq!(actual.out, "no!");
let actual =
nu!("const x = (if 5 < 3 { 'yes!' } else if 4 < 5 { 'no!' } else { 'okay!' }); $x");
assert_eq!(actual.out, "no!");
}
#[rstest]
#[case(&"const x = if true ()", "expected block, found nothing")]
#[case(&"const x = if true {foo: bar}", "expected block, found record")]
#[case(&"const x = if true {1: 2}", "expected block")]
fn if_const_error(#[case] inp: &str, #[case] expect: &str) {
let actual = nu!(inp);
assert!(actual.err.contains(expect));
}
#[test]
fn const_glob_type() {
let actual = nu!("const x: glob = 'aa'; $x | describe");
assert_eq!(actual.out, "glob");
}
#[test]
fn const_raw_string() {
let actual = nu!(r#"const x = r#'abcde""fghi"''''jkl'#; $x"#);
assert_eq!(actual.out, r#"abcde""fghi"''''jkl"#);
let actual = nu!(r#"const x = r##'abcde""fghi"''''#jkl'##; $x"#);
assert_eq!(actual.out, r#"abcde""fghi"''''#jkl"#);
let actual = nu!(r#"const x = r###'abcde""fghi"'''##'#jkl'###; $x"#);
assert_eq!(actual.out, r#"abcde""fghi"'''##'#jkl"#);
let actual = nu!(r#"const x = r#'abc'#; $x"#);
assert_eq!(actual.out, "abc");
}
#[test]
fn const_takes_pipeline() {
let actual = nu!(r#"const list = 'bar_baz_quux' | split row '_'; $list | length"#);
assert_eq!(actual.out, "3");
}
#[test]
fn const_const() {
let actual = nu!(r#"const y = (const x = "foo"; $x + $x); $y"#);
assert_eq!(actual.out, "foofoo");
let actual = nu!(r#"const y = (const x = "foo"; $x + $x); $x"#);
assert!(actual.err.contains("nu::parser::variable_not_found"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/path/expand_path.rs | tests/path/expand_path.rs | use nu_path::expand_path_with;
use nu_test_support::playground::Playground;
use pretty_assertions::assert_eq;
use std::path::PathBuf;
#[cfg(not(windows))]
#[test]
fn expand_path_with_and_without_relative() {
let relative_to = "/foo/bar";
let path = "../..";
let full_path = "/foo/bar/../..";
let cwd = std::env::current_dir().expect("Could not get current directory");
assert_eq!(
expand_path_with(full_path, cwd, true),
expand_path_with(path, relative_to, true),
);
}
#[test]
fn expand_path_with_relative() {
let relative_to = "/foo/bar";
let path = "../..";
assert_eq!(
PathBuf::from("/"),
expand_path_with(path, relative_to, true),
);
}
#[cfg(not(windows))]
#[test]
fn expand_path_no_change() {
let path = "/foo/bar";
let cwd = std::env::current_dir().expect("Could not get current directory");
let actual = expand_path_with(path, cwd, true);
assert_eq!(actual, PathBuf::from(path));
}
#[test]
fn expand_unicode_path_no_change() {
Playground::setup("nu_path_test_1", |dirs, _| {
let mut spam = dirs.test().to_owned();
spam.push("🚒.txt");
let cwd = std::env::current_dir().expect("Could not get current directory");
let actual = expand_path_with(spam, cwd, true);
let mut expected = dirs.test().to_owned();
expected.push("🚒.txt");
assert_eq!(actual, expected);
});
}
#[ignore]
#[test]
fn expand_non_utf8_path() {
// TODO
}
#[test]
fn expand_path_relative_to() {
Playground::setup("nu_path_test_1", |dirs, _| {
let actual = expand_path_with("spam.txt", dirs.test(), true);
let mut expected = dirs.test().to_owned();
expected.push("spam.txt");
assert_eq!(actual, expected);
});
}
#[test]
fn expand_unicode_path_relative_to_unicode_path_with_spaces() {
Playground::setup("nu_path_test_1", |dirs, _| {
let mut relative_to = dirs.test().to_owned();
relative_to.push("e-$ èрт🚒♞中片-j");
let actual = expand_path_with("🚒.txt", relative_to, true);
let mut expected = dirs.test().to_owned();
expected.push("e-$ èрт🚒♞中片-j/🚒.txt");
assert_eq!(actual, expected);
});
}
#[ignore]
#[test]
fn expand_non_utf8_path_relative_to_non_utf8_path_with_spaces() {
// TODO
}
#[test]
fn expand_absolute_path_relative_to() {
Playground::setup("nu_path_test_1", |dirs, _| {
let mut absolute_path = dirs.test().to_owned();
absolute_path.push("spam.txt");
let actual = expand_path_with(&absolute_path, "non/existent/directory", true);
let expected = absolute_path;
assert_eq!(actual, expected);
});
}
#[test]
fn expand_path_with_dot_relative_to() {
Playground::setup("nu_path_test_1", |dirs, _| {
let actual = expand_path_with("./spam.txt", dirs.test(), true);
let mut expected = dirs.test().to_owned();
expected.push("spam.txt");
assert_eq!(actual, expected);
});
}
#[test]
fn expand_path_with_many_dots_relative_to() {
Playground::setup("nu_path_test_1", |dirs, _| {
let actual = expand_path_with("././/.//////./././//.////spam.txt", dirs.test(), true);
let mut expected = dirs.test().to_owned();
expected.push("spam.txt");
assert_eq!(actual, expected);
});
}
#[test]
fn expand_path_with_double_dot_relative_to() {
Playground::setup("nu_path_test_1", |dirs, _| {
let actual = expand_path_with("foo/../spam.txt", dirs.test(), true);
let mut expected = dirs.test().to_owned();
expected.push("spam.txt");
assert_eq!(actual, expected);
});
}
#[test]
fn expand_path_with_many_double_dots_relative_to() {
Playground::setup("nu_path_test_1", |dirs, _| {
let actual = expand_path_with("foo/bar/baz/../../../spam.txt", dirs.test(), true);
let mut expected = dirs.test().to_owned();
expected.push("spam.txt");
assert_eq!(actual, expected);
});
}
#[test]
fn expand_path_with_3_ndots_relative_to() {
Playground::setup("nu_path_test_1", |dirs, _| {
let actual = expand_path_with("foo/bar/.../spam.txt", dirs.test(), true);
let mut expected = dirs.test().to_owned();
expected.push("spam.txt");
assert_eq!(actual, expected);
});
}
#[test]
fn expand_path_with_many_3_ndots_relative_to() {
Playground::setup("nu_path_test_1", |dirs, _| {
let actual = expand_path_with(
"foo/bar/baz/eggs/sausage/bacon/.../.../.../spam.txt",
dirs.test(),
true,
);
let mut expected = dirs.test().to_owned();
expected.push("spam.txt");
assert_eq!(actual, expected);
});
}
#[test]
fn expand_path_with_4_ndots_relative_to() {
Playground::setup("nu_path_test_1", |dirs, _| {
let actual = expand_path_with("foo/bar/baz/..../spam.txt", dirs.test(), true);
let mut expected = dirs.test().to_owned();
expected.push("spam.txt");
assert_eq!(actual, expected);
});
}
#[test]
fn expand_path_with_many_4_ndots_relative_to() {
Playground::setup("nu_path_test_1", |dirs, _| {
let actual = expand_path_with(
"foo/bar/baz/eggs/sausage/bacon/..../..../spam.txt",
dirs.test(),
true,
);
let mut expected = dirs.test().to_owned();
expected.push("spam.txt");
assert_eq!(actual, expected);
});
}
#[test]
fn expand_path_with_way_too_many_dots_relative_to() {
Playground::setup("nu_path_test_1", |dirs, _| {
let mut relative_to = dirs.test().to_owned();
relative_to.push("foo/bar/baz/eggs/sausage/bacon/vikings");
let actual = expand_path_with(
"././..////././...///././.....///spam.txt",
relative_to,
true,
);
let mut expected = dirs.test().to_owned();
expected.push("spam.txt");
assert_eq!(actual, expected);
});
}
#[test]
fn expand_unicode_path_with_way_too_many_dots_relative_to_unicode_path_with_spaces() {
Playground::setup("nu_path_test_1", |dirs, _| {
let mut relative_to = dirs.test().to_owned();
relative_to.push("foo/áčěéí +šř=é/baz/eggs/e-$ èрт🚒♞中片-j/bacon/öäöä öäöä");
let actual = expand_path_with("././..////././...///././.....///🚒.txt", relative_to, true);
let mut expected = dirs.test().to_owned();
expected.push("🚒.txt");
assert_eq!(actual, expected);
});
}
#[test]
fn expand_path_tilde() {
let tilde_path = "~";
let cwd = std::env::current_dir().expect("Could not get current directory");
let actual = expand_path_with(tilde_path, cwd, true);
assert!(actual.is_absolute());
assert!(!actual.starts_with("~"));
}
#[test]
fn expand_path_tilde_relative_to() {
let tilde_path = "~";
let actual = expand_path_with(tilde_path, "non/existent/path", true);
assert!(actual.is_absolute());
assert!(!actual.starts_with("~"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/path/canonicalize.rs | tests/path/canonicalize.rs | use nu_path::canonicalize_with;
use nu_test_support::fs::Stub::EmptyFile;
use nu_test_support::nu;
use nu_test_support::playground::Playground;
use pretty_assertions::assert_eq;
use std::path::Path;
#[test]
fn canonicalize_path() {
Playground::setup("nu_path_test_1", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("spam.txt")]);
let mut spam = dirs.test().to_owned();
spam.push("spam.txt");
let cwd = std::env::current_dir().expect("Could not get current directory");
let actual = canonicalize_with(spam, cwd).expect("Failed to canonicalize");
assert!(actual.ends_with("spam.txt"));
});
}
#[test]
fn canonicalize_unicode_path() {
Playground::setup("nu_path_test_1", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("🚒.txt")]);
let mut spam = dirs.test().to_owned();
spam.push("🚒.txt");
let cwd = std::env::current_dir().expect("Could not get current directory");
let actual = canonicalize_with(spam, cwd).expect("Failed to canonicalize");
assert!(actual.ends_with("🚒.txt"));
});
}
#[ignore]
#[test]
fn canonicalize_non_utf8_path() {
// TODO
}
#[test]
fn canonicalize_path_relative_to() {
Playground::setup("nu_path_test_1", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("spam.txt")]);
let actual = canonicalize_with("spam.txt", dirs.test()).expect("Failed to canonicalize");
let mut expected = dirs.test().to_owned();
expected.push("spam.txt");
assert_eq!(actual, expected);
});
}
#[test]
fn canonicalize_unicode_path_relative_to_unicode_path_with_spaces() {
Playground::setup("nu_path_test_1", |dirs, sandbox| {
sandbox.mkdir("e-$ èрт🚒♞中片-j");
sandbox.with_files(&[EmptyFile("e-$ èрт🚒♞中片-j/🚒.txt")]);
let mut relative_to = dirs.test().to_owned();
relative_to.push("e-$ èрт🚒♞中片-j");
let actual = canonicalize_with("🚒.txt", relative_to).expect("Failed to canonicalize");
let mut expected = dirs.test().to_owned();
expected.push("e-$ èрт🚒♞中片-j/🚒.txt");
assert_eq!(actual, expected);
});
}
#[ignore]
#[test]
fn canonicalize_non_utf8_path_relative_to_non_utf8_path_with_spaces() {
// TODO
}
#[test]
fn canonicalize_absolute_path_relative_to() {
Playground::setup("nu_path_test_1", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("spam.txt")]);
let mut absolute_path = dirs.test().to_owned();
absolute_path.push("spam.txt");
let actual = canonicalize_with(&absolute_path, "non/existent/directory")
.expect("Failed to canonicalize");
let expected = absolute_path;
assert_eq!(actual, expected);
});
}
#[test]
fn canonicalize_dot() {
let expected = std::env::current_dir().expect("Could not get current directory");
let actual = canonicalize_with(".", expected.as_path()).expect("Failed to canonicalize");
assert_eq!(actual, expected);
}
#[test]
fn canonicalize_many_dots() {
let expected = std::env::current_dir().expect("Could not get current directory");
let actual = canonicalize_with("././/.//////./././//.///", expected.as_path())
.expect("Failed to canonicalize");
assert_eq!(actual, expected);
}
#[test]
fn canonicalize_path_with_dot_relative_to() {
Playground::setup("nu_path_test_1", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("spam.txt")]);
let actual = canonicalize_with("./spam.txt", dirs.test()).expect("Failed to canonicalize");
let mut expected = dirs.test().to_owned();
expected.push("spam.txt");
assert_eq!(actual, expected);
});
}
#[test]
fn canonicalize_path_with_many_dots_relative_to() {
Playground::setup("nu_path_test_1", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("spam.txt")]);
let actual = canonicalize_with("././/.//////./././//.////spam.txt", dirs.test())
.expect("Failed to canonicalize");
let mut expected = dirs.test().to_owned();
expected.push("spam.txt");
assert_eq!(actual, expected);
});
}
#[test]
fn canonicalize_double_dot() {
let cwd = std::env::current_dir().expect("Could not get current directory");
let actual = canonicalize_with("..", &cwd).expect("Failed to canonicalize");
let expected = cwd
.parent()
.expect("Could not get parent of current directory");
assert_eq!(actual, expected);
}
#[test]
fn canonicalize_path_with_double_dot_relative_to() {
Playground::setup("nu_path_test_1", |dirs, sandbox| {
sandbox.mkdir("foo");
sandbox.with_files(&[EmptyFile("spam.txt")]);
let actual =
canonicalize_with("foo/../spam.txt", dirs.test()).expect("Failed to canonicalize");
let mut expected = dirs.test().to_owned();
expected.push("spam.txt");
assert_eq!(actual, expected);
});
}
#[test]
fn canonicalize_path_with_many_double_dots_relative_to() {
Playground::setup("nu_path_test_1", |dirs, sandbox| {
sandbox.mkdir("foo/bar/baz");
sandbox.with_files(&[EmptyFile("spam.txt")]);
let actual = canonicalize_with("foo/bar/baz/../../../spam.txt", dirs.test())
.expect("Failed to canonicalize");
let mut expected = dirs.test().to_owned();
expected.push("spam.txt");
assert_eq!(actual, expected);
});
}
#[test]
fn canonicalize_ndots2() {
// This test will fail if you have the nushell repo on the root partition
// So, let's start in a nested folder before trying to canonicalize_with "..."
Playground::setup("nu_path_test_1", |dirs, sandbox| {
sandbox.mkdir("aaa/bbb/ccc");
let output = nu!( cwd: dirs.root(), "cd nu_path_test_1/aaa/bbb/ccc; $env.PWD");
let cwd = Path::new(&output.out);
let actual = canonicalize_with("...", cwd).expect("Failed to canonicalize");
let expected = cwd
.parent()
.expect("Could not get parent of current directory")
.parent()
.expect("Could not get parent of a parent of current directory");
assert_eq!(actual, expected);
});
}
#[test]
fn canonicalize_path_with_3_ndots_relative_to() {
Playground::setup("nu_path_test_1", |dirs, sandbox| {
sandbox.mkdir("foo/bar");
sandbox.with_files(&[EmptyFile("spam.txt")]);
let actual =
canonicalize_with("foo/bar/.../spam.txt", dirs.test()).expect("Failed to canonicalize");
let mut expected = dirs.test().to_owned();
expected.push("spam.txt");
assert_eq!(actual, expected);
});
}
#[test]
fn canonicalize_path_with_many_3_ndots_relative_to() {
Playground::setup("nu_path_test_1", |dirs, sandbox| {
sandbox.mkdir("foo/bar/baz/eggs/sausage/bacon");
sandbox.with_files(&[EmptyFile("spam.txt")]);
let actual = canonicalize_with(
"foo/bar/baz/eggs/sausage/bacon/.../.../.../spam.txt",
dirs.test(),
)
.expect("Failed to canonicalize");
let mut expected = dirs.test().to_owned();
expected.push("spam.txt");
assert_eq!(actual, expected);
});
}
#[test]
fn canonicalize_path_with_4_ndots_relative_to() {
Playground::setup("nu_path_test_1", |dirs, sandbox| {
sandbox.mkdir("foo/bar/baz");
sandbox.with_files(&[EmptyFile("spam.txt")]);
let actual = canonicalize_with("foo/bar/baz/..../spam.txt", dirs.test())
.expect("Failed to canonicalize");
let mut expected = dirs.test().to_owned();
expected.push("spam.txt");
assert_eq!(actual, expected);
});
}
#[test]
fn canonicalize_path_with_many_4_ndots_relative_to() {
Playground::setup("nu_path_test_1", |dirs, sandbox| {
sandbox.mkdir("foo/bar/baz/eggs/sausage/bacon");
sandbox.with_files(&[EmptyFile("spam.txt")]);
let actual = canonicalize_with(
"foo/bar/baz/eggs/sausage/bacon/..../..../spam.txt",
dirs.test(),
)
.expect("Failed to canonicalize");
let mut expected = dirs.test().to_owned();
expected.push("spam.txt");
assert_eq!(actual, expected);
});
}
#[test]
fn canonicalize_path_with_way_too_many_dots_relative_to() {
Playground::setup("nu_path_test_1", |dirs, sandbox| {
sandbox.mkdir("foo/bar/baz/eggs/sausage/bacon/vikings");
sandbox.with_files(&[EmptyFile("spam.txt")]);
let mut relative_to = dirs.test().to_owned();
relative_to.push("foo/bar/baz/eggs/sausage/bacon/vikings");
let actual = canonicalize_with("././..////././...///././.....///spam.txt", relative_to)
.expect("Failed to canonicalize");
let mut expected = dirs.test().to_owned();
expected.push("spam.txt");
assert_eq!(actual, expected);
});
}
#[test]
fn canonicalize_unicode_path_with_way_too_many_dots_relative_to_unicode_path_with_spaces() {
Playground::setup("nu_path_test_1", |dirs, sandbox| {
sandbox.mkdir("foo/áčěéí +šř=é/baz/eggs/e-$ èрт🚒♞中片-j/bacon/öäöä öäöä");
sandbox.with_files(&[EmptyFile("🚒.txt")]);
let mut relative_to = dirs.test().to_owned();
relative_to.push("foo/áčěéí +šř=é/baz/eggs/e-$ èрт🚒♞中片-j/bacon/öäöä öäöä");
let actual = canonicalize_with("././..////././...///././.....///🚒.txt", relative_to)
.expect("Failed to canonicalize");
let mut expected = dirs.test().to_owned();
expected.push("🚒.txt");
assert_eq!(actual, expected);
});
}
#[test]
fn canonicalize_tilde() {
let tilde_path = "~";
let cwd = std::env::current_dir().expect("Could not get current directory");
let actual = canonicalize_with(tilde_path, cwd).expect("Failed to canonicalize");
assert!(actual.is_absolute());
assert!(!actual.starts_with("~"));
}
#[test]
fn canonicalize_tilde_relative_to() {
let tilde_path = "~";
let actual =
canonicalize_with(tilde_path, "non/existent/path").expect("Failed to canonicalize");
assert!(actual.is_absolute());
assert!(!actual.starts_with("~"));
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn canonicalize_symlink() {
Playground::setup("nu_path_test_1", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("spam.txt")]);
sandbox.symlink("spam.txt", "link_to_spam.txt");
let mut symlink_path = dirs.test().to_owned();
symlink_path.push("link_to_spam.txt");
let cwd = std::env::current_dir().expect("Could not get current directory");
let actual = canonicalize_with(symlink_path, cwd).expect("Failed to canonicalize");
let mut expected = dirs.test().to_owned();
expected.push("spam.txt");
assert_eq!(actual, expected);
});
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn canonicalize_symlink_relative_to() {
Playground::setup("nu_path_test_1", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("spam.txt")]);
sandbox.symlink("spam.txt", "link_to_spam.txt");
let actual =
canonicalize_with("link_to_spam.txt", dirs.test()).expect("Failed to canonicalize");
let mut expected = dirs.test().to_owned();
expected.push("spam.txt");
assert_eq!(actual, expected);
});
}
#[cfg(not(target_arch = "wasm32"))]
#[cfg(not(windows))] // seems like Windows symlink requires existing file or dir
#[test]
fn canonicalize_symlink_loop_relative_to_should_fail() {
Playground::setup("nu_path_test_1", |dirs, sandbox| {
// sandbox.with_files(vec![EmptyFile("spam.txt")]);
sandbox.symlink("spam.txt", "link_to_spam.txt");
sandbox.symlink("link_to_spam.txt", "spam.txt");
let actual = canonicalize_with("link_to_spam.txt", dirs.test());
assert!(actual.is_err());
});
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn canonicalize_nested_symlink_relative_to() {
Playground::setup("nu_path_test_1", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("spam.txt")]);
sandbox.symlink("spam.txt", "link_to_spam.txt");
sandbox.symlink("link_to_spam.txt", "link_to_link_to_spam.txt");
let actual = canonicalize_with("link_to_link_to_spam.txt", dirs.test())
.expect("Failed to canonicalize");
let mut expected = dirs.test().to_owned();
expected.push("spam.txt");
assert_eq!(actual, expected);
});
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn canonicalize_nested_symlink_within_symlink_dir_relative_to() {
Playground::setup("nu_path_test_1", |dirs, sandbox| {
sandbox.mkdir("foo/bar/baz");
sandbox.with_files(&[EmptyFile("foo/bar/baz/spam.txt")]);
sandbox.symlink("foo/bar/baz/spam.txt", "foo/bar/link_to_spam.txt");
sandbox.symlink("foo/bar/link_to_spam.txt", "foo/link_to_link_to_spam.txt");
sandbox.symlink("foo", "link_to_foo");
let actual = canonicalize_with("link_to_foo/link_to_link_to_spam.txt", dirs.test())
.expect("Failed to canonicalize");
let mut expected = dirs.test().to_owned();
expected.push("foo/bar/baz/spam.txt");
assert_eq!(actual, expected);
});
}
#[test]
fn canonicalize_should_fail() {
let path = Path::new("/foo/bar/baz"); // hopefully, this path does not exist
let cwd = std::env::current_dir().expect("Could not get current directory");
assert!(canonicalize_with(path, cwd).is_err());
}
#[test]
fn canonicalize_with_should_fail() {
let relative_to = "/foo";
let path = "bar/baz";
assert!(canonicalize_with(path, relative_to).is_err());
}
#[cfg(windows)]
#[test]
fn canonicalize_unc() {
// Ensure that canonicalizing UNC paths does not turn them verbatim.
// Assumes the C drive exists and that the `localhost` UNC path works.
let actual =
nu_path::canonicalize_with(r"\\localhost\c$", ".").expect("failed to canonicalize");
let expected = Path::new(r"\\localhost\c$");
assert_eq!(actual, expected);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/path/mod.rs | tests/path/mod.rs | mod canonicalize;
mod expand_path;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/shell/repl.rs | tests/shell/repl.rs | use nu_test_support::{nu, nu_repl_code};
use pretty_assertions::assert_eq;
#[test]
fn mut_variable() {
let lines = &["mut x = 0", "$x = 1", "$x"];
let actual = nu!(nu_repl_code(lines));
assert_eq!(actual.out, "1");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/shell/mod.rs | tests/shell/mod.rs | use nu_test_support::fs::Stub::{FileWithContent, FileWithContentToBeTrimmed};
use nu_test_support::playground::Playground;
use nu_test_support::{nu, nu_repl_code};
use pretty_assertions::assert_eq;
mod environment;
mod pipeline;
mod repl;
//FIXME: jt: we need to focus some fixes on wix as the plugins will differ
#[ignore]
#[test]
fn plugins_are_declared_with_wix() {
let actual = nu!(r#"
open Cargo.toml
| get bin.name
| str replace "nu_plugin_(extra|core)_(.*)" "nu_plugin_$2"
| drop
| sort-by
| wrap cargo | merge {
open wix/main.wxs --raw | from xml
| get Wix.children.Product.children.0.Directory.children.0
| where Directory.attributes.Id == "$(var.PlatformProgramFilesFolder)"
| get Directory.children.Directory.children.0 | last
| get Directory.children.Component.children
| each { |it| echo $it | first }
| skip
| where File.attributes.Name =~ "nu_plugin"
| str substring [_, -4] File.attributes.Name
| get File.attributes.Name
| sort-by
| wrap wix
}
| default wix _
| each { |it| if $it.wix != $it.cargo { 1 } { 0 } }
| math sum
"#);
assert_eq!(actual.out, "0");
}
#[test]
#[cfg(not(windows))]
fn do_not_panic_if_broken_pipe() {
// `nu -h | false`
// used to panic with a BrokenPipe error
let child_output = std::process::Command::new("sh")
.arg("-c")
.arg(format!(
"{:?} -h | false",
nu_test_support::fs::executable_path()
))
.output()
.expect("failed to execute process");
assert!(child_output.stderr.is_empty());
}
#[test]
fn nu_lib_dirs_repl() {
Playground::setup("nu_lib_dirs_repl", |dirs, sandbox| {
sandbox
.mkdir("scripts")
.with_files(&[FileWithContentToBeTrimmed(
"scripts/foo.nu",
r#"
$env.FOO = "foo"
"#,
)]);
let inp_lines = &[
"$env.NU_LIB_DIRS = [ ('scripts' | path expand) ]",
"source-env foo.nu",
"$env.FOO",
];
let actual_repl = nu!(cwd: dirs.test(), nu_repl_code(inp_lines));
assert!(actual_repl.err.is_empty());
assert_eq!(actual_repl.out, "foo");
})
}
#[test]
fn nu_lib_dirs_script() {
Playground::setup("nu_lib_dirs_script", |dirs, sandbox| {
sandbox
.mkdir("scripts")
.with_files(&[FileWithContentToBeTrimmed(
"scripts/foo.nu",
r#"
$env.FOO = "foo"
"#,
)])
.with_files(&[FileWithContentToBeTrimmed(
"main.nu",
"
source-env foo.nu
",
)]);
let inp_lines = &[
"$env.NU_LIB_DIRS = [ ('scripts' | path expand) ]",
"source-env main.nu",
"$env.FOO",
];
let actual_repl = nu!(cwd: dirs.test(), nu_repl_code(inp_lines));
assert!(actual_repl.err.is_empty());
assert_eq!(actual_repl.out, "foo");
})
}
#[test]
fn nu_lib_dirs_relative_repl() {
Playground::setup("nu_lib_dirs_relative_repl", |dirs, sandbox| {
sandbox
.mkdir("scripts")
.with_files(&[FileWithContentToBeTrimmed(
"scripts/foo.nu",
r#"
$env.FOO = "foo"
"#,
)]);
let inp_lines = &[
"$env.NU_LIB_DIRS = [ 'scripts' ]",
"source-env foo.nu",
"$env.FOO",
];
let actual_repl = nu!(cwd: dirs.test(), nu_repl_code(inp_lines));
assert!(actual_repl.err.is_empty());
assert_eq!(actual_repl.out, "foo");
})
}
// TODO: add absolute path tests after we expand const capabilities (see #8310)
#[test]
fn const_nu_lib_dirs_relative() {
Playground::setup("const_nu_lib_dirs_relative", |dirs, sandbox| {
sandbox
.mkdir("scripts")
.with_files(&[FileWithContentToBeTrimmed(
"scripts/foo.nu",
r#"
$env.FOO = "foo"
"#,
)])
.with_files(&[FileWithContentToBeTrimmed(
"main.nu",
"
const NU_LIB_DIRS = [ 'scripts' ]
source-env foo.nu
$env.FOO
",
)]);
let outcome = nu!(cwd: dirs.test(), "source main.nu");
assert!(outcome.err.is_empty());
assert_eq!(outcome.out, "foo");
})
}
#[test]
fn nu_lib_dirs_relative_script() {
Playground::setup("nu_lib_dirs_relative_script", |dirs, sandbox| {
sandbox
.mkdir("scripts")
.with_files(&[FileWithContentToBeTrimmed(
"scripts/main.nu",
"
source-env ../foo.nu
",
)])
.with_files(&[FileWithContentToBeTrimmed(
"foo.nu",
r#"
$env.FOO = "foo"
"#,
)]);
let inp_lines = &[
"$env.NU_LIB_DIRS = [ 'scripts' ]",
"source-env scripts/main.nu",
"$env.FOO",
];
let actual_repl = nu!(cwd: dirs.test(), nu_repl_code(inp_lines));
assert!(actual_repl.err.is_empty());
assert_eq!(actual_repl.out, "foo");
})
}
#[test]
fn run_script_that_looks_like_module() {
Playground::setup("run_script_that_looks_like_module", |dirs, _| {
let inp_lines = &[
"module spam { export def eggs [] { 'eggs' } }",
"export use spam eggs",
"export def foo [] { eggs }",
"export alias bar = foo",
"export def --env baz [] { bar }",
"baz",
];
let actual = nu!(cwd: dirs.test(), inp_lines.join("; "));
assert_eq!(actual.out, "eggs");
})
}
#[test]
fn run_export_extern() {
Playground::setup("run_script_that_looks_like_module", |dirs, _| {
let inp_lines = &["export extern foo []", "help foo"];
let actual = nu!(cwd: dirs.test(), inp_lines.join("; "));
assert!(actual.out.contains("Usage"));
})
}
#[test]
fn run_in_login_mode() {
let child_output = std::process::Command::new(nu_test_support::fs::executable_path())
.args(["-n", "-l", "-c", "echo $nu.is-login"])
.output()
.expect("failed to run nu");
assert_eq!("true\n", String::from_utf8_lossy(&child_output.stdout));
assert!(child_output.stderr.is_empty());
}
#[test]
fn run_in_not_login_mode() {
let child_output = std::process::Command::new(nu_test_support::fs::executable_path())
.args(["-n", "-c", "echo $nu.is-login"])
.output()
.expect("failed to run nu");
assert_eq!("false\n", String::from_utf8_lossy(&child_output.stdout));
assert!(child_output.stderr.is_empty());
}
#[test]
fn run_in_interactive_mode() {
let child_output = std::process::Command::new(nu_test_support::fs::executable_path())
.args(["-n", "-i", "-c", "echo $nu.is-interactive"])
.output()
.expect("failed to run nu");
assert_eq!("true\n", String::from_utf8_lossy(&child_output.stdout));
assert!(child_output.stderr.is_empty());
}
#[test]
fn run_in_noninteractive_mode() {
let child_output = std::process::Command::new(nu_test_support::fs::executable_path())
.args(["-n", "-c", "echo $nu.is-interactive"])
.output()
.expect("failed to run nu");
assert_eq!("false\n", String::from_utf8_lossy(&child_output.stdout));
assert!(child_output.stderr.is_empty());
}
#[test]
fn run_with_no_newline() {
let child_output = std::process::Command::new(nu_test_support::fs::executable_path())
.args(["-n", "--no-newline", "-c", "\"hello world\""])
.output()
.expect("failed to run nu");
assert_eq!("hello world", String::from_utf8_lossy(&child_output.stdout)); // with no newline
assert!(child_output.stderr.is_empty());
}
#[test]
fn main_script_can_have_subcommands1() {
Playground::setup("main_subcommands", |dirs, sandbox| {
sandbox.mkdir("main_subcommands");
sandbox.with_files(&[FileWithContent(
"script.nu",
r#"def "main foo" [x: int] {
print ($x + 100)
}
def "main" [] {
print "usage: script.nu <command name>"
}"#,
)]);
let actual = nu!(cwd: dirs.test(), "nu script.nu foo 123");
assert_eq!(actual.out, "223");
})
}
#[test]
fn main_script_can_have_subcommands2() {
Playground::setup("main_subcommands", |dirs, sandbox| {
sandbox.mkdir("main_subcommands");
sandbox.with_files(&[FileWithContent(
"script.nu",
r#"def "main foo" [x: int] {
print ($x + 100)
}
def "main" [] {
print "usage: script.nu <command name>"
}"#,
)]);
let actual = nu!(cwd: dirs.test(), "nu script.nu");
assert!(actual.out.contains("usage: script.nu"));
})
}
#[test]
fn source_empty_file() {
Playground::setup("source_empty_file", |dirs, sandbox| {
sandbox.mkdir("source_empty_file");
sandbox.with_files(&[FileWithContent("empty.nu", "")]);
let actual = nu!(cwd: dirs.test(), "nu empty.nu");
assert!(actual.out.is_empty());
})
}
#[test]
fn source_use_null() {
let actual = nu!(r#"source null"#);
assert!(actual.out.is_empty());
assert!(actual.err.is_empty());
let actual = nu!(r#"source-env null"#);
assert!(actual.out.is_empty());
assert!(actual.err.is_empty());
let actual = nu!(r#"use null"#);
assert!(actual.out.is_empty());
assert!(actual.err.is_empty());
let actual = nu!(r#"overlay use null"#);
assert!(actual.out.is_empty());
assert!(actual.err.is_empty());
}
#[test]
fn source_use_file_named_null() {
Playground::setup("source_file_named_null", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
"null",
r#"export-env { print "hello world" }"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"source "null""#);
assert!(actual.out.contains("hello world"));
assert!(actual.err.is_empty());
let actual = nu!(cwd: dirs.test(), r#"source-env "null""#);
assert!(actual.out.contains("hello world"));
assert!(actual.err.is_empty());
let actual = nu!(cwd: dirs.test(), r#"use "null""#);
assert!(actual.out.contains("hello world"));
assert!(actual.err.is_empty());
let actual = nu!(cwd: dirs.test(), r#"overlay use "null""#);
assert!(actual.out.contains("hello world"));
assert!(actual.err.is_empty());
})
}
#[test]
fn main_script_help_uses_script_name1() {
// Note: this test is somewhat fragile and might need to be adapted if the usage help message changes
Playground::setup("main_filename", |dirs, sandbox| {
sandbox.mkdir("main_filename");
sandbox.with_files(&[FileWithContent(
"script.nu",
r#"def main [] {}
"#,
)]);
let actual = nu!(cwd: dirs.test(), "nu script.nu --help");
assert!(actual.out.contains("> script.nu"));
assert!(!actual.out.contains("> main"));
})
}
#[test]
fn main_script_help_uses_script_name2() {
// Note: this test is somewhat fragile and might need to be adapted if the usage help message changes
Playground::setup("main_filename", |dirs, sandbox| {
sandbox.mkdir("main_filename");
sandbox.with_files(&[FileWithContent(
"script.nu",
r#"def main [foo: string] {}
"#,
)]);
let actual = nu!(cwd: dirs.test(), "nu script.nu");
assert!(actual.err.contains("Usage: script.nu"));
assert!(!actual.err.contains("Usage: main"));
})
}
#[test]
fn main_script_subcommand_help_uses_script_name1() {
// Note: this test is somewhat fragile and might need to be adapted if the usage help message changes
Playground::setup("main_filename", |dirs, sandbox| {
sandbox.mkdir("main_filename");
sandbox.with_files(&[FileWithContent(
"script.nu",
r#"def main [] {}
def 'main foo' [] {}
"#,
)]);
let actual = nu!(cwd: dirs.test(), "nu script.nu foo --help");
assert!(actual.out.contains("> script.nu foo"));
assert!(!actual.out.contains("> main foo"));
})
}
#[test]
fn main_script_subcommand_help_uses_script_name2() {
// Note: this test is somewhat fragile and might need to be adapted if the usage help message changes
Playground::setup("main_filename", |dirs, sandbox| {
sandbox.mkdir("main_filename");
sandbox.with_files(&[FileWithContent(
"script.nu",
r#"def main [] {}
def 'main foo' [bar: string] {}
"#,
)]);
let actual = nu!(cwd: dirs.test(), "nu script.nu foo");
assert!(actual.err.contains("Usage: script.nu foo"));
assert!(!actual.err.contains("Usage: main foo"));
})
}
#[test]
fn script_file_not_found() {
let actual = nu!(r#"nu non-existent-script.nu foo bar"#);
assert!(
!actual.err.contains(".rs"),
"internal rust source was mentioned"
);
assert!(
actual.err.contains("non-existent-script.nu"),
"error did not include script name"
);
assert!(
actual.err.contains("commandline"),
"source file for the error was not commandline"
);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/shell/environment/env.rs | tests/shell/environment/env.rs | use nu_test_support::fs::Stub::FileWithContent;
use nu_test_support::playground::Playground;
use nu_test_support::{nu, nu_repl_code, nu_with_std};
use pretty_assertions::assert_eq;
#[test]
fn env_shorthand() {
let actual = nu!("
FOO=bar echo $env.FOO
");
assert_eq!(actual.out, "bar");
}
#[test]
fn env_shorthand_with_equals() {
let actual = nu!("
RUST_LOG=my_module=info $env.RUST_LOG
");
assert_eq!(actual.out, "my_module=info");
}
#[test]
fn env_shorthand_with_interpolation() {
let actual = nu!(r#"
let num = 123
FOO=$"($num) bar" echo $env.FOO
"#);
assert_eq!(actual.out, "123 bar");
}
#[test]
fn env_shorthand_with_comma_equals() {
let actual = nu!("
RUST_LOG=info,my_module=info $env.RUST_LOG
");
assert_eq!(actual.out, "info,my_module=info");
}
#[test]
fn env_shorthand_with_comma_colons_equals() {
let actual = nu!("
RUST_LOG=info,my_module=info,lib_crate::lib_mod=trace $env.RUST_LOG
");
assert_eq!(actual.out, "info,my_module=info,lib_crate::lib_mod=trace");
}
#[test]
fn env_shorthand_multi_second_with_comma_colons_equals() {
let actual = nu!("
FOO=bar RUST_LOG=info,my_module=info,lib_crate::lib_mod=trace $env.FOO + $env.RUST_LOG
");
assert_eq!(
actual.out,
"barinfo,my_module=info,lib_crate::lib_mod=trace"
);
}
#[test]
fn env_shorthand_multi_first_with_comma_colons_equals() {
let actual = nu!("
RUST_LOG=info,my_module=info,lib_crate::lib_mod=trace FOO=bar $env.FOO + $env.RUST_LOG
");
assert_eq!(
actual.out,
"barinfo,my_module=info,lib_crate::lib_mod=trace"
);
}
#[test]
fn env_shorthand_multi() {
let actual = nu!("
FOO=bar BAR=baz $env.FOO + $env.BAR
");
assert_eq!(actual.out, "barbaz");
}
#[test]
fn env_assignment() {
let actual = nu!(r#"
$env.FOOBAR = "barbaz"; $env.FOOBAR
"#);
assert_eq!(actual.out, "barbaz");
}
#[test]
fn env_assignment_with_if() {
let actual = nu!(r#"$env.FOOBAR = if 3 == 4 { "bar" } else { "baz" }; $env.FOOBAR"#);
assert_eq!(actual.out, "baz");
}
#[test]
fn env_assignment_with_match() {
let actual = nu!(r#"$env.FOOBAR = match 1 { 1 => { 'yes!' }, _ => { 'no!' } }; $env.FOOBAR"#);
assert_eq!(actual.out, "yes!");
}
#[test]
fn mutate_env_file_pwd_env_var_fails() {
let actual = nu!("$env.FILE_PWD = 'foo'");
assert!(actual.err.contains("automatic_env_var_set_manually"));
}
#[test]
fn load_env_file_pwd_env_var_fails() {
let actual = nu!("load-env { FILE_PWD : 'foo' }");
assert!(actual.err.contains("automatic_env_var_set_manually"));
}
#[test]
fn load_env_pwd_env_var_fails() {
let actual = nu!("load-env { PWD : 'foo' }");
assert!(actual.err.contains("automatic_env_var_set_manually"));
}
#[test]
fn passes_with_env_env_var_to_external_process() {
let actual = nu!("
with-env { FOO: foo } {nu --testbin echo_env FOO}
");
assert_eq!(actual.out, "foo");
}
#[test]
fn hides_environment_from_child() {
let actual = nu!(r#"
$env.TEST = 1; ^$nu.current-exe -c "hide-env TEST; ^$nu.current-exe -c '$env.TEST'"
"#);
assert!(actual.out.is_empty());
assert!(actual.err.contains("column_not_found") || actual.err.contains("name_not_found"));
}
#[test]
fn has_file_pwd() {
Playground::setup("has_file_pwd", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent("spam.nu", "$env.FILE_PWD")]);
let actual = nu!(cwd: dirs.test(), "nu spam.nu");
assert!(actual.out.ends_with("has_file_pwd"));
})
}
#[test]
fn has_file_loc() {
Playground::setup("has_file_pwd", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent("spam.nu", "$env.CURRENT_FILE")]);
let actual = nu!(cwd: dirs.test(), "nu spam.nu");
assert!(actual.out.ends_with("spam.nu"));
})
}
#[test]
fn hides_env_in_block() {
let inp = &[
"$env.foo = 'foo'",
"hide-env foo",
"let b = {|| $env.foo }",
"do $b",
];
let actual = nu!(&inp.join("; "));
let actual_repl = nu!(nu_repl_code(inp));
assert!(actual.err.contains("column_not_found"));
assert!(actual_repl.err.contains("column_not_found"));
}
#[test]
fn env_var_not_var() {
let actual = nu!("
echo $PWD
");
assert!(actual.err.contains("use $env.PWD instead of $PWD"));
}
#[test]
fn env_var_case_insensitive() {
let actual = nu!("
$env.foo = 111
print $env.Foo
$env.FOO = 222
print $env.foo
");
assert!(actual.out.contains("111"));
assert!(actual.out.contains("222"));
}
#[test]
fn env_conversion_on_assignment() {
let actual = nu!(r#"
$env.FOO = "bar:baz:quox"
$env.ENV_CONVERSIONS = { FOO: { from_string: {|| split row ":"} } }
$env.FOO | to nuon
"#);
assert_eq!(actual.out, "[bar, baz, quox]");
}
#[test]
fn std_log_env_vars_are_not_overridden() {
let actual = nu_with_std!(
envs: vec![
("NU_LOG_FORMAT".to_string(), "%MSG%".to_string()),
("NU_LOG_DATE_FORMAT".to_string(), "%Y".to_string()),
],
r#"
use std/log
print -e $env.NU_LOG_FORMAT
print -e $env.NU_LOG_DATE_FORMAT
log error "err"
"#
);
assert_eq!(actual.err, "%MSG%\n%Y\nerr\n");
}
#[test]
fn std_log_env_vars_have_defaults() {
let actual = nu_with_std!(
r#"
use std/log
print -e $env.NU_LOG_FORMAT
print -e $env.NU_LOG_DATE_FORMAT
"#
);
assert!(actual.err.contains("%MSG%"));
assert!(actual.err.contains("%Y-"));
}
#[test]
fn env_shlvl_commandstring_does_not_increment() {
let actual = nu!("
$env.SHLVL = 5
nu -c 'print $env.SHLVL; exit'
");
assert_eq!(actual.out, "5");
}
// Note: Do not use -i / --interactive in tests.
// -i attempts to acquire a terminal, and if more than one
// test tries to obtain a terminal at the same time, the
// test run will likely hang, at least for some users.
// Instead, use -e / --execute with an `exit` to test REPL
// functionality as demonstrated below.
//
// We've also learned that `-e 'exit'` is not enough to
// prevent failures entirely. For now we're going to ignore
// these tests until we can find a better solution.
#[ignore = "Causing hangs when both tests overlap"]
#[test]
fn env_shlvl_in_repl() {
let actual = nu!(r#"
$env.SHLVL = 5
nu --no-std-lib -n -e 'print $"SHLVL:($env.SHLVL)"; exit'
"#);
assert!(actual.out.ends_with("SHLVL:6"));
}
#[ignore = "Causing hangs when both tests overlap"]
#[test]
fn env_shlvl_in_exec_repl() {
let actual = nu!(r#"
$env.SHLVL = 29
nu -c 'exec nu --no-std-lib -n -e `print $"SHLVL:($env.SHLVL)"; exit`'
"#);
assert!(actual.out.ends_with("SHLVL:30"));
}
#[test]
fn path_is_a_list_in_repl() {
let actual = nu!(r#"
nu -c "exec nu --no-std-lib -n -e `print $'path:($env.pATh | describe)'; exit`"
"#);
assert!(actual.out.ends_with("path:list<string>"));
}
#[test]
fn path_is_a_list() {
let actual = nu!("
print ($env.path | describe)
");
assert_eq!(actual.out, "list<string>");
}
#[test]
fn path_is_a_list_in_script() {
Playground::setup("has_file_pwd", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent("checkpath.nu", "$env.path | describe")]);
let actual = nu!(cwd: dirs.test(), "nu checkpath.nu");
assert!(actual.out.ends_with("list<string>"));
})
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/shell/environment/mod.rs | tests/shell/environment/mod.rs | mod env;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/shell/pipeline/mod.rs | tests/shell/pipeline/mod.rs | mod commands;
use nu_test_support::nu;
use pretty_assertions::assert_eq;
#[test]
fn doesnt_break_on_utf8() {
let actual = nu!("echo ö");
assert_eq!(actual.out, "ö", "'{}' should contain ö", actual.out);
}
#[test]
fn non_zero_exit_code_in_middle_of_pipeline_ignored() {
let actual = nu!("nu -c 'print a b; exit 42' | collect");
assert_eq!(actual.out, "ab");
let actual = nu!("nu -c 'print a b; exit 42' | nu --stdin -c 'collect'");
assert_eq!(actual.out, "ab");
}
#[test]
fn infinite_output_piped_to_value() {
let actual = nu!("nu --testbin iecho x | 1");
assert_eq!(actual.out, "1");
assert_eq!(actual.err, "");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/shell/pipeline/commands/external.rs | tests/shell/pipeline/commands/external.rs | use nu_test_support::fs::Stub::{EmptyFile, FileWithContent};
use nu_test_support::nu;
use nu_test_support::playground::Playground;
use pretty_assertions::assert_eq;
use rstest::rstest;
#[test]
fn shows_error_for_command_not_found() {
let actual = nu!("ferris_is_not_here.exe");
assert!(!actual.err.is_empty());
}
#[test]
fn shows_error_for_command_not_found_in_pipeline() {
let actual = nu!("ferris_is_not_here.exe | echo done");
assert!(!actual.err.is_empty());
}
#[ignore] // jt: we can't test this using the -c workaround currently
#[test]
fn automatically_change_directory() {
use nu_test_support::playground::Playground;
Playground::setup("cd_test_5_1", |dirs, sandbox| {
sandbox.mkdir("autodir");
let actual = nu!(
cwd: dirs.test(),
"
autodir
echo (pwd)
"
);
assert!(actual.out.ends_with("autodir"));
})
}
// FIXME: jt: we don't currently support autocd in testing
#[ignore]
#[test]
fn automatically_change_directory_with_trailing_slash_and_same_name_as_command() {
use nu_test_support::playground::Playground;
Playground::setup("cd_test_5_1", |dirs, sandbox| {
sandbox.mkdir("cd");
let actual = nu!(
cwd: dirs.test(),
"
cd/
pwd
"
);
assert!(actual.out.ends_with("cd"));
})
}
#[test]
fn pass_dot_as_external_arguments() {
let actual = nu!("nu --testbin cococo .");
assert_eq!(actual.out, ".");
}
#[test]
fn correctly_escape_external_arguments() {
let actual = nu!("^nu --testbin cococo '$0'");
assert_eq!(actual.out, "$0");
}
#[test]
fn escape_also_escapes_equals() {
let actual = nu!("^MYFOONAME=MYBARVALUE");
assert!(
actual
.err
.contains("Command `MYFOONAME=MYBARVALUE` not found")
);
}
#[test]
fn execute_binary_in_string() {
let actual = nu!(r#"
let cmd = "nu"
^$"($cmd)" --testbin cococo "$0"
"#);
assert_eq!(actual.out, "$0");
}
#[test]
fn single_quote_dollar_external() {
let actual = nu!("let author = 'JT'; nu --testbin cococo $'foo=($author)'");
assert_eq!(actual.out, "foo=JT");
}
#[test]
fn redirects_custom_command_external() {
let actual = nu!("def foo [] { nu --testbin cococo foo bar }; foo | str length");
assert_eq!(actual.out, "7");
}
#[test]
fn passes_binary_data_between_externals() {
let actual = nu!(cwd: "tests/fixtures/formats", "nu --testbin meowb sample.db | nu --testbin relay | hash sha256");
assert_eq!(
actual.out,
"2f5050e7eea415c1f3d80b5d93355efd15043ec9157a2bb167a9e73f2ae651f2"
)
}
#[test]
fn command_not_found_error_suggests_search_term() {
// 'distinct' is not a command, but it is a search term for 'uniq'
let actual = nu!("ls | distinct");
assert!(actual.err.contains("uniq"));
}
#[test]
fn command_not_found_error_suggests_typo_fix() {
let actual = nu!("benchmark { echo 'foo'}");
assert!(actual.err.contains("timeit"));
}
#[cfg(not(windows))]
#[test]
fn command_not_found_error_recognizes_non_executable_file() {
let actual = nu!("./Cargo.toml");
assert!(actual.err.contains(
"refers to a file that is not executable. Did you forget to set execute permissions?"
));
}
#[test]
fn command_not_found_error_shows_not_found_1() {
let actual = nu!(r#"
export extern "foo" [];
foo
"#);
assert!(actual.err.contains("Command `foo` not found"));
}
#[test]
fn command_substitution_wont_output_extra_newline() {
let actual = nu!(r#"
with-env { FOO: "bar" } { echo $"prefix (nu --testbin echo_env FOO) suffix" }
"#);
assert_eq!(actual.out, "prefix bar suffix");
let actual = nu!(r#"
with-env { FOO: "bar" } { (nu --testbin echo_env FOO) }
"#);
assert_eq!(actual.out, "bar");
}
#[rstest::rstest]
#[case("err>|")]
#[case("e>|")]
fn basic_err_pipe_works(#[case] redirection: &str) {
let actual = nu!(
r#"with-env { FOO: "bar" } { nu --testbin echo_env_stderr FOO {redirection} str length }"#
.replace("{redirection}", redirection)
);
assert_eq!(actual.out, "3");
}
#[rstest::rstest]
#[case("out+err>|")]
#[case("err+out>|")]
#[case("o+e>|")]
#[case("e+o>|")]
fn basic_outerr_pipe_works(#[case] redirection: &str) {
let actual = nu!(
r#"with-env { FOO: "bar" } { nu --testbin echo_env_mixed out-err FOO FOO {redirection} str length }"#
.replace("{redirection}", redirection)
);
assert_eq!(actual.out, "7");
}
#[test]
fn dont_run_glob_if_pass_variable_to_external() {
Playground::setup("dont_run_glob", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("jt_likes_cake.txt"),
EmptyFile("andres_likes_arepas.txt"),
]);
let actual = nu!(cwd: dirs.test(), r#"let f = "*.txt"; nu --testbin nonu $f"#);
assert_eq!(actual.out, "*.txt");
})
}
#[test]
fn run_glob_if_pass_variable_to_external() {
Playground::setup("run_glob_on_external", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("jt_likes_cake.txt"),
EmptyFile("andres_likes_arepas.txt"),
]);
let actual = nu!(cwd: dirs.test(), r#"let f = "*.txt"; nu --testbin nonu ...(glob $f)"#);
assert!(actual.out.contains("jt_likes_cake.txt"));
assert!(actual.out.contains("andres_likes_arepas.txt"));
})
}
#[test]
fn subexpression_does_not_implicitly_capture() {
let actual = nu!("(nu --testbin cococo); null");
assert_eq!(actual.out, "cococo");
}
mod it_evaluation {
use super::nu;
use nu_test_support::fs::Stub::{EmptyFile, FileWithContent, FileWithContentToBeTrimmed};
use nu_test_support::playground::Playground;
#[test]
fn takes_rows_of_nu_value_strings() {
Playground::setup("it_argument_test_1", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("jt_likes_cake.txt"),
EmptyFile("andres_likes_arepas.txt"),
]);
let actual = nu!(cwd: dirs.test(), "
ls
| sort-by name
| get name
| each { |it| nu --testbin cococo $it }
| get 1
");
assert_eq!(actual.out, "jt_likes_cake.txt");
})
}
#[test]
fn takes_rows_of_nu_value_lines() {
Playground::setup("it_argument_test_2", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"nu_candies.txt",
"
AndrásWithKitKatzz
AndrásWithKitKatz
",
)]);
let actual = nu!(cwd: dirs.test(), "
open nu_candies.txt
| lines
| each { |it| nu --testbin chop $it}
| get 1
");
assert_eq!(actual.out, "AndrásWithKitKat");
})
}
#[test]
fn can_properly_buffer_lines_externally() {
let actual = nu!("
nu --testbin repeater c 8197 | lines | length
");
assert_eq!(actual.out, "1");
}
#[test]
fn supports_fetching_given_a_column_path_to_it() {
Playground::setup("it_argument_test_3", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
"sample.toml",
r#"
nu_party_venue = "zion"
"#,
)]);
let actual = nu!(cwd: dirs.test(), "
open sample.toml
| nu --testbin cococo $in.nu_party_venue
");
assert_eq!(actual.out, "zion");
})
}
}
mod stdin_evaluation {
use super::nu;
#[test]
fn does_not_panic_with_no_newline_in_stream() {
let actual = nu!(r#"
nu --testbin nonu "where's the nuline?" | length
"#);
assert_eq!(actual.err, "");
}
#[test]
fn does_not_block_indefinitely() {
let stdout = nu!("
( nu --testbin iecho yes
| nu --testbin chop
| nu --testbin chop
| lines
| first )
")
.out;
assert_eq!(stdout, "y");
}
}
mod external_words {
use super::nu;
use nu_test_support::fs::Stub::FileWithContent;
use nu_test_support::playground::Playground;
#[test]
fn relaxed_external_words() {
let actual = nu!("
nu --testbin cococo joturner@foo.bar.baz
");
assert_eq!(actual.out, "joturner@foo.bar.baz");
}
#[test]
fn raw_string_as_external_argument() {
let actual = nu!("nu --testbin cococo r#'asdf'#");
assert_eq!(actual.out, "asdf");
}
//FIXME: jt: limitation in testing - can't use single ticks currently
#[ignore]
#[test]
fn no_escaping_for_single_quoted_strings() {
let actual = nu!(r#"
nu --testbin cococo 'test "things"'
"#);
assert_eq!(actual.out, "test \"things\"");
}
#[rstest::rstest]
#[case("sample.toml", r#""sample.toml""#)]
#[case("a sample file.toml", r#""a sample file.toml""#)]
//FIXME: jt: we don't currently support single ticks in tests
//#[case("quote'mark.toml", r#""quote'mark.toml""#)]
#[cfg_attr(
not(target_os = "windows"),
case(r#"quote"mark.toml"#, r#"$"quote(char double_quote)mark.toml""#)
)]
#[cfg_attr(not(target_os = "windows"), case("?mark.toml", r#""?mark.toml""#))]
#[cfg_attr(not(target_os = "windows"), case("*.toml", r#""*.toml""#))]
#[cfg_attr(not(target_os = "windows"), case("*.toml", "*.toml"))]
#[case("$ sign.toml", r#""$ sign.toml""#)]
fn external_arg_with_special_characters(#[case] path: &str, #[case] nu_path_argument: &str) {
Playground::setup("external_arg_with_quotes", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
path,
r#"
nu_party_venue = "zion"
"#,
)]);
let actual = nu!(
cwd: dirs.test(),
format!("nu --testbin meow {nu_path_argument} | from toml | get nu_party_venue")
);
assert_eq!(actual.out, "zion");
})
}
}
mod nu_commands {
use nu_test_support::playground::Playground;
use super::nu;
#[test]
fn echo_internally_externally() {
let actual = nu!(r#"
nu -n -c "echo 'foo'"
"#);
assert_eq!(actual.out, "foo");
}
#[test]
fn failed_with_proper_exit_code() {
Playground::setup("external failed", |dirs, _sandbox| {
let actual = nu!(cwd: dirs.test(), r#"
nu -n -c "cargo build | complete | get exit_code"
"#);
// cargo for non rust project's exit code is 101.
assert_eq!(actual.out, "101")
})
}
#[test]
fn better_arg_quoting() {
let actual = nu!(r#"
nu -n -c "\# '"
"#);
assert_eq!(actual.out, "");
}
#[test]
fn command_list_arg_test() {
let actual = nu!("
nu ...['-n' '-c' 'version']
");
assert!(actual.out.contains("version"));
assert!(actual.out.contains("rust_version"));
assert!(actual.out.contains("rust_channel"));
}
#[test]
fn command_cell_path_arg_test() {
let actual = nu!("
nu ...([ '-n' '-c' 'version' ])
");
assert!(actual.out.contains("version"));
assert!(actual.out.contains("rust_version"));
assert!(actual.out.contains("rust_channel"));
}
}
mod nu_script {
use super::nu;
#[test]
fn run_nu_script() {
let actual = nu!(cwd: "tests/fixtures/formats", "
nu -n script.nu
");
assert_eq!(actual.out, "done");
}
#[test]
fn run_nu_script_multiline() {
let actual = nu!(cwd: "tests/fixtures/formats", "
nu -n script_multiline.nu
");
assert_eq!(actual.out, "23");
}
}
mod tilde_expansion {
use super::nu;
#[test]
fn as_home_directory_when_passed_as_argument_and_begins_with_tilde() {
let actual = nu!("
nu --testbin cococo ~
");
assert!(!actual.out.contains('~'));
}
#[test]
fn does_not_expand_when_passed_as_argument_and_does_not_start_with_tilde() {
let actual = nu!(r#"
nu --testbin cococo "1~1"
"#);
assert_eq!(actual.out, "1~1");
}
}
mod external_command_arguments {
use super::nu;
use nu_test_support::fs::Stub::EmptyFile;
use nu_test_support::playground::Playground;
#[test]
fn expands_table_of_primitives_to_positional_arguments() {
Playground::setup(
"expands_table_of_primitives_to_positional_arguments",
|dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("jt_likes_cake.txt"),
EmptyFile("andres_likes_arepas.txt"),
EmptyFile("ferris_not_here.txt"),
]);
let actual = nu!(cwd: dirs.test(), "
nu --testbin cococo ...(ls | get name)
");
assert_eq!(
actual.out,
"andres_likes_arepas.txt ferris_not_here.txt jt_likes_cake.txt"
);
},
)
}
#[test]
fn proper_subexpression_paths_in_external_args() {
Playground::setup(
"expands_table_of_primitives_to_positional_arguments",
|dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("jt_likes_cake.txt"),
EmptyFile("andres_likes_arepas.txt"),
EmptyFile("ferris_not_here.txt"),
]);
let actual = nu!(cwd: dirs.test(), "
nu --testbin cococo (ls | sort-by name | get name).1
");
assert_eq!(actual.out, "ferris_not_here.txt");
},
)
}
#[cfg(not(windows))]
#[test]
fn string_interpolation_with_an_external_command() {
Playground::setup(
"string_interpolation_with_an_external_command",
|dirs, sandbox| {
sandbox.mkdir("cd");
sandbox.with_files(&[EmptyFile("cd/jt_likes_cake.txt")]);
let actual = nu!(cwd: dirs.test(), r#"
nu --testbin cococo $"(pwd)/cd"
"#);
assert!(actual.out.contains("cd"));
},
)
}
#[test]
fn semicolons_are_sanitized_before_passing_to_subshell() {
let actual = nu!("nu --testbin cococo \"a;b\"");
assert_eq!(actual.out, "a;b");
}
#[test]
fn ampersands_are_sanitized_before_passing_to_subshell() {
let actual = nu!("nu --testbin cococo \"a&b\"");
assert_eq!(actual.out, "a&b");
}
#[cfg(not(windows))]
#[test]
fn subcommands_are_sanitized_before_passing_to_subshell() {
let actual = nu!("nu --testbin cococo \"$(ls)\"");
assert_eq!(actual.out, "$(ls)");
}
#[cfg(not(windows))]
#[test]
fn shell_arguments_are_sanitized_even_if_coming_from_other_commands() {
let actual = nu!("nu --testbin cococo (echo \"a;&$(hello)\")");
assert_eq!(actual.out, "a;&$(hello)");
}
#[test]
fn remove_quotes_in_shell_arguments() {
let actual = nu!("nu --testbin cococo expression='-r -w'");
assert_eq!(actual.out, "expression=-r -w");
let actual = nu!(r#"nu --testbin cococo expression="-r -w""#);
assert_eq!(actual.out, "expression=-r -w");
let actual = nu!("nu --testbin cococo expression='-r -w'");
assert_eq!(actual.out, "expression=-r -w");
let actual = nu!(r#"nu --testbin cococo expression="-r\" -w""#);
assert_eq!(actual.out, r#"expression=-r" -w"#);
let actual = nu!(r#"nu --testbin cococo expression='-r\" -w'"#);
assert_eq!(actual.out, r#"expression=-r\" -w"#);
}
}
#[test]
fn exit_code_stops_execution_closure() {
let actual = nu!("[1 2] | each {|x| nu -c $'exit ($x)'; print $x }");
assert!(actual.out.is_empty());
assert!(actual.err.contains("exited with code 1"));
}
#[test]
fn exit_code_stops_execution_custom_command() {
let actual = nu!("def cmd [] { nu -c 'exit 42'; 'ok1' }; cmd; print 'ok2'");
assert!(actual.out.is_empty());
assert!(!actual.err.contains("exited with code 42"));
}
#[test]
fn exit_code_stops_execution_for_loop() {
let actual = nu!("for x in [0 1] { nu -c 'exit 42'; print $x }");
assert!(actual.out.is_empty());
assert!(!actual.err.contains("exited with code 42"));
}
#[test]
fn display_error_with_exit_code_stops() {
Playground::setup("errexit", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
"tmp_env.nu",
"$env.config.display_errors.exit_code = true",
)]);
let actual = nu!(
env_config: "tmp_env.nu",
cwd: dirs.test(),
"def cmd [] { nu -c 'exit 42'; 'ok1' }; cmd; print 'ok2'",
);
assert!(actual.err.contains("exited with code"));
assert_eq!(actual.out, "");
});
}
#[test]
fn display_error_exit_code_stops_execution_for_loop() {
Playground::setup("errexit", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
"tmp_env.nu",
"$env.config.display_errors.exit_code = true",
)]);
let actual = nu!(
env_config: "tmp_env.nu",
cwd: dirs.test(),
"for x in [0 1] { nu -c 'exit 42'; print $x }",
);
assert!(actual.err.contains("exited with code"));
assert_eq!(actual.out, "");
});
}
#[test]
fn arg_dont_run_subcommand_if_surrounded_with_quote() {
let actual = nu!("nu --testbin cococo `(echo aa)`");
assert_eq!(actual.out, "(echo aa)");
let actual = nu!("nu --testbin cococo \"(echo aa)\"");
assert_eq!(actual.out, "(echo aa)");
let actual = nu!("nu --testbin cococo '(echo aa)'");
assert_eq!(actual.out, "(echo aa)");
}
#[test]
fn external_error_with_backtrace() {
Playground::setup("external error with backtrace", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent("tmp_env.nu", "$env.NU_BACKTRACE = 1")]);
let actual = nu!(
env_config: "tmp_env.nu",
cwd: dirs.test(),
r#"def a [x] { if $x == 3 { nu --testbin --fail }};def b [] {a 1; a 3; a 2}; b"#);
let chained_error_cnt: Vec<&str> = actual
.err
.matches("diagnostic code: chained_error")
.collect();
assert_eq!(chained_error_cnt.len(), 1);
assert!(actual.err.contains("non_zero_exit_code"));
let eval_with_input_cnt: Vec<&str> = actual.err.matches("eval_block_with_input").collect();
assert_eq!(eval_with_input_cnt.len(), 1);
let actual = nu!(
env_config: "tmp_env.nu",
cwd: dirs.test(),
r#"nu --testbin --fail"#);
let chained_error_cnt: Vec<&str> = actual
.err
.matches("diagnostic code: chained_error")
.collect();
// run error make directly, show no backtrace is available
assert_eq!(chained_error_cnt.len(), 0);
});
}
#[test]
fn sub_external_expression_with_and_op_should_raise_proper_error() {
let actual = nu!("(nu --testbin cococo false) and true");
assert!(
actual
.err
.contains("The 'and' operator does not work on values of type 'string'")
)
}
#[test]
fn bad_config_file_restrict_cmd_running_with_commands() {
Playground::setup("bad config file", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent("tmp_env.nu", "errorcmd")]);
let actual = nu!(
env_config: "tmp_env.nu",
cwd: dirs.test(),
r#"print bbb"#);
assert!(actual.err.contains("Command `errorcmd` not found"));
assert!(!actual.out.contains("bbb"));
assert!(!actual.status.success());
});
let actual = nu!(env_config: "not_exists.nu", "print bbb");
assert!(actual.err.contains("File not found: not_exists.nu"));
assert!(!actual.out.contains("bbb"));
assert!(!actual.status.success());
}
// FIXME: ignore these cases for now, the value inside a pipeline
// makes all previous exit status untracked.
// #[case("nu --testbin fail 10 | nu --testbin fail 20 | 10", 10)]
// #[case("nu --testbin fail 20 | 10 | nu --testbin fail", 20)]
// #[case("30 | nu --testbin fail | nu --testbin fail 30", 1)]
#[rstest]
#[case("nu --testbin fail | print aa", 1)]
#[case("nu --testbin nonu a | print bb", 0)]
#[case("nu --testbin fail 30 | nu --testbin nonu a | print aa", 30)]
#[case("print aa | print cc | nu --testbin fail 40", 40)]
#[case("nu --testbin fail 20 | print aa | nu --testbin fail", 1)]
#[case("nu --testbin fail | print aa | nu --testbin fail 20", 20)]
#[case("let x = nu --testbin fail 20 | into int", 20)]
fn pipefail_feature(#[case] inp: &str, #[case] expect_code: i32) {
let actual = nu!(
experimental: vec!["pipefail".to_string()],
inp
);
assert_eq!(
actual
.status
.code()
.expect("exit_status should not be none"),
expect_code
);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/shell/pipeline/commands/internal.rs | tests/shell/pipeline/commands/internal.rs | use nu_test_support::fs::Stub::{FileWithContent, FileWithContentToBeTrimmed};
use nu_test_support::nu;
use nu_test_support::playground::Playground;
use pretty_assertions::assert_eq;
#[test]
fn takes_rows_of_nu_value_strings_and_pipes_it_to_stdin_of_external() {
let actual = nu!(r###"
[
[name rusty_luck origin];
[Jason 1 Canada]
[JT 1 "New Zealand"]
[Andrés 1 Ecuador]
[AndKitKatz 1 "Estados Unidos"]
]
| get origin
| each {|it| nu --testbin cococo $it | nu --testbin chop}
| get 2
"###);
// chop will remove the last escaped double quote from \"Estados Unidos\"
assert_eq!(actual.out, "Ecuado");
}
#[test]
fn treats_dot_dot_as_path_not_range() {
Playground::setup("dot_dot_dir", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"nu_times.csv",
"
name,rusty_luck,origin
Jason,1,Canada
",
)]);
let actual = nu!(cwd: dirs.test(), "
mkdir temp;
cd temp;
print (open ../nu_times.csv).name.0 | table;
cd ..;
rmdir temp
");
// chop will remove the last escaped double quote from \"Estados Unidos\"
assert_eq!(actual.out, "Jason");
})
}
#[test]
fn subexpression_properly_redirects() {
let actual = nu!(r#"
echo (nu --testbin cococo "hello") | str join
"#);
assert_eq!(actual.out, "hello");
}
#[test]
fn argument_subexpression() {
let actual = nu!(r#"
echo "foo" | each { |it| echo (echo $it) }
"#);
assert_eq!(actual.out, "foo");
}
#[test]
fn for_loop() {
let actual = nu!("
for i in 1..3 { print $i }
");
assert_eq!(actual.out, "123");
}
#[test]
fn subexpression_handles_dot() {
Playground::setup("subexpression_handles_dot", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"nu_times.csv",
"
name,rusty_luck,origin
Jason,1,Canada
JT,1,New Zealand
Andrés,1,Ecuador
AndKitKatz,1,Estados Unidos
",
)]);
let actual = nu!(cwd: dirs.test(), "
echo (open nu_times.csv)
| get name
| each { |it| nu --testbin chop $it }
| get 3
");
assert_eq!(actual.out, "AndKitKat");
});
}
#[test]
fn string_interpolation_with_it() {
let actual = nu!(r#"
echo "foo" | each { |it| echo $"($it)" }
"#);
assert_eq!(actual.out, "foo");
}
#[test]
fn string_interpolation_with_it_column_path() {
let actual = nu!(r#"
echo [[name]; [sammie]] | each { |it| echo $"($it.name)" } | get 0
"#);
assert_eq!(actual.out, "sammie");
}
#[test]
fn string_interpolation_shorthand_overlap() {
let actual = nu!(r#"
$"3 + 4 = (3 + 4)"
"#);
assert_eq!(actual.out, "3 + 4 = 7");
}
// FIXME: jt - we don't currently have a way to escape the single ticks easily
#[ignore]
#[test]
fn string_interpolation_and_paren() {
let actual = nu!(r#"
$"a paren is ('(')"
"#);
assert_eq!(actual.out, "a paren is (");
}
#[test]
fn string_interpolation_with_unicode() {
//カ = U+30AB : KATAKANA LETTER KA
let actual = nu!(r#"
$"カ"
"#);
assert_eq!(actual.out, "カ");
}
#[test]
fn run_custom_command() {
let actual = nu!("
def add-me [x y] { $x + $y}; add-me 10 5
");
assert_eq!(actual.out, "15");
}
#[test]
fn run_custom_command_with_flag() {
let actual = nu!(r#"
def foo [--bar:number] { if ($bar | is-empty) { echo "empty" } else { echo $bar } }; foo --bar 10
"#);
assert_eq!(actual.out, "10");
}
#[test]
fn run_custom_command_with_flag_missing() {
let actual = nu!(r#"
def foo [--bar:number] { if ($bar | is-empty) { echo "empty" } else { echo $bar } }; foo
"#);
assert_eq!(actual.out, "empty");
}
#[test]
fn run_custom_subcommand() {
let actual = nu!(r#"
def "str double" [x] { echo $x $x | str join }; str double bob
"#);
assert_eq!(actual.out, "bobbob");
}
#[test]
fn run_inner_custom_command() {
let actual = nu!("
def outer [x] { def inner [y] { echo $y }; inner $x }; outer 10
");
assert_eq!(actual.out, "10");
}
#[test]
fn run_broken_inner_custom_command() {
let actual = nu!("
def outer [x] { def inner [y] { echo $y }; inner $x }; inner 10
");
assert!(!actual.err.is_empty());
}
#[test]
fn run_custom_command_with_rest() {
let actual = nu!(r#"
def rest-me [...rest: string] { echo $rest.1 $rest.0}; rest-me "hello" "world" | to json --raw
"#);
assert_eq!(actual.out, r#"["world","hello"]"#);
}
#[test]
fn run_custom_command_with_rest_and_arg() {
let actual = nu!(r#"
def rest-me-with-arg [name: string, ...rest: string] { echo $rest.1 $rest.0 $name}; rest-me-with-arg "hello" "world" "yay" | to json --raw
"#);
assert_eq!(actual.out, r#"["yay","world","hello"]"#);
}
#[test]
fn run_custom_command_with_rest_and_flag() {
let actual = nu!(r#"
def rest-me-with-flag [--name: string, ...rest: string] { echo $rest.1 $rest.0 $name}; rest-me-with-flag "hello" "world" --name "yay" | to json --raw
"#);
assert_eq!(actual.out, r#"["world","hello","yay"]"#);
}
#[test]
fn run_custom_command_with_empty_rest() {
let actual = nu!("
def rest-me-with-empty-rest [...rest: string] { $rest }; rest-me-with-empty-rest | is-empty
");
assert_eq!(actual.out, "true");
assert_eq!(actual.err, "");
}
//FIXME: jt: blocked on https://github.com/nushell/engine-q/issues/912
#[ignore]
#[test]
fn run_custom_command_with_rest_other_name() {
let actual = nu!(r#"
def say-hello [
greeting:string,
...names:string # All of the names
] {
echo $"($greeting), ($names | sort-by | str join)"
}
say-hello Salutations E D C A B
"#);
assert_eq!(actual.out, "Salutations, ABCDE");
assert_eq!(actual.err, "");
}
#[test]
fn alias_a_load_env() {
let actual = nu!("
def activate-helper [] { {BOB: SAM} }; alias activate = load-env (activate-helper); activate; $env.BOB
");
assert_eq!(actual.out, "SAM");
}
#[test]
fn let_variable() {
let actual = nu!("
let x = 5
let y = 12
$x + $y
");
assert_eq!(actual.out, "17");
}
#[test]
fn let_doesnt_leak() {
let actual = nu!("
do { let x = 5 }; echo $x
");
assert!(actual.err.contains("variable not found"));
}
#[test]
fn mutate_env_variable() {
let actual = nu!(r#"
$env.TESTENVVAR = "hello world"
echo $env.TESTENVVAR
"#);
assert_eq!(actual.out, "hello world");
}
#[test]
fn mutate_env_hides_variable() {
let actual = nu!(r#"
$env.TESTENVVAR = "hello world"
print $env.TESTENVVAR
hide-env TESTENVVAR
print $env.TESTENVVAR
"#);
assert_eq!(actual.out, "hello world");
assert!(actual.err.contains("not_found"));
}
#[test]
fn mutate_env_hides_variable_in_parent_scope() {
let actual = nu!(r#"
$env.TESTENVVAR = "hello world"
print $env.TESTENVVAR
do {
hide-env TESTENVVAR
print $env.TESTENVVAR
}
print $env.TESTENVVAR
"#);
assert_eq!(actual.out, "hello world");
assert!(actual.err.contains("not_found"));
}
#[test]
fn unlet_env_variable() {
let actual = nu!(r#"
$env.TEST_VAR = "hello world"
hide-env TEST_VAR
echo $env.TEST_VAR
"#);
assert!(actual.err.contains("not_found"));
}
#[test]
#[ignore]
fn unlet_nonexistent_variable() {
let actual = nu!("
hide-env NONEXISTENT_VARIABLE
");
assert!(actual.err.contains("did not find"));
}
#[test]
fn unlet_variable_in_parent_scope() {
let actual = nu!(r#"
$env.DEBUG = "1"
print $env.DEBUG
do {
$env.DEBUG = "2"
print $env.DEBUG
hide-env DEBUG
print $env.DEBUG
}
print $env.DEBUG
"#);
assert_eq!(actual.out, "1211");
}
#[test]
fn mutate_env_doesnt_leak() {
let actual = nu!(r#"
do { $env.xyz = "my message" }; echo $env.xyz
"#);
assert!(actual.err.contains("not_found"));
}
#[test]
fn proper_shadow_mutate_env_aliases() {
let actual = nu!(r#"
$env.DEBUG = "true"; print $env.DEBUG | table; do { $env.DEBUG = "false"; print $env.DEBUG } | table; print $env.DEBUG
"#);
assert_eq!(actual.out, "truefalsetrue");
}
#[test]
fn load_env_variable() {
let actual = nu!(r#"
echo {TESTENVVAR: "hello world"} | load-env
echo $env.TESTENVVAR
"#);
assert_eq!(actual.out, "hello world");
}
#[test]
fn load_env_variable_arg() {
let actual = nu!(r#"
load-env {TESTENVVAR: "hello world"}
echo $env.TESTENVVAR
"#);
assert_eq!(actual.out, "hello world");
}
#[test]
fn load_env_doesnt_leak() {
let actual = nu!(r#"
do { echo { name: xyz, value: "my message" } | load-env }; echo $env.xyz
"#);
assert!(actual.err.contains("not_found"));
}
#[test]
fn proper_shadow_load_env_aliases() {
let actual = nu!(r#"
$env.DEBUG = "true"; print $env.DEBUG | table; do { echo {DEBUG: "false"} | load-env; print $env.DEBUG } | table; print $env.DEBUG
"#);
assert_eq!(actual.out, "truefalsetrue");
}
//FIXME: jt: load-env can not currently hide variables because null no longer hides
#[ignore]
#[test]
fn load_env_can_hide_var_envs() {
let actual = nu!(r#"
$env.DEBUG = "1"
echo $env.DEBUG
load-env [[name, value]; [DEBUG null]]
echo $env.DEBUG
"#);
assert_eq!(actual.out, "1");
assert!(actual.err.contains("error"));
assert!(actual.err.contains("Unknown column"));
}
//FIXME: jt: load-env can not currently hide variables because null no longer hides
#[ignore]
#[test]
fn load_env_can_hide_var_envs_in_parent_scope() {
let actual = nu!(r#"
$env.DEBUG = "1"
echo $env.DEBUG
do {
load-env [[name, value]; [DEBUG null]]
echo $env.DEBUG
}
echo $env.DEBUG
"#);
assert_eq!(actual.out, "11");
assert!(actual.err.contains("error"));
assert!(actual.err.contains("Unknown column"));
}
#[test]
fn proper_shadow_let_aliases() {
let actual = nu!("
let DEBUG = false; print $DEBUG | table; do { let DEBUG = true; print $DEBUG } | table; print $DEBUG
");
assert_eq!(actual.out, "falsetruefalse");
}
#[test]
fn block_params_override() {
let actual = nu!("
[1, 2, 3] | each { |a| echo $it }
");
assert!(actual.err.contains("variable not found"));
}
#[test]
fn alias_reuse() {
let actual = nu!("alias foo = echo bob; foo; foo");
assert!(actual.out.contains("bob"));
assert!(actual.err.is_empty());
}
#[test]
fn block_params_override_correct() {
let actual = nu!("
[1, 2, 3] | each { |a| echo $a } | to json --raw
");
assert_eq!(actual.out, "[1,2,3]");
}
#[test]
fn hex_number() {
let actual = nu!("
0x10
");
assert_eq!(actual.out, "16");
}
#[test]
fn binary_number() {
let actual = nu!("
0b10
");
assert_eq!(actual.out, "2");
}
#[test]
fn octal_number() {
let actual = nu!("
0o10
");
assert_eq!(actual.out, "8");
}
#[test]
fn run_dynamic_closures() {
let actual = nu!(r#"
let closure = {|| echo "holaaaa" }; do $closure
"#);
assert_eq!(actual.out, "holaaaa");
}
#[test]
fn dynamic_closure_type_check() {
let actual = nu!(r#"let closure = {|x: int| echo $x}; do $closure "aa""#);
assert!(actual.err.contains("can't convert string to int"))
}
#[test]
fn dynamic_closure_optional_arg() {
let actual = nu!(r#"let closure = {|x: int = 3| echo $x}; do $closure"#);
assert_eq!(actual.out, "3");
let actual = nu!(r#"let closure = {|x: int = 3| echo $x}; do $closure 10"#);
assert_eq!(actual.out, "10");
}
#[test]
fn dynamic_closure_rest_args() {
let actual = nu!(r#"let closure = {|...args| $args | str join ""}; do $closure 1 2 3"#);
assert_eq!(actual.out, "123");
let actual = nu!(
r#"let closure = {|required, ...args| $"($required), ($args | str join "")"}; do $closure 1 2 3"#
);
assert_eq!(actual.out, "1, 23");
let actual = nu!(
r#"let closure = {|required, optional?, ...args| $"($required), ($optional), ($args | str join "")"}; do $closure 1 2 3"#
);
assert_eq!(actual.out, "1, 2, 3");
}
#[test]
fn argument_subexpression_reports_errors() {
let actual = nu!("echo (ferris_is_not_here.exe)");
assert!(!actual.err.is_empty());
}
#[test]
fn can_process_one_row_from_internal_and_pipes_it_to_stdin_of_external() {
let actual = nu!(r#""nushelll" | nu --testbin chop"#);
assert_eq!(actual.out, "nushell");
}
#[test]
fn bad_operator() {
let actual = nu!("
2 $ 2
");
assert!(actual.err.contains("operator"));
}
#[test]
fn index_out_of_bounds() {
let actual = nu!("
let foo = [1, 2, 3]; echo $foo.5
");
assert!(actual.err.contains("too large"));
}
#[test]
fn negative_float_start() {
let actual = nu!("
-1.3 + 4
");
assert_eq!(actual.out, "2.7");
}
#[test]
fn string_inside_of() {
let actual = nu!(r#"
"bob" in "bobby"
"#);
assert_eq!(actual.out, "true");
}
#[test]
fn string_not_inside_of() {
let actual = nu!(r#"
"bob" not-in "bobby"
"#);
assert_eq!(actual.out, "false");
}
#[test]
fn index_row() {
let actual = nu!("
let foo = [[name]; [joe] [bob]]; echo $foo.1 | to json --raw
");
assert_eq!(actual.out, r#"{"name":"bob"}"#);
}
#[test]
fn index_cell() {
let actual = nu!("
let foo = [[name]; [joe] [bob]]; echo $foo.name.1
");
assert_eq!(actual.out, "bob");
}
#[test]
fn index_cell_alt() {
let actual = nu!("
let foo = [[name]; [joe] [bob]]; echo $foo.1.name
");
assert_eq!(actual.out, "bob");
}
#[test]
fn not_echoing_ranges_without_numbers() {
let actual = nu!("
echo ..
");
assert_eq!(actual.out, "..");
}
#[test]
fn not_echoing_exclusive_ranges_without_numbers() {
let actual = nu!("
echo ..<
");
assert_eq!(actual.out, "..<");
}
#[test]
fn echoing_ranges() {
let actual = nu!("
echo 1..3 | math sum
");
assert_eq!(actual.out, "6");
}
#[test]
fn echoing_exclusive_ranges() {
let actual = nu!("
echo 1..<4 | math sum
");
assert_eq!(actual.out, "6");
}
#[test]
fn table_literals1() {
let actual = nu!("
echo [[name age]; [foo 13]] | get age.0
");
assert_eq!(actual.out, "13");
}
#[test]
fn table_literals2() {
let actual = nu!("
echo [[name age] ; [bob 13] [sally 20]] | get age | math sum
");
assert_eq!(actual.out, "33");
}
#[test]
fn list_with_commas() {
let actual = nu!("
echo [1, 2, 3] | math sum
");
assert_eq!(actual.out, "6");
}
#[test]
fn range_with_left_var() {
let actual = nu!("
({ size: 3}.size)..10 | math sum
");
assert_eq!(actual.out, "52");
}
#[test]
fn range_with_right_var() {
let actual = nu!("
4..({ size: 30}.size) | math sum
");
assert_eq!(actual.out, "459");
}
#[test]
fn range_with_open_left() {
let actual = nu!("
echo ..30 | math sum
");
assert_eq!(actual.out, "465");
}
#[test]
fn exclusive_range_with_open_left() {
let actual = nu!("
echo ..<31 | math sum
");
assert_eq!(actual.out, "465");
}
#[test]
fn range_with_open_right() {
let actual = nu!("
echo 5.. | first 10 | math sum
");
assert_eq!(actual.out, "95");
}
#[test]
fn exclusive_range_with_open_right() {
let actual = nu!("
echo 5..< | first 10 | math sum
");
assert_eq!(actual.out, "95");
}
#[test]
fn range_with_mixed_types() {
let actual = nu!("
echo 1..10.5 | math sum
");
assert_eq!(actual.out, "55.0");
}
#[test]
fn filesize_math() {
let actual = nu!("100 * 10kB");
assert_eq!(actual.out, "1.0 MB");
}
#[test]
fn filesize_math2() {
let actual = nu!("100 / 10kB");
assert!(
actual
.err
.contains("nu::parser::operator_incompatible_types")
);
}
#[test]
fn filesize_math3() {
let actual = nu!("100kB / 10");
assert_eq!(actual.out, "10.0 kB");
}
#[test]
fn filesize_math4() {
let actual = nu!("100kB * 5");
assert_eq!(actual.out, "500.0 kB");
}
#[test]
fn filesize_math5() {
let actual = nu!("100 * 1kB");
assert_eq!(actual.out, "100.0 kB");
}
#[test]
fn exclusive_range_with_mixed_types() {
let actual = nu!("
echo 1..<10.5 | math sum
");
assert_eq!(actual.out, "55.0");
}
#[test]
fn table_with_commas() {
let actual = nu!("
echo [[name, age, height]; [JT, 42, 185] [Unknown, 99, 99]] | get age | math sum
");
assert_eq!(actual.out, "141");
}
#[test]
fn duration_overflow() {
let actual = nu!("
ls | get modified | each { |it| $it + 10000000000000000day }
");
assert!(actual.err.contains("duration too large"));
}
#[test]
fn date_and_duration_overflow() {
let actual = nu!("
ls | get modified | each { |it| $it + 1000000000day }
");
// assert_eq!(actual.err, "overflow");
assert!(actual.err.contains("duration too large"));
}
#[test]
fn pipeline_params_simple() {
let actual = nu!("
echo 1 2 3 | $in.1 * $in.2
");
assert_eq!(actual.out, "6");
}
#[test]
fn pipeline_params_inner() {
let actual = nu!("
echo 1 2 3 | (echo $in.2 6 7 | $in.0 * $in.1 * $in.2)
");
assert_eq!(actual.out, "126");
}
#[test]
fn better_table_lex() {
let actual = nu!("
let table = [
[name, size];
[small, 7]
[medium, 10]
[large, 12]
];
$table.1.size
");
assert_eq!(actual.out, "10");
}
#[test]
fn better_subexpr_lex() {
let actual = nu!("
(echo boo
sam | str length | math sum)
");
assert_eq!(actual.out, "6");
}
#[test]
fn subsubcommand() {
let actual = nu!(r#"
def "aws s3 rb" [url] { $url + " loaded" }; aws s3 rb localhost
"#);
assert_eq!(actual.out, "localhost loaded");
}
#[test]
fn manysubcommand() {
let actual = nu!(r#"
def "aws s3 rb ax vf qqqq rrrr" [url] { $url + " loaded" }; aws s3 rb ax vf qqqq rrrr localhost
"#);
assert_eq!(actual.out, "localhost loaded");
}
#[test]
fn nothing_string_1() {
let actual = nu!(r#"
null == "foo"
"#);
assert_eq!(actual.out, "false");
}
#[test]
fn hide_alias_shadowing() {
let actual = nu!("
def test-shadowing [] {
alias greet = echo hello;
let xyz = {|| greet };
hide greet;
do $xyz
};
test-shadowing
");
assert_eq!(actual.out, "hello");
}
// FIXME: Seems like subexpression are no longer scoped. Should we remove this test?
#[ignore]
#[test]
fn hide_alias_does_not_escape_scope() {
let actual = nu!("
def test-alias [] {
alias greet = echo hello;
(hide greet);
greet
};
test-alias
");
assert_eq!(actual.out, "hello");
}
#[test]
fn hide_alias_hides_alias() {
let actual = nu!("
def test-alias [] {
alias ll = ls -l;
hide ll;
ll
};
test-alias
");
assert!(
actual.err.contains("Command `ll` not found") && actual.err.contains("Did you mean `all`?")
);
}
mod parse {
use nu_test_support::nu;
/*
The debug command's signature is:
Usage:
> debug {flags}
flags:
-h, --help: Display the help message for this command
-r, --raw: Prints the raw value representation.
*/
#[test]
fn errors_if_flag_passed_is_not_exact() {
let actual = nu!("debug -ra");
assert!(actual.err.contains("unknown flag"),);
let actual = nu!("debug --rawx");
assert!(actual.err.contains("unknown flag"),);
}
#[test]
fn errors_if_flag_is_not_supported() {
let actual = nu!("debug --ferris");
assert!(actual.err.contains("unknown flag"),);
}
#[test]
fn errors_if_passed_an_unexpected_argument() {
let actual = nu!("debug ferris");
assert!(actual.err.contains("extra positional argument"),);
}
#[test]
fn ensure_backticks_are_bareword_command() {
let actual = nu!("`8abc123`");
assert!(actual.err.contains("Command `8abc123` not found"),);
}
}
mod tilde_expansion {
use nu_test_support::nu;
#[test]
#[should_panic]
fn as_home_directory_when_passed_as_argument_and_begins_with_tilde() {
let actual = nu!("
echo ~
");
assert!(!actual.out.contains('~'),);
}
#[test]
fn does_not_expand_when_passed_as_argument_and_does_not_start_with_tilde() {
let actual = nu!(r#"
echo "1~1"
"#);
assert_eq!(actual.out, "1~1");
}
}
mod variable_scoping {
use nu_test_support::nu;
fn test_variable_scope(code: &str, expected: &str) {
let actual = nu!(code);
assert_eq!(actual.out, expected);
}
fn test_variable_scope_list(code: &str, expected: &[&str]) {
let actual = nu!(code);
let result: Vec<&str> = actual.out.matches("ZZZ").collect();
assert_eq!(result, expected);
}
#[test]
fn access_variables_in_scopes() {
test_variable_scope(
" def test [input] { echo [0 1 2] | do { do { echo $input } } }
test ZZZ ",
"ZZZ",
);
test_variable_scope(
r#" def test [input] { echo [0 1 2] | do { do { if $input == "ZZZ" { echo $input } else { echo $input } } } }
test ZZZ "#,
"ZZZ",
);
test_variable_scope(
r#" def test [input] { echo [0 1 2] | do { do { if $input == "ZZZ" { echo $input } else { echo $input } } } }
test ZZZ "#,
"ZZZ",
);
test_variable_scope(
" def test [input] { echo [0 1 2] | do { echo $input } }
test ZZZ ",
"ZZZ",
);
test_variable_scope(
" def test [input] { echo [0 1 2] | do { if $input == $input { echo $input } else { echo $input } } }
test ZZZ ",
"ZZZ"
);
test_variable_scope_list(
" def test [input] { echo [0 1 2] | each { |_| echo $input } }
test ZZZ ",
&["ZZZ", "ZZZ", "ZZZ"],
);
test_variable_scope_list(
" def test [input] { echo [0 1 2] | each { |it| if $it > 0 {echo $input} else {echo $input}} }
test ZZZ ",
&["ZZZ", "ZZZ", "ZZZ"],
);
test_variable_scope_list(
" def test [input] { echo [0 1 2] | each { |_| if $input == $input {echo $input} else {echo $input}} }
test ZZZ ",
&["ZZZ", "ZZZ", "ZZZ"],
);
}
}
#[test]
fn pipe_input_to_print() {
let actual = nu!(r#""foo" | print"#);
assert_eq!(actual.out, "foo");
assert!(actual.err.is_empty());
}
#[test]
fn err_pipe_input_to_print() {
let actual = nu!(r#""foo" e>| print"#);
assert!(actual.err.contains("only works on external commands"));
}
#[test]
fn outerr_pipe_input_to_print() {
let actual = nu!(r#""foo" o+e>| print"#);
assert!(actual.err.contains("only works on external commands"));
}
#[test]
fn command_not_found_error_shows_not_found_2() {
let actual = nu!(r#"
export def --wrapped my-foo [...rest] { foo };
my-foo
"#);
assert!(
actual.err.contains("Command `foo` not found")
&& actual.err.contains("Did you mean `for`?")
);
}
#[test]
fn error_on_out_greater_pipe() {
let actual = nu!(r#""foo" o>| print"#);
assert!(
actual
.err
.contains("Redirecting stdout to a pipe is the same as normal piping")
)
}
#[test]
fn error_with_backtrace() {
Playground::setup("error with backtrace", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent("tmp_env.nu", "$env.NU_BACKTRACE = 1")]);
let actual = nu!(
env_config: "tmp_env.nu",
cwd: dirs.test(),
r#"def a [x] { if $x == 3 { error make {msg: 'a custom error'}}};a 3"#);
let chained_error_cnt: Vec<&str> = actual
.err
.matches("diagnostic code: chained_error")
.collect();
// run `a 3`, and it raises error, so there should be 1.
assert_eq!(chained_error_cnt.len(), 1);
assert!(actual.err.contains("a custom error"));
let actual = nu!(
env_config: "tmp_env.nu",
cwd: dirs.test(),
r#"def a [x] { if $x == 3 { error make {msg: 'a custom error'}}};def b [] { a 1; a 3; a 2 };b"#);
let chained_error_cnt: Vec<&str> = actual
.err
.matches("diagnostic code: chained_error")
.collect();
// run `b`, it runs `a 3`, and it raises error, so there should be 2.
assert_eq!(chained_error_cnt.len(), 2);
assert!(actual.err.contains("a custom error"));
let actual = nu!(
env_config: "tmp_env.nu",
cwd: dirs.test(),
r#"error make {msg: 'a custom err'}"#);
let chained_error_cnt: Vec<&str> = actual
.err
.matches("diagnostic code: chained_error")
.collect();
// run error make directly, show no backtrace is available
assert_eq!(chained_error_cnt.len(), 0);
});
}
#[test]
fn liststream_error_with_backtrace_custom() {
Playground::setup("liststream error with backtrace", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent("tmp_env.nu", "$env.NU_BACKTRACE = 1")]);
let actual = nu!(
env_config: "tmp_env.nu",
cwd: dirs.test(),
r#"def a [x] { if $x == 3 { [1] | each {error make {'msg': 'a custom error'}}}};a 3"#);
assert!(actual.err.contains("a custom error"));
});
}
#[test]
fn liststream_error_with_backtrace_function() {
Playground::setup("liststream error with backtrace", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent("tmp_env.nu", "$env.NU_BACKTRACE = 1")]);
let actual = nu!(
env_config: "tmp_env.nu",
cwd: dirs.test(),
r#"def a [x] {
if $x == 3 {
[1]
| each {
error make {
msg: 'a custom error'
}
}
}
}
def b [] {
a 1
a 3
a 2
}
b
"#);
let chained_error_cnt: Vec<&str> = actual
.err
.matches("diagnostic code: chained_error")
.collect();
assert_eq!(chained_error_cnt.len(), 1);
assert!(actual.err.contains("a custom error"));
let eval_with_input_cnt: Vec<&str> = actual.err.matches("eval_block_with_input").collect();
assert_eq!(eval_with_input_cnt.len(), 2);
});
}
#[test]
fn liststream_error_with_backtrace_single_stream() {
Playground::setup("liststream error with backtrace", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent("tmp_env.nu", "$env.NU_BACKTRACE = 1")]);
let actual = nu!(
env_config: "tmp_env.nu",
cwd: dirs.test(),
r#"[1] | each { error make {msg: 'a custom err'} }"#);
let chained_error_cnt: Vec<&str> = actual
.err
.matches("diagnostic code: chained_error")
.collect();
// run error make directly, show no backtrace is available
assert_eq!(chained_error_cnt.len(), 0);
});
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/tests/shell/pipeline/commands/mod.rs | tests/shell/pipeline/commands/mod.rs | mod external;
mod internal;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/benches/benchmarks.rs | benches/benchmarks.rs | use nu_cli::{eval_source, evaluate_commands};
use nu_plugin_core::{Encoder, EncodingType};
use nu_plugin_protocol::{PluginCallResponse, PluginOutput};
use nu_protocol::{
PipelineData, Signals, Span, Spanned, Value,
engine::{EngineState, Stack},
};
use nu_std::load_standard_library;
use nu_utils::ConfigFileKind;
use std::{
fmt::Write,
hint::black_box,
rc::Rc,
sync::{Arc, atomic::AtomicBool},
};
use tango_bench::{IntoBenchmarks, benchmark_fn, tango_benchmarks, tango_main};
fn load_bench_commands() -> EngineState {
nu_command::add_shell_command_context(nu_cmd_lang::create_default_context())
}
fn setup_engine() -> EngineState {
let mut engine_state = load_bench_commands();
let cwd = std::env::current_dir()
.unwrap()
.into_os_string()
.into_string()
.unwrap();
// parsing config.nu breaks without PWD set, so set a valid path
engine_state.add_env_var("PWD".into(), Value::string(cwd, Span::test_data()));
engine_state.generate_nu_constant();
engine_state
}
fn setup_stack_and_engine_from_command(command: &str) -> (Stack, EngineState) {
let mut engine = setup_engine();
let commands = Spanned {
span: Span::unknown(),
item: command.to_string(),
};
let mut stack = Stack::new();
evaluate_commands(
&commands,
&mut engine,
&mut stack,
PipelineData::empty(),
Default::default(),
)
.unwrap();
(stack, engine)
}
// generate a new table data with `row_cnt` rows, `col_cnt` columns.
fn encoding_test_data(row_cnt: usize, col_cnt: usize) -> Value {
let record = Value::test_record(
(0..col_cnt)
.map(|x| (format!("col_{x}"), Value::test_int(x as i64)))
.collect(),
);
Value::list(vec![record; row_cnt], Span::test_data())
}
fn bench_command(
name: impl Into<String>,
command: impl Into<String> + Clone,
stack: Stack,
engine: EngineState,
) -> impl IntoBenchmarks {
let commands = Spanned {
span: Span::unknown(),
item: command.into(),
};
[benchmark_fn(name, move |b| {
let commands = commands.clone();
let stack = stack.clone();
let engine = engine.clone();
b.iter(move || {
let mut stack = stack.clone();
let mut engine = engine.clone();
#[allow(clippy::unit_arg)]
black_box(
evaluate_commands(
&commands,
&mut engine,
&mut stack,
PipelineData::empty(),
Default::default(),
)
.unwrap(),
);
})
})]
}
fn bench_eval_source(
name: &str,
fname: String,
source: Vec<u8>,
stack: Stack,
engine: EngineState,
) -> impl IntoBenchmarks {
[benchmark_fn(name, move |b| {
let stack = stack.clone();
let engine = engine.clone();
let fname = fname.clone();
let source = source.clone();
b.iter(move || {
let mut stack = stack.clone();
let mut engine = engine.clone();
let fname: &str = &fname.clone();
let source: &[u8] = &source.clone();
black_box(eval_source(
&mut engine,
&mut stack,
source,
fname,
PipelineData::empty(),
false,
));
})
})]
}
/// Load the standard library into the engine.
fn bench_load_standard_lib() -> impl IntoBenchmarks {
[benchmark_fn("load_standard_lib", move |b| {
let engine = setup_engine();
b.iter(move || {
let mut engine = engine.clone();
load_standard_library(&mut engine)
})
})]
}
/// Load all modules of standard library into the engine through a general `use`.
fn bench_load_use_standard_lib() -> impl IntoBenchmarks {
[benchmark_fn("load_use_standard_lib", move |b| {
// We need additional commands like `format number` for the standard library
let engine = nu_cmd_extra::add_extra_command_context(setup_engine());
let commands = Spanned {
item: "use std".into(),
span: Span::unknown(),
};
b.iter(move || {
let mut engine = engine.clone();
let mut stack = Stack::new();
let _ = load_standard_library(&mut engine);
evaluate_commands(
&commands,
&mut engine,
&mut stack,
PipelineData::empty(),
Default::default(),
)
})
})]
}
fn create_flat_record_string(n: usize) -> String {
let mut s = String::from("let record = { ");
for i in 0..n {
write!(s, "col_{i}: {i}, ").unwrap();
}
s.push('}');
s
}
fn create_nested_record_string(depth: usize) -> String {
let mut s = String::from("let record = {");
for _ in 0..depth {
s.push_str("col: {");
}
s.push_str("col_final: 0");
for _ in 0..depth {
s.push('}');
}
s.push('}');
s
}
fn create_example_table_nrows(n: usize) -> String {
let mut s = String::from("let table = [[foo bar baz]; ");
for i in 0..n {
s.push_str(&format!("[0, 1, {i}]"));
if i < n - 1 {
s.push_str(", ");
}
}
s.push(']');
s
}
fn bench_record_create(n: usize) -> impl IntoBenchmarks {
bench_command(
format!("record_create_{n}"),
create_flat_record_string(n),
Stack::new(),
setup_engine(),
)
}
fn bench_record_flat_access(n: usize) -> impl IntoBenchmarks {
let setup_command = create_flat_record_string(n);
let (stack, engine) = setup_stack_and_engine_from_command(&setup_command);
bench_command(
format!("record_flat_access_{n}"),
"$record.col_0 | ignore",
stack,
engine,
)
}
fn bench_record_nested_access(n: usize) -> impl IntoBenchmarks {
let setup_command = create_nested_record_string(n);
let (stack, engine) = setup_stack_and_engine_from_command(&setup_command);
let nested_access = ".col".repeat(n);
bench_command(
format!("record_nested_access_{n}"),
format!("$record{nested_access} | ignore"),
stack,
engine,
)
}
fn bench_record_insert(n: usize, m: usize) -> impl IntoBenchmarks {
let setup_command = create_flat_record_string(n);
let (stack, engine) = setup_stack_and_engine_from_command(&setup_command);
let mut insert = String::from("$record");
for i in n..(n + m) {
write!(insert, " | insert col_{i} {i}").unwrap();
}
insert.push_str(" | ignore");
bench_command(format!("record_insert_{n}_{m}"), insert, stack, engine)
}
fn bench_table_create(n: usize) -> impl IntoBenchmarks {
bench_command(
format!("table_create_{n}"),
create_example_table_nrows(n),
Stack::new(),
setup_engine(),
)
}
fn bench_table_get(n: usize) -> impl IntoBenchmarks {
let setup_command = create_example_table_nrows(n);
let (stack, engine) = setup_stack_and_engine_from_command(&setup_command);
bench_command(
format!("table_get_{n}"),
"$table | get bar | math sum | ignore",
stack,
engine,
)
}
fn bench_table_select(n: usize) -> impl IntoBenchmarks {
let setup_command = create_example_table_nrows(n);
let (stack, engine) = setup_stack_and_engine_from_command(&setup_command);
bench_command(
format!("table_select_{n}"),
"$table | select foo baz | ignore",
stack,
engine,
)
}
fn bench_table_insert_row(n: usize, m: usize) -> impl IntoBenchmarks {
let setup_command = create_example_table_nrows(n);
let (stack, engine) = setup_stack_and_engine_from_command(&setup_command);
let mut insert = String::from("$table");
for i in n..(n + m) {
write!(insert, " | insert {i} {{ foo: 0, bar: 1, baz: {i} }}").unwrap();
}
insert.push_str(" | ignore");
bench_command(format!("table_insert_row_{n}_{m}"), insert, stack, engine)
}
fn bench_table_insert_col(n: usize, m: usize) -> impl IntoBenchmarks {
let setup_command = create_example_table_nrows(n);
let (stack, engine) = setup_stack_and_engine_from_command(&setup_command);
let mut insert = String::from("$table");
for i in 0..m {
write!(insert, " | insert col_{i} {i}").unwrap();
}
insert.push_str(" | ignore");
bench_command(format!("table_insert_col_{n}_{m}"), insert, stack, engine)
}
fn bench_eval_interleave(n: usize) -> impl IntoBenchmarks {
let engine = setup_engine();
let stack = Stack::new();
bench_command(
format!("eval_interleave_{n}"),
format!("seq 1 {n} | wrap a | interleave {{ seq 1 {n} | wrap b }} | ignore"),
stack,
engine,
)
}
fn bench_eval_interleave_with_interrupt(n: usize) -> impl IntoBenchmarks {
let mut engine = setup_engine();
engine.set_signals(Signals::new(Arc::new(AtomicBool::new(false))));
let stack = Stack::new();
bench_command(
format!("eval_interleave_with_interrupt_{n}"),
format!("seq 1 {n} | wrap a | interleave {{ seq 1 {n} | wrap b }} | ignore"),
stack,
engine,
)
}
fn bench_eval_for(n: usize) -> impl IntoBenchmarks {
let engine = setup_engine();
let stack = Stack::new();
bench_command(
format!("eval_for_{n}"),
format!("(for $x in (1..{n}) {{ 1 }}) | ignore"),
stack,
engine,
)
}
fn bench_eval_each(n: usize) -> impl IntoBenchmarks {
let engine = setup_engine();
let stack = Stack::new();
bench_command(
format!("eval_each_{n}"),
format!("(1..{n}) | each {{|_| 1 }} | ignore"),
stack,
engine,
)
}
fn bench_eval_par_each(n: usize) -> impl IntoBenchmarks {
let engine = setup_engine();
let stack = Stack::new();
bench_command(
format!("eval_par_each_{n}"),
format!("(1..{n}) | par-each -t 2 {{|_| 1 }} | ignore"),
stack,
engine,
)
}
fn bench_eval_default_config() -> impl IntoBenchmarks {
let kind = ConfigFileKind::Config;
let default_env = kind.default().as_bytes().to_vec();
let fname = kind.default_path().to_string();
bench_eval_source(
"eval_default_config",
fname,
default_env,
Stack::new(),
setup_engine(),
)
}
fn bench_eval_default_env() -> impl IntoBenchmarks {
let kind = ConfigFileKind::Env;
let default_env = kind.default().as_bytes().to_vec();
let fname = kind.default_path().to_string();
bench_eval_source(
"eval_default_env",
fname,
default_env,
Stack::new(),
setup_engine(),
)
}
fn encode_json(row_cnt: usize, col_cnt: usize) -> impl IntoBenchmarks {
let test_data = Rc::new(PluginOutput::CallResponse(
0,
PluginCallResponse::value(encoding_test_data(row_cnt, col_cnt)),
));
let encoder = Rc::new(EncodingType::try_from_bytes(b"json").unwrap());
[benchmark_fn(
format!("encode_json_{row_cnt}_{col_cnt}"),
move |b| {
let encoder = encoder.clone();
let test_data = test_data.clone();
b.iter(move || {
let mut res = Vec::new();
encoder.encode(&*test_data, &mut res).unwrap();
})
},
)]
}
fn encode_msgpack(row_cnt: usize, col_cnt: usize) -> impl IntoBenchmarks {
let test_data = Rc::new(PluginOutput::CallResponse(
0,
PluginCallResponse::value(encoding_test_data(row_cnt, col_cnt)),
));
let encoder = Rc::new(EncodingType::try_from_bytes(b"msgpack").unwrap());
[benchmark_fn(
format!("encode_msgpack_{row_cnt}_{col_cnt}"),
move |b| {
let encoder = encoder.clone();
let test_data = test_data.clone();
b.iter(move || {
let mut res = Vec::new();
encoder.encode(&*test_data, &mut res).unwrap();
})
},
)]
}
fn decode_json(row_cnt: usize, col_cnt: usize) -> impl IntoBenchmarks {
let test_data = PluginOutput::CallResponse(
0,
PluginCallResponse::value(encoding_test_data(row_cnt, col_cnt)),
);
let encoder = EncodingType::try_from_bytes(b"json").unwrap();
let mut res = vec![];
encoder.encode(&test_data, &mut res).unwrap();
[benchmark_fn(
format!("decode_json_{row_cnt}_{col_cnt}"),
move |b| {
let res = res.clone();
b.iter(move || {
let mut binary_data = std::io::Cursor::new(res.clone());
binary_data.set_position(0);
let _: Result<Option<PluginOutput>, _> =
black_box(encoder.decode(&mut binary_data));
})
},
)]
}
fn decode_msgpack(row_cnt: usize, col_cnt: usize) -> impl IntoBenchmarks {
let test_data = PluginOutput::CallResponse(
0,
PluginCallResponse::value(encoding_test_data(row_cnt, col_cnt)),
);
let encoder = EncodingType::try_from_bytes(b"msgpack").unwrap();
let mut res = vec![];
encoder.encode(&test_data, &mut res).unwrap();
[benchmark_fn(
format!("decode_msgpack_{row_cnt}_{col_cnt}"),
move |b| {
let res = res.clone();
b.iter(move || {
let mut binary_data = std::io::Cursor::new(res.clone());
binary_data.set_position(0);
let _: Result<Option<PluginOutput>, _> =
black_box(encoder.decode(&mut binary_data));
})
},
)]
}
tango_benchmarks!(
bench_load_standard_lib(),
bench_load_use_standard_lib(),
// Data types
// Record
bench_record_create(1),
bench_record_create(10),
bench_record_create(100),
bench_record_create(1_000),
bench_record_flat_access(1),
bench_record_flat_access(10),
bench_record_flat_access(100),
bench_record_flat_access(1_000),
bench_record_nested_access(1),
bench_record_nested_access(2),
bench_record_nested_access(4),
bench_record_nested_access(8),
bench_record_nested_access(16),
bench_record_nested_access(32),
bench_record_nested_access(64),
bench_record_nested_access(128),
bench_record_insert(1, 1),
bench_record_insert(10, 1),
bench_record_insert(100, 1),
bench_record_insert(1000, 1),
bench_record_insert(1, 10),
bench_record_insert(10, 10),
bench_record_insert(100, 10),
bench_record_insert(1000, 10),
// Table
bench_table_create(1),
bench_table_create(10),
bench_table_create(100),
bench_table_create(1_000),
bench_table_get(1),
bench_table_get(10),
bench_table_get(100),
bench_table_get(1_000),
bench_table_select(1),
bench_table_select(10),
bench_table_select(100),
bench_table_select(1_000),
bench_table_insert_row(1, 1),
bench_table_insert_row(10, 1),
bench_table_insert_row(100, 1),
bench_table_insert_row(1000, 1),
bench_table_insert_row(1, 10),
bench_table_insert_row(10, 10),
bench_table_insert_row(100, 10),
bench_table_insert_row(1000, 10),
bench_table_insert_col(1, 1),
bench_table_insert_col(10, 1),
bench_table_insert_col(100, 1),
bench_table_insert_col(1000, 1),
bench_table_insert_col(1, 10),
bench_table_insert_col(10, 10),
bench_table_insert_col(100, 10),
bench_table_insert_col(1000, 10),
// Eval
// Interleave
bench_eval_interleave(100),
bench_eval_interleave(1_000),
bench_eval_interleave(10_000),
bench_eval_interleave_with_interrupt(100),
bench_eval_interleave_with_interrupt(1_000),
bench_eval_interleave_with_interrupt(10_000),
// For
bench_eval_for(1),
bench_eval_for(10),
bench_eval_for(100),
bench_eval_for(1_000),
bench_eval_for(10_000),
// Each
bench_eval_each(1),
bench_eval_each(10),
bench_eval_each(100),
bench_eval_each(1_000),
bench_eval_each(10_000),
// Par-Each
bench_eval_par_each(1),
bench_eval_par_each(10),
bench_eval_par_each(100),
bench_eval_par_each(1_000),
bench_eval_par_each(10_000),
// Config
bench_eval_default_config(),
// Env
bench_eval_default_env(),
// Encode
// Json
encode_json(100, 5),
encode_json(10000, 15),
// MsgPack
encode_msgpack(100, 5),
encode_msgpack(10000, 15),
// Decode
// Json
decode_json(100, 5),
decode_json(10000, 15),
// MsgPack
decode_msgpack(100, 5),
decode_msgpack(10000, 15)
);
tango_main!();
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_query/src/query_web.rs | crates/nu_plugin_query/src/query_web.rs | use crate::{Query, web_tables::WebTable};
use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand};
use nu_protocol::{
Category, Example, LabeledError, Record, Signature, Span, Spanned, SyntaxShape, Value,
};
use scraper::{Html, Selector as ScraperSelector};
pub struct QueryWeb;
impl SimplePluginCommand for QueryWeb {
type Plugin = Query;
fn name(&self) -> &str {
"query web"
}
fn description(&self) -> &str {
"execute selector query on html/web"
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.named("query", SyntaxShape::String, "selector query", Some('q'))
.switch("as-html", "return the query output as html", Some('m'))
.named(
"attribute",
SyntaxShape::Any,
"downselect based on the given attribute",
Some('a'),
)
// TODO: use detailed shape when https://github.com/nushell/nushell/issues/13253 is resolved
// .named(
// "attribute",
// SyntaxShape::OneOf(vec![
// SyntaxShape::List(Box::new(SyntaxShape::String)),
// SyntaxShape::String,
// ]),
// "downselect based on the given attribute",
// Some('a'),
// )
.named(
"as-table",
SyntaxShape::List(Box::new(SyntaxShape::String)),
"find table based on column header list",
Some('t'),
)
.switch(
"inspect",
"run in inspect mode to provide more information for determining column headers",
Some('i'),
)
.category(Category::Network)
}
fn examples(&self) -> Vec<Example<'_>> {
web_examples()
}
fn run(
&self,
_plugin: &Query,
_engine: &EngineInterface,
call: &EvaluatedCall,
input: &Value,
) -> Result<Value, LabeledError> {
parse_selector_params(call, input)
}
}
pub fn web_examples() -> Vec<Example<'static>> {
vec![
Example {
example: "http get https://phoronix.com | query web --query 'header' | flatten",
description: "Retrieve all `<header>` elements from phoronix.com website",
result: None,
},
Example {
example: "http get https://en.wikipedia.org/wiki/List_of_cities_in_India_by_population |
query web --as-table [City 'Population(2011)[3]' 'Population(2001)[3][a]' 'State or unionterritory' 'Reference']",
description: "Retrieve a html table from Wikipedia and parse it into a nushell table using table headers as guides",
result: None
},
Example {
example: "http get https://www.nushell.sh | query web --query 'h2, h2 + p' | each {str join} | chunks 2 | each {rotate --ccw tagline description} | flatten",
description: "Pass multiple css selectors to extract several elements within single query, group the query results together and rotate them to create a table",
result: None,
},
Example {
example: "http get https://example.org | query web --query a --attribute href",
description: "Retrieve a specific html attribute instead of the default text",
result: None,
},
Example {
example: r#"http get https://www.rust-lang.org | query web --query 'meta[property^="og:"]' --attribute [ property content ]"#,
description: r#"Retrieve the OpenGraph properties (`<meta property="og:...">`) from a web page"#,
result: None,
}
]
}
pub struct Selector {
pub query: Spanned<String>,
pub as_html: bool,
pub attribute: Value,
pub as_table: Value,
pub inspect: Spanned<bool>,
}
pub fn parse_selector_params(call: &EvaluatedCall, input: &Value) -> Result<Value, LabeledError> {
let head = call.head;
let query: Option<Spanned<String>> = call.get_flag("query")?;
let as_html = call.has_flag("as-html")?;
let attribute = call
.get_flag("attribute")?
.unwrap_or_else(|| Value::nothing(head));
let as_table: Value = call
.get_flag("as-table")?
.unwrap_or_else(|| Value::nothing(head));
let inspect = call.has_flag("inspect")?;
let inspect_span = call.get_flag_span("inspect").unwrap_or(call.head);
let selector = Selector {
query: query.unwrap_or(Spanned {
span: call.head,
item: "".to_owned(),
}),
as_html,
attribute,
as_table,
inspect: Spanned {
item: inspect,
span: inspect_span,
},
};
let span = input.span();
match input {
Value::String { val, .. } => begin_selector_query(val.to_string(), selector, span),
_ => Err(LabeledError::new("Requires text input")
.with_label("expected text from pipeline", span)),
}
}
fn begin_selector_query(
input_html: String,
selector: Selector,
span: Span,
) -> Result<Value, LabeledError> {
if let Value::List { .. } = selector.as_table {
retrieve_tables(
input_html.as_str(),
&selector.as_table,
selector.inspect.item,
span,
)
} else if selector.attribute.is_empty() {
execute_selector_query(
input_html.as_str(),
selector.query,
selector.as_html,
selector.inspect,
span,
)
} else if let Value::List { .. } = selector.attribute {
execute_selector_query_with_attributes(
input_html.as_str(),
selector.query,
&selector.attribute,
selector.inspect,
span,
)
} else {
execute_selector_query_with_attribute(
input_html.as_str(),
selector.query,
selector.attribute.as_str().unwrap_or(""),
selector.inspect,
span,
)
}
}
pub fn retrieve_tables(
input_string: &str,
columns: &Value,
inspect_mode: bool,
span: Span,
) -> Result<Value, LabeledError> {
let html = input_string;
let mut cols: Vec<String> = Vec::new();
if let Value::List { vals, .. } = &columns {
for x in vals {
if let Value::String { val, .. } = x {
cols.push(val.to_string())
}
}
}
if inspect_mode {
eprintln!("Passed in Column Headers = {:?}\n", &cols);
eprintln!("First 2048 HTML chars = {}\n", &html[0..2047]);
}
let tables = match WebTable::find_by_headers(html, &cols, inspect_mode) {
Some(t) => {
if inspect_mode {
eprintln!("Table Found = {:#?}", &t);
}
t
}
None => vec![WebTable::empty()],
};
if tables.len() == 1 {
return Ok(retrieve_table(
tables.into_iter().next().ok_or_else(|| {
LabeledError::new("Cannot retrieve table")
.with_label("Error retrieving table.", span)
.with_help("No table found.")
})?,
columns,
span,
));
}
let vals = tables
.into_iter()
.map(move |table| retrieve_table(table, columns, span))
.collect();
Ok(Value::list(vals, span))
}
fn retrieve_table(mut table: WebTable, columns: &Value, span: Span) -> Value {
let mut cols: Vec<String> = Vec::new();
if let Value::List { vals, .. } = &columns {
for x in vals {
// TODO Find a way to get the Config object here
if let Value::String { val, .. } = x {
cols.push(val.to_string())
}
}
}
if cols.is_empty() && !table.headers().is_empty() {
for col in table.headers().keys() {
cols.push(col.to_string());
}
}
// We provided columns but the table has no headers, so we'll just make a single column table
if !cols.is_empty() && table.headers().is_empty() {
let mut record = Record::new();
for col in &cols {
record.push(
col.clone(),
Value::string("error: no data found (column name may be incorrect)", span),
);
}
return Value::record(record, span);
}
let mut table_out = Vec::new();
// sometimes there are tables where the first column is the headers, kind of like
// a table has ben rotated ccw 90 degrees, in these cases all columns will be missing
// we keep track of this with this variable so we can deal with it later
let mut at_least_one_row_filled = false;
// if columns are still empty, let's just make a single column table with the data
if cols.is_empty() {
at_least_one_row_filled = true;
let table_with_no_empties: Vec<_> = table.iter().filter(|item| !item.is_empty()).collect();
let mut record = Record::new();
for row in &table_with_no_empties {
for (counter, cell) in row.iter().enumerate() {
record.push(format!("column{counter}"), Value::string(cell, span));
}
}
table_out.push(Value::record(record, span))
} else {
for row in &table {
let record = cols
.iter()
.map(|col| {
let val = row
.get(col)
.unwrap_or(&format!("Missing column: '{}'", &col))
.to_string();
if !at_least_one_row_filled && val != format!("Missing column: '{}'", &col) {
at_least_one_row_filled = true;
}
(col.clone(), Value::string(val, span))
})
.collect();
table_out.push(Value::record(record, span))
}
}
if !at_least_one_row_filled {
let mut data2 = Vec::new();
for x in &table.data {
data2.push(x.join(", "));
}
table.data = vec![data2];
return retrieve_table(table, columns, span);
}
// table_out
Value::list(table_out, span)
}
fn execute_selector_query_with_attribute(
input_string: &str,
query_string: Spanned<String>,
attribute: &str,
inspect: Spanned<bool>,
span: Span,
) -> Result<Value, LabeledError> {
let doc = Html::parse_fragment(input_string);
let vals: Vec<Value> = doc
.select(&fallible_css(query_string, inspect)?)
.map(|selection| {
Value::string(
selection.value().attr(attribute).unwrap_or("").to_string(),
span,
)
})
.collect();
Ok(Value::list(vals, span))
}
fn execute_selector_query_with_attributes(
input_string: &str,
query_string: Spanned<String>,
attributes: &Value,
inspect: Spanned<bool>,
span: Span,
) -> Result<Value, LabeledError> {
let doc = Html::parse_fragment(input_string);
let mut attrs: Vec<String> = Vec::new();
if let Value::List { vals, .. } = &attributes {
for x in vals {
if let Value::String { val, .. } = x {
attrs.push(val.to_string())
}
}
}
let vals: Vec<Value> = doc
.select(&fallible_css(query_string, inspect)?)
.map(|selection| {
let mut record = Record::new();
for attr in &attrs {
record.push(
attr.to_string(),
Value::string(selection.value().attr(attr).unwrap_or("").to_string(), span),
);
}
Value::record(record, span)
})
.collect();
Ok(Value::list(vals, span))
}
fn execute_selector_query(
input_string: &str,
query_string: Spanned<String>,
as_html: bool,
inspect: Spanned<bool>,
span: Span,
) -> Result<Value, LabeledError> {
let doc = Html::parse_fragment(input_string);
let vals: Vec<Value> = match as_html {
true => doc
.select(&fallible_css(query_string, inspect)?)
.map(|selection| Value::string(selection.html(), span))
.collect(),
false => doc
.select(&fallible_css(query_string, inspect)?)
.map(|selection| {
Value::list(
selection
.text()
.map(|text| Value::string(text, span))
.collect(),
span,
)
})
.collect(),
};
Ok(Value::list(vals, span))
}
fn fallible_css(
selector: Spanned<String>,
inspect: Spanned<bool>,
) -> Result<ScraperSelector, LabeledError> {
if inspect.item {
ScraperSelector::parse("html").map_err(|e| {
LabeledError::new("CSS query parse error")
.with_label(e.to_string(), inspect.span)
.with_help(
"cannot parse query `html` as a valid CSS selector, possibly an internal error",
)
})
} else {
ScraperSelector::parse(&selector.item).map_err(|e| {
LabeledError::new("CSS query parse error")
.with_label(e.to_string(), selector.span)
.with_help("cannot parse query as a valid CSS selector")
})
}
}
pub fn css(selector: &str, inspect: bool) -> ScraperSelector {
if inspect {
ScraperSelector::parse("html").expect("Error unwrapping the default scraperselector")
} else {
ScraperSelector::parse(selector).expect("Error unwrapping scraperselector::parse")
}
}
#[cfg(test)]
mod tests {
use super::*;
const SIMPLE_LIST: &str = r#"
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
"#;
const NESTED_TEXT: &str = r#"<p>Hello there, <span style="color: red;">World</span></p>"#;
const MULTIPLE_ATTRIBUTES: &str = r#"
<a href="https://example.org" target="_blank">Example</a>
<a href="https://example.com" target="_self">Example</a>
"#;
fn null_spanned<T: ToOwned + ?Sized>(input: &T) -> Spanned<T::Owned> {
Spanned {
item: input.to_owned(),
span: Span::unknown(),
}
}
#[test]
fn test_first_child_is_not_empty() {
assert!(
!execute_selector_query(
SIMPLE_LIST,
null_spanned("li:first-child"),
false,
null_spanned(&false),
Span::test_data()
)
.unwrap()
.is_empty()
)
}
#[test]
fn test_first_child() {
let item = execute_selector_query(
SIMPLE_LIST,
null_spanned("li:first-child"),
false,
null_spanned(&false),
Span::test_data(),
)
.unwrap();
let config = nu_protocol::Config::default();
let out = item.to_expanded_string("\n", &config);
assert_eq!("[[Coffee]]".to_string(), out)
}
#[test]
fn test_nested_text_nodes() {
let item = execute_selector_query(
NESTED_TEXT,
null_spanned("p:first-child"),
false,
null_spanned(&false),
Span::test_data(),
)
.unwrap();
let out = item
.into_list()
.unwrap()
.into_iter()
.map(|matches| {
matches
.into_list()
.unwrap()
.into_iter()
.map(|text_nodes| text_nodes.coerce_into_string().unwrap())
.collect::<Vec<String>>()
})
.collect::<Vec<Vec<String>>>();
assert_eq!(
out,
vec![vec!["Hello there, ".to_string(), "World".to_string()]],
);
}
#[test]
fn test_multiple_attributes() {
let item = execute_selector_query_with_attributes(
MULTIPLE_ATTRIBUTES,
null_spanned("a"),
&Value::list(
vec![
Value::string("href".to_string(), Span::unknown()),
Value::string("target".to_string(), Span::unknown()),
],
Span::unknown(),
),
null_spanned(&false),
Span::test_data(),
)
.unwrap();
let out = item
.into_list()
.unwrap()
.into_iter()
.map(|matches| {
matches
.into_record()
.unwrap()
.into_iter()
.map(|(key, value)| (key, value.coerce_into_string().unwrap()))
.collect::<Vec<(String, String)>>()
})
.collect::<Vec<Vec<(String, String)>>>();
assert_eq!(
out,
vec![
vec![
("href".to_string(), "https://example.org".to_string()),
("target".to_string(), "_blank".to_string())
],
vec![
("href".to_string(), "https://example.com".to_string()),
("target".to_string(), "_self".to_string())
]
]
)
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_query/src/lib.rs | crates/nu_plugin_query/src/lib.rs | mod query;
mod query_json;
mod query_web;
mod query_webpage_info;
mod query_xml;
mod web_tables;
pub use query::Query;
pub use query_json::{QueryJson, execute_json_query};
pub use query_web::{QueryWeb, parse_selector_params};
pub use query_xml::{QueryXml, execute_xpath_query};
pub use web_tables::WebTable;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_query/src/query_xml.rs | crates/nu_plugin_query/src/query_xml.rs | use crate::Query;
use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand};
use nu_protocol::{
Category, Example, LabeledError, Record, Signature, Span, Spanned, SyntaxShape, Type, Value,
record,
};
use sxd_document::parser;
use sxd_xpath::{Context, Factory};
pub struct QueryXml;
impl SimplePluginCommand for QueryXml {
type Plugin = Query;
fn name(&self) -> &str {
"query xml"
}
fn description(&self) -> &str {
"Execute XPath 1.0 query on XML input"
}
fn extra_description(&self) -> &str {
r#"Scalar results (Number, String, Boolean) are returned as nu scalars.
Output of the nodeset results depends on the flags used:
- No flags: returns a table with `string_value` column.
- You have to specify `--output-string-value` to include `string_value` in the output when using any other `--output-*` flags.
- `--output-type` includes `type` column with node type.
- `--output-names` includes `local_name`, `prefixed_name`, and `namespace` columns.
"#
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.required("query", SyntaxShape::String, "xpath query")
.named(
"namespaces",
SyntaxShape::Record(vec![]),
"map of prefixes to namespace URIs",
Some('n'),
)
.switch(
"output-string-value",
"Include `string_value` in the nodeset output. On by default.",
None,
)
.switch(
"output-type",
"Include `type` in the nodeset output. Off by default.",
None,
)
.switch(
"output-names",
"Include `local_name`, `prefixed_name`, and `namespace` in the nodeset output. Off by default.",
None,
)
.input_output_types(vec![
(Type::String, Type::Any),
])
.category(Category::Filters)
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
// full output
Example {
description: "Query namespaces on the root element of an SVG file",
example: r#"http get --raw https://www.w3.org/TR/SVG/images/conform/smiley.svg
| query xml '/svg:svg/namespace::*' --output-string-value --output-names --output-type --namespaces {svg: "http://www.w3.org/2000/svg"}"#,
result: None,
},
// scalar output
Example {
description: "Query the language of Nushell blog (`xml:` prefix is always available)",
example: r#"http get --raw https://www.nushell.sh/atom.xml
| query xml 'string(/*/@xml:lang)'"#,
result: None,
},
// query attributes
Example {
description: "Query all XLink targets in SVG document",
example: r#"http get --raw https://www.w3.org/TR/SVG/images/conform/smiley.svg
| query xml '//*/@xlink:href' --namespaces {xlink: "http://www.w3.org/1999/xlink"}"#,
result: None,
},
// default output
Example {
description: "Get recent Nushell news",
example: r#"http get --raw https://www.nushell.sh/atom.xml
| query xml '//atom:entry/atom:title|//atom:entry/atom:link/@href' --namespaces {atom: "http://www.w3.org/2005/Atom"}
| window 2 --stride 2
| each { {title: $in.0.string_value, link: $in.1.string_value} }"#,
result: None,
},
]
}
fn run(
&self,
_plugin: &Query,
_engine: &EngineInterface,
call: &EvaluatedCall,
input: &Value,
) -> Result<Value, LabeledError> {
let query: Option<Spanned<String>> = call.opt(0)?;
let namespaces: Option<Record> = call.get_flag::<Record>("namespaces")?;
execute_xpath_query(call, input, query, namespaces)
}
}
pub fn execute_xpath_query(
call: &EvaluatedCall,
input: &Value,
query: Option<Spanned<String>>,
namespaces: Option<Record>,
) -> Result<Value, LabeledError> {
let (query_string, span) = match &query {
Some(v) => (&v.item, v.span),
None => {
return Err(
LabeledError::new("problem with input data").with_label("query missing", call.head)
);
}
};
let node_output_options = NodeOutputOptions::from_call(call);
let xpath = build_xpath(query_string, span)?;
let input_string = input.coerce_str()?;
let package = parser::parse(&input_string);
if let Err(err) = package {
return Err(
LabeledError::new("Invalid XML document").with_label(err.to_string(), input.span())
);
}
let package = package.expect("invalid xml document");
let document = package.as_document();
let mut context = Context::new();
let mut namespaces = namespaces.unwrap_or_default();
if namespaces.get("xml").is_none() {
// XML namespace is always present, so we add it explicitly
// it's used in attributes like `xml:lang`, `xml:base`, etc.
namespaces.insert(
"xml",
Value::string("http://www.w3.org/XML/1998/namespace", call.head),
);
}
// NB: `xmlns:whatever=` or `xmlns=` may look like an attribute, but XPath doesn't treat it as such.
// Those are namespaces, and they are available through a separate axis (`namespace::`)
// Thus we don't need to register a namespace for `xmlns` prefix
for (prefix, uri) in namespaces.into_iter() {
context.set_namespace(prefix.as_str(), uri.into_string()?.as_str());
}
// leaving this here for augmentation at some point
// build_variables(&arguments, &mut context);
// build_namespaces(&arguments, &mut context);
let res = xpath.evaluate(&context, document.root());
match res {
Ok(sxd_xpath::Value::Boolean(b)) => Ok(Value::bool(b, call.head)),
Ok(sxd_xpath::Value::Number(n)) => Ok(Value::float(n, call.head)),
Ok(sxd_xpath::Value::String(s)) => Ok(Value::string(s, call.head)),
Ok(sxd_xpath::Value::Nodeset(ns)) => {
let mut records: Vec<Value> = vec![];
for n in ns.document_order() {
records.push(node_to_record(n, &node_output_options, call.head));
}
Ok(Value::list(records, call.head))
}
Err(err) => {
Err(LabeledError::new("xpath query error").with_label(err.to_string(), call.head))
}
}
}
fn node_to_record(
n: sxd_xpath::nodeset::Node<'_>,
options: &NodeOutputOptions,
span: Span,
) -> Value {
use sxd_xpath::nodeset::Node;
let mut record = record! {};
if options.string_value {
record.push("string_value", Value::string(n.string_value(), span));
}
if options.type_ {
record.push(
"type",
match n {
Node::Element(..) => Value::string("element", span),
Node::Attribute(..) => Value::string("attribute", span),
Node::Text(..) => Value::string("text", span),
Node::Comment(..) => Value::string("comment", span),
Node::ProcessingInstruction(..) => Value::string("processing_instruction", span),
Node::Root(..) => Value::string("root", span),
Node::Namespace(..) => Value::string("namespace", span),
},
);
}
if options.names {
record.push(
"local_name",
match n.expanded_name() {
Some(name) => Value::string(name.local_part(), span),
None => Value::nothing(span),
},
);
record.push(
"namespace",
match n.expanded_name() {
Some(name) => match name.namespace_uri() {
Some(uri) => Value::string(uri, span),
None => Value::nothing(span),
},
None => Value::nothing(span),
},
);
record.push(
"prefixed_name",
match n.prefixed_name() {
Some(name) => Value::string(name, span),
None => Value::nothing(span),
},
);
}
Value::record(record, span)
}
fn build_xpath(xpath_str: &str, span: Span) -> Result<sxd_xpath::XPath, LabeledError> {
let factory = Factory::new();
match factory.build(xpath_str) {
Ok(xpath) => xpath.ok_or_else(|| {
LabeledError::new("invalid xpath query").with_label("the query must not be empty", span)
}),
Err(err) => Err(LabeledError::new("invalid xpath query").with_label(err.to_string(), span)),
}
}
struct NodeOutputOptions {
string_value: bool,
type_: bool,
names: bool,
}
impl NodeOutputOptions {
fn from_call(call: &EvaluatedCall) -> Self {
match (
call.has_flag("output-string-value")
.expect("output-string-value flag"),
call.has_flag("output-type").expect("output-type flag"),
call.has_flag("output-names").expect("output-names flag"),
) {
// no flags - old behavior - single column
(false, false, false) => NodeOutputOptions {
string_value: true,
type_: false,
names: false,
},
(string_value, type_, names) => NodeOutputOptions {
string_value,
type_,
names,
},
}
}
}
#[cfg(test)]
mod tests {
use super::execute_xpath_query as query;
use nu_plugin::EvaluatedCall;
use nu_protocol::{IntoSpanned, Span, Spanned, Value, record};
#[test]
fn position_function_in_predicate() {
let call = EvaluatedCall {
head: Span::test_data(),
positional: vec![],
named: vec![],
};
let text = Value::string(
r#"<?xml version="1.0" encoding="UTF-8"?><a><b/><b/></a>"#,
Span::test_data(),
);
let spanned_str: Spanned<String> = Spanned {
item: "count(//a/*[position() = 2])".to_string(),
span: Span::test_data(),
};
let actual = query(&call, &text, Some(spanned_str), None).expect("test should not fail");
assert_eq!(actual, Value::test_float(1.0));
}
#[test]
fn functions_implicitly_coerce_argument_types() {
let call = EvaluatedCall {
head: Span::test_data(),
positional: vec![],
named: vec![],
};
let text = Value::string(
r#"<?xml version="1.0" encoding="UTF-8"?><a>true</a>"#,
Span::test_data(),
);
let spanned_str: Spanned<String> = Spanned {
item: "count(//*[contains(., true)])".to_string(),
span: Span::test_data(),
};
let actual = query(&call, &text, Some(spanned_str), None).expect("test should not fail");
assert_eq!(actual, Value::test_float(1.0));
}
#[test]
fn namespaces_are_used() {
let call = EvaluatedCall {
head: Span::test_data(),
positional: vec![],
named: vec![],
};
// document uses `dp` ("document prefix") as a prefix
let text = Value::string(
r#"<?xml version="1.0" encoding="UTF-8"?><a xmlns:dp="http://example.com/ns"><dp:b>yay</dp:b></a>"#,
Span::test_data(),
);
// but query uses `qp` ("query prefix") as a prefix
let namespaces = record! {
"qp" => Value::string("http://example.com/ns", Span::test_data()),
};
let spanned_str: Spanned<String> = Spanned {
item: "//qp:b/text()".to_string(),
span: Span::test_data(),
};
let actual =
query(&call, &text, Some(spanned_str), Some(namespaces)).expect("test should not fail");
let expected = Value::list(
vec![Value::test_record(record! {
"string_value" => Value::string("yay", Span::test_data()),
})],
Span::test_data(),
);
// and yet it should work regardless
assert_eq!(actual, expected);
}
#[test]
fn number_returns_float() {
let call = EvaluatedCall {
head: Span::test_data(),
positional: vec![],
named: vec![],
};
let text = Value::test_string(r#"<?xml version="1.0" encoding="UTF-8"?><elt/>"#);
let spanned_str: Spanned<String> = Spanned {
item: "count(/elt)".to_string(),
span: Span::test_data(),
};
let actual = query(&call, &text, Some(spanned_str), None).expect("test should not fail");
assert_eq!(actual, Value::test_float(1.0));
}
#[test]
fn boolean_returns_bool() {
let call = EvaluatedCall {
head: Span::test_data(),
positional: vec![],
named: vec![],
};
let text = Value::test_string(r#"<?xml version="1.0" encoding="UTF-8"?><elt/>"#);
let spanned_str: Spanned<String> = Spanned {
item: "false()".to_string(),
span: Span::test_data(),
};
let actual = query(&call, &text, Some(spanned_str), None).expect("test should not fail");
assert_eq!(actual, Value::test_bool(false));
}
#[test]
fn string_returns_string() {
let call = EvaluatedCall {
head: Span::test_data(),
positional: vec![],
named: vec![],
};
let text = Value::test_string(r#"<?xml version="1.0" encoding="UTF-8"?><elt/>"#);
let spanned_str: Spanned<String> = Spanned {
item: "local-name(/elt)".to_string(),
span: Span::test_data(),
};
let actual = query(&call, &text, Some(spanned_str), None).expect("test should not fail");
assert_eq!(actual, Value::test_string("elt"));
}
#[test]
fn nodeset_returns_table() {
let call = EvaluatedCall {
head: Span::test_data(),
positional: vec![],
named: vec![],
};
let text = Value::test_string(r#"<?xml version="1.0" encoding="UTF-8"?><elt>hello</elt>"#);
let spanned_str: Spanned<String> = Spanned {
item: "/elt".to_string(),
span: Span::test_data(),
};
let actual = query(&call, &text, Some(spanned_str), None).expect("test should not fail");
let expected = Value::list(
vec![Value::test_record(record! {
"string_value" => Value::string("hello", Span::test_data()),
})],
Span::test_data(),
);
assert_eq!(actual, expected);
}
#[test]
fn have_to_specify_output_string_value_explicitly_with_other_output_flags() {
let call = EvaluatedCall {
head: Span::test_data(),
positional: vec![],
named: vec![(
"output-type".to_string().into_spanned(Span::test_data()),
Some(Value::test_bool(true)),
)],
};
let text = Value::test_string(r#"<?xml version="1.0" encoding="UTF-8"?><elt>hello</elt>"#);
let spanned_str: Spanned<String> = Spanned {
item: "/elt".to_string(),
span: Span::test_data(),
};
let actual = query(&call, &text, Some(spanned_str), None).expect("test should not fail");
let expected = Value::test_list(vec![Value::test_record(record! {
"type" => Value::test_string("element"),
})]);
assert_eq!(actual, expected);
}
#[test]
fn output_string_value_adds_string_value_column() {
let call = EvaluatedCall {
head: Span::test_data(),
positional: vec![],
named: vec![
(
"output-string-value"
.to_string()
.into_spanned(Span::test_data()),
Some(Value::test_bool(true)),
),
(
"output-type".to_string().into_spanned(Span::test_data()),
Some(Value::test_bool(true)),
),
],
};
let text = Value::test_string(r#"<?xml version="1.0" encoding="UTF-8"?><elt>hello</elt>"#);
let spanned_str: Spanned<String> = Spanned {
item: "/elt".to_string(),
span: Span::test_data(),
};
let actual = query(&call, &text, Some(spanned_str), None).expect("test should not fail");
let expected = Value::test_list(vec![Value::test_record(record! {
"string_value" => Value::test_string("hello"),
"type" => Value::test_string("element"),
})]);
assert_eq!(actual, expected);
}
#[test]
fn output_names_adds_names_columns() {
let call = EvaluatedCall {
head: Span::test_data(),
positional: vec![],
named: vec![
(
"output-names".to_string().into_spanned(Span::test_data()),
Some(Value::test_bool(true)),
),
(
"output-string-value"
.to_string()
.into_spanned(Span::test_data()),
Some(Value::test_bool(true)),
),
],
};
let text = Value::test_string(
r#"<?xml version="1.0" encoding="UTF-8"?><elt xmlns="http://www.w3.org/2000/svg">hello</elt>"#,
);
let spanned_str: Spanned<String> = Spanned {
item: "/svg:elt".to_string(),
span: Span::test_data(),
};
let namespaces = record! {
"svg" => Value::test_string("http://www.w3.org/2000/svg"),
};
let actual =
query(&call, &text, Some(spanned_str), Some(namespaces)).expect("test should not fail");
let expected = Value::test_list(vec![Value::test_record(record! {
"string_value" => Value::test_string("hello"),
"local_name" => Value::test_string("elt"),
"namespace" => Value::test_string("http://www.w3.org/2000/svg"),
"prefixed_name" => Value::test_string("elt"),
})]);
assert_eq!(actual, expected);
}
#[test]
fn xml_namespace_is_always_present() {
let call = EvaluatedCall {
head: Span::test_data(),
positional: vec![],
named: vec![],
};
let text = Value::test_string(
r#"<?xml version="1.0" encoding="UTF-8"?><elt xml:lang="en">hello</elt>"#,
);
let spanned_str: Spanned<String> = Spanned {
item: "string(/elt/@xml:lang)".to_string(),
span: Span::test_data(),
};
let actual = query(&call, &text, Some(spanned_str), None).expect("test should not fail");
assert_eq!(actual, Value::test_string("en"));
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_query/src/query_json.rs | crates/nu_plugin_query/src/query_json.rs | use crate::Query;
use gjson::Value as gjValue;
use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand};
use nu_protocol::{
Category, Example, LabeledError, Record, Signature, Span, Spanned, SyntaxShape, Value,
};
pub struct QueryJson;
impl SimplePluginCommand for QueryJson {
type Plugin = Query;
fn name(&self) -> &str {
"query json"
}
fn description(&self) -> &str {
"execute json query on json file (open --raw <file> | query json 'query string')"
}
fn extra_description(&self) -> &str {
"query json uses the gjson crate https://github.com/tidwall/gjson.rs to query json data."
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.required("query", SyntaxShape::String, "json query")
.category(Category::Filters)
}
fn examples(&self) -> Vec<nu_protocol::Example<'_>> {
vec![
Example {
description: "Get a list of children from a json object",
example: r#"'{"children": ["Sara","Alex","Jack"]}' | query json children"#,
result: Some(Value::test_list(vec![
Value::test_string("Sara"),
Value::test_string("Alex"),
Value::test_string("Jack"),
])),
},
Example {
description: "Get a list of first names of the friends from a json object",
example: r#"'{
"friends": [
{"first": "Dale", "last": "Murphy", "age": 44, "nets": ["ig", "fb", "tw"]},
{"first": "Roger", "last": "Craig", "age": 68, "nets": ["fb", "tw"]},
{"first": "Jane", "last": "Murphy", "age": 47, "nets": ["ig", "tw"]}
]
}' | query json friends.#.first"#,
result: Some(Value::test_list(vec![
Value::test_string("Dale"),
Value::test_string("Roger"),
Value::test_string("Jane"),
])),
},
Example {
description: "Get the key named last of the name from a json object",
example: r#"'{"name": {"first": "Tom", "last": "Anderson"}}' | query json name.last"#,
result: Some(Value::test_string("Anderson")),
},
Example {
description: "Get the count of children from a json object",
example: r#"'{"children": ["Sara","Alex","Jack"]}' | query json children.#"#,
result: Some(Value::test_int(3)),
},
Example {
description: "Get the first child from the children array in reverse the order using the @reverse modifier from a json object",
example: r#"'{"children": ["Sara","Alex","Jack"]}' | query json "children|@reverse|0""#,
result: Some(Value::test_string("Jack")),
},
]
}
fn run(
&self,
_plugin: &Query,
_engine: &EngineInterface,
call: &EvaluatedCall,
input: &Value,
) -> Result<Value, LabeledError> {
let query: Option<Spanned<String>> = call.opt(0)?;
execute_json_query(call, input, query)
}
}
pub fn execute_json_query(
call: &EvaluatedCall,
input: &Value,
query: Option<Spanned<String>>,
) -> Result<Value, LabeledError> {
let input_string = match input.coerce_str() {
Ok(s) => s,
Err(e) => {
return Err(LabeledError::new("Problem with input data").with_inner(e));
}
};
let query_string = match &query {
Some(v) => &v.item,
None => {
return Err(LabeledError::new("Problem with input data")
.with_label("query string missing", call.head));
}
};
// Validate the json before trying to query it
let is_valid_json = gjson::valid(&input_string);
if !is_valid_json {
return Err(
LabeledError::new("Invalid JSON").with_label("this is not valid JSON", call.head)
);
}
let val: gjValue = gjson::get(&input_string, query_string);
if query_contains_modifiers(query_string) {
let json_str = val.json();
Ok(Value::string(json_str, call.head))
} else {
Ok(convert_gjson_value_to_nu_value(&val, call.head))
}
}
fn query_contains_modifiers(query: &str) -> bool {
// https://github.com/tidwall/gjson.rs documents 7 modifiers as of 4/19/21
// Some of these modifiers mean we really need to output the data as a string
// instead of tabular data. Others don't matter.
// Output as String
// @ugly: Remove all whitespace from a json document.
// @pretty: Make the json document more human readable.
query.contains("@ugly") || query.contains("@pretty")
// Output as Tabular
// Since it's output as tabular, which is our default, we can just ignore these
// @reverse: Reverse an array or the members of an object.
// @this: Returns the current element. It can be used to retrieve the root element.
// @valid: Ensure the json document is valid.
// @flatten: Flattens an array.
// @join: Joins multiple objects into a single object.
}
fn convert_gjson_value_to_nu_value(v: &gjValue, span: Span) -> Value {
match v.kind() {
gjson::Kind::Array => {
let mut vals = vec![];
v.each(|_k, v| {
vals.push(convert_gjson_value_to_nu_value(&v, span));
true
});
Value::list(vals, span)
}
gjson::Kind::Null => Value::nothing(span),
gjson::Kind::False => Value::bool(false, span),
gjson::Kind::Number => {
let str_value = v.str();
if str_value.contains('.') {
Value::float(v.f64(), span)
} else {
Value::int(v.i64(), span)
}
}
gjson::Kind::String => Value::string(v.str(), span),
gjson::Kind::True => Value::bool(true, span),
gjson::Kind::Object => {
let mut record = Record::new();
v.each(|k, v| {
record.push(k.to_string(), convert_gjson_value_to_nu_value(&v, span));
true
});
Value::record(record, span)
}
}
}
#[cfg(test)]
mod tests {
use gjson::{Value as gjValue, valid};
#[test]
fn validate_string() {
let json = r#"{ "name": { "first": "Tom", "last": "Anderson" }, "age": 37, "children": ["Sara", "Alex", "Jack"], "friends": [ { "first": "James", "last": "Murphy" }, { "first": "Roger", "last": "Craig" } ] }"#;
let val = valid(json);
assert!(val);
}
#[test]
fn answer_from_get_age() {
let json = r#"{ "name": { "first": "Tom", "last": "Anderson" }, "age": 37, "children": ["Sara", "Alex", "Jack"], "friends": [ { "first": "James", "last": "Murphy" }, { "first": "Roger", "last": "Craig" } ] }"#;
let val: gjValue = gjson::get(json, "age");
assert_eq!(val.str(), "37");
}
#[test]
fn answer_from_get_children() {
let json = r#"{ "name": { "first": "Tom", "last": "Anderson" }, "age": 37, "children": ["Sara", "Alex", "Jack"], "friends": [ { "first": "James", "last": "Murphy" }, { "first": "Roger", "last": "Craig" } ] }"#;
let val: gjValue = gjson::get(json, "children");
assert_eq!(val.str(), r#"["Sara", "Alex", "Jack"]"#);
}
#[test]
fn answer_from_get_children_count() {
let json = r#"{ "name": { "first": "Tom", "last": "Anderson" }, "age": 37, "children": ["Sara", "Alex", "Jack"], "friends": [ { "first": "James", "last": "Murphy" }, { "first": "Roger", "last": "Craig" } ] }"#;
let val: gjValue = gjson::get(json, "children.#");
assert_eq!(val.str(), "3");
}
#[test]
fn answer_from_get_friends_first_name() {
let json = r#"{ "name": { "first": "Tom", "last": "Anderson" }, "age": 37, "children": ["Sara", "Alex", "Jack"], "friends": [ { "first": "James", "last": "Murphy" }, { "first": "Roger", "last": "Craig" } ] }"#;
let val: gjValue = gjson::get(json, "friends.#.first");
assert_eq!(val.str(), r#"["James","Roger"]"#);
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_query/src/web_tables.rs | crates/nu_plugin_query/src/web_tables.rs | use crate::query_web::css;
use scraper::{Html, Selector as ScraperSelector, element_ref::ElementRef};
use std::collections::HashMap;
pub type Headers = HashMap<String, usize>;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WebTable {
headers: Headers,
pub data: Vec<Vec<String>>,
}
impl WebTable {
/// Finds the first table in `html`.
pub fn find_first(html: &str) -> Option<WebTable> {
let html = Html::parse_fragment(html);
html.select(&css("table", false)).next().map(WebTable::new)
}
pub fn find_all_tables(html: &str) -> Option<Vec<WebTable>> {
let html = Html::parse_fragment(html);
let iter: Vec<WebTable> = html
.select(&css("table", false))
.map(WebTable::new)
.collect();
if iter.is_empty() {
return None;
}
Some(iter)
}
/// Finds the table in `html` with an id of `id`.
pub fn find_by_id(html: &str, id: &str) -> Option<WebTable> {
let html = Html::parse_fragment(html);
let selector = format!("table#{id}");
ScraperSelector::parse(&selector)
.ok()
.as_ref()
.map(|s| html.select(s))
.and_then(|mut s| s.next())
.map(WebTable::new)
}
/// Finds the table in `html` whose first row contains all of the headers
/// specified in `headers`. The order does not matter.
///
/// If `headers` is empty, this is the same as
/// [`find_first`](#method.find_first).
pub fn find_by_headers<T>(
html: &str,
headers: &[T],
inspect_mode: bool,
) -> Option<Vec<WebTable>>
where
T: AsRef<str>,
{
if headers.is_empty() {
return WebTable::find_all_tables(html);
}
let sel_table = css("table", false);
let sel_tr = css("tr", false);
let sel_th = css("th", false);
let html = Html::parse_fragment(html);
let mut tables = html
.select(&sel_table)
.filter(|table| {
table.select(&sel_tr).next().is_some_and(|tr| {
let cells = select_cells(tr, &sel_th, true);
if inspect_mode {
eprintln!("Potential HTML Headers = {:?}\n", &cells);
}
headers.iter().all(|h| contains_str(&cells, h.as_ref()))
})
})
.peekable();
tables.peek()?;
Some(tables.map(WebTable::new).collect())
}
/// Returns the headers of the table.
///
/// This will be empty if the table had no `<th>` tags in its first row. See
/// [`Headers`](type.Headers.html) for more.
pub fn headers(&self) -> &Headers {
&self.headers
}
/// Returns an iterator over the [`Row`](struct.Row.html)s of the table.
///
/// Only `<td>` cells are considered when generating rows. If the first row
/// of the table is a header row, meaning it contains at least one `<th>`
/// cell, the iterator will start on the second row. Use
/// [`headers`](#method.headers) to access the header row in that case.
pub fn iter(&self) -> Iter<'_> {
Iter {
headers: &self.headers,
iter: self.data.iter(),
}
}
pub fn empty() -> WebTable {
WebTable {
headers: HashMap::new(),
data: vec![vec!["".to_string()]],
}
}
// fn new(element: ElementRef) -> Table {
// let sel_tr = css("tr", false);
// let sel_th = css("th", false);
// let sel_td = css("td", false);
// let mut headers = HashMap::new();
// let mut rows = element.select(&sel_tr).peekable();
// if let Some(tr) = rows.peek() {
// for (i, th) in tr.select(&sel_th).enumerate() {
// headers.insert(cell_content(th), i);
// }
// }
// if !headers.is_empty() {
// rows.next();
// }
// let data = rows.map(|tr| select_cells(tr, &sel_td, true)).collect();
// Table { headers, data }
// }
fn new(element: ElementRef) -> WebTable {
let sel_tr = css("tr", false);
let sel_th = css("th", false);
let sel_td = css("td", false);
let mut headers = HashMap::new();
let mut rows = element.select(&sel_tr).peekable();
if let Some(tr) = rows.clone().peek() {
for (i, th) in tr.select(&sel_th).enumerate() {
headers.insert(cell_content(th), i);
}
}
if !headers.is_empty() {
rows.next();
}
if headers.is_empty() {
// try looking for data as headers i.e. they're row headers not column headers
for (i, d) in rows
.clone()
.map(|tr| select_cells(tr, &sel_th, true))
.enumerate()
{
headers.insert(d.join(", "), i);
}
// check if headers are there but empty
let mut empty_headers = true;
for (h, _i) in headers.clone() {
if !h.is_empty() {
empty_headers = false;
break;
}
}
if empty_headers {
headers = HashMap::new();
}
let data = rows.map(|tr| select_cells(tr, &sel_td, true)).collect();
WebTable { headers, data }
} else {
let data = rows.map(|tr| select_cells(tr, &sel_td, true)).collect();
WebTable { headers, data }
}
}
}
impl<'a> IntoIterator for &'a WebTable {
type Item = Row<'a>;
type IntoIter = Iter<'a>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
/// An iterator over the rows in a [`Table`](struct.Table.html).
pub struct Iter<'a> {
headers: &'a Headers,
iter: std::slice::Iter<'a, Vec<String>>,
}
impl<'a> Iterator for Iter<'a> {
type Item = Row<'a>;
fn next(&mut self) -> Option<Self::Item> {
let headers = self.headers;
self.iter.next().map(|cells| Row { headers, cells })
}
}
/// A row in a [`Table`](struct.Table.html).
///
/// A row consists of a number of data cells stored as strings. If the row
/// contains the same number of cells as the table's header row, its cells can
/// be safely accessed by header names using [`get`](#method.get). Otherwise,
/// the data should be accessed via [`as_slice`](#method.as_slice) or by
/// iterating over the row.
///
/// This struct can be thought of as a lightweight reference into a table. As
/// such, it implements the `Copy` trait.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Row<'a> {
headers: &'a Headers,
cells: &'a [String],
}
impl<'a> Row<'a> {
/// Returns the number of cells in the row.
pub fn len(&self) -> usize {
self.cells.len()
}
/// Returns `true` if the row contains no cells.
pub fn is_empty(&self) -> bool {
self.cells.is_empty()
}
/// Returns the cell underneath `header`.
///
/// Returns `None` if there is no such header, or if there is no cell at
/// that position in the row.
pub fn get(&self, header: &str) -> Option<&'a str> {
// eprintln!(
// "header={}, headers={:?}, cells={:?}",
// &header, &self.headers, &self.cells
// );
self.headers.get(header).and_then(|&i| {
// eprintln!("i={}", i);
self.cells.get(i).map(String::as_str)
})
}
pub fn get_header_at(&self, index: usize) -> Option<&'a str> {
let mut a_match = "";
for (key, val) in self.headers {
if *val == index {
a_match = key;
break;
}
}
if a_match.is_empty() {
None
} else {
Some(a_match)
}
}
/// Returns a slice containing all the cells.
pub fn as_slice(&self) -> &'a [String] {
self.cells
}
/// Returns an iterator over the cells of the row.
pub fn iter(&self) -> std::slice::Iter<'_, String> {
self.cells.iter()
}
}
impl<'a> IntoIterator for Row<'a> {
type Item = &'a String;
type IntoIter = std::slice::Iter<'a, String>;
fn into_iter(self) -> Self::IntoIter {
self.cells.iter()
}
}
fn select_cells(
element: ElementRef,
selector: &ScraperSelector,
remove_html_tags: bool,
) -> Vec<String> {
if remove_html_tags {
let scraped = element.select(selector).map(cell_content);
let mut dehtmlized: Vec<String> = Vec::new();
for item in scraped {
if item.is_empty() {
dehtmlized.push(item);
continue;
}
let frag = Html::parse_fragment(&item);
for node in frag.tree {
if let scraper::node::Node::Text(text) = node {
dehtmlized.push(text.text.to_string());
}
}
}
dehtmlized
} else {
element.select(selector).map(cell_content).collect()
}
}
fn cell_content(element: ElementRef) -> String {
// element.inner_html().trim().to_string()
let mut dehtmlize = String::new();
let element = element.inner_html().trim().to_string();
let frag = Html::parse_fragment(&element);
for node in frag.tree {
if let scraper::node::Node::Text(text) = node {
dehtmlize.push_str(&text.text)
}
}
// eprintln!("element={} dehtmlize={}", &element, &dehtmlize);
if dehtmlize.is_empty() {
dehtmlize = element;
}
dehtmlize
}
fn contains_str(slice: &[String], item: &str) -> bool {
// slice.iter().any(|s| s == item)
let mut dehtmlized = String::new();
let frag = Html::parse_fragment(item);
for node in frag.tree {
if let scraper::node::Node::Text(text) = node {
dehtmlized.push_str(&text.text);
}
}
if dehtmlized.is_empty() {
dehtmlized = item.to_string();
}
slice.iter().any(|s| {
// eprintln!(
// "\ns={} item={} contains={}\n",
// &s,
// &dehtmlized,
// &dehtmlized.contains(s)
// );
// s.starts_with(item)
dehtmlized.contains(s)
})
}
#[cfg(test)]
mod tests {
use super::*;
// use crate::query_web::retrieve_tables;
// use indexmap::indexmap;
// use nu_protocol::Value;
const TABLE_EMPTY: &str = r#"
<table></table>
"#;
const TABLE_TH: &str = r#"
<table>
<tr><th>Name</th><th>Age</th></tr>
</table>
"#;
const TABLE_TD: &str = r#"
<table>
<tr><td>Name</td><td>Age</td></tr>
</table>
"#;
const TWO_TABLES_TD: &str = r#"
<table>
<tr><td>Name</td><td>Age</td></tr>
</table>
<table>
<tr><td>Profession</td><td>Civil State</td></tr>
</table>
"#;
const TABLE_TH_TD: &str = r#"
<table>
<tr><th>Name</th><th>Age</th></tr>
<tr><td>John</td><td>20</td></tr>
</table>
"#;
const TWO_TABLES_TH_TD: &str = r#"
<table>
<tr><th>Name</th><th>Age</th></tr>
<tr><td>John</td><td>20</td></tr>
</table>
<table>
<tr><th>Profession</th><th>Civil State</th></tr>
<tr><td>Mechanic</td><td>Single</td></tr>
</table>
"#;
const TABLE_TD_TD: &str = r#"
<table>
<tr><td>Name</td><td>Age</td></tr>
<tr><td>John</td><td>20</td></tr>
</table>
"#;
const TABLE_TH_TH: &str = r#"
<table>
<tr><th>Name</th><th>Age</th></tr>
<tr><th>John</th><th>20</th></tr>
</table>
"#;
const TABLE_COMPLEX: &str = r#"
<table>
<tr><th>Name</th><th>Age</th><th>Extra</th></tr>
<tr><td>John</td><td>20</td></tr>
<tr><td>May</td><td>30</td><td>foo</td></tr>
<tr></tr>
<tr><td></td><td></td><td></td></tr>
<tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>
</table>
"#;
const TWO_TABLES_COMPLEX: &str = r#"
<!doctype HTML>
<html>
<head><title>foo</title></head>
<body>
<table>
<tr><th>Name</th><th>Age</th><th>Extra</th></tr>
<tr><td>John</td><td>20</td></tr>
<tr><td>May</td><td>30</td><td>foo</td></tr>
<tr></tr>
<tr><td></td><td></td><td></td></tr>
<tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>
</table>
<table>
<tr><th>Profession</th><th>Civil State</th><th>Extra</th></tr>
<tr><td>Carpenter</td><td>Single</td></tr>
<tr><td>Mechanic</td><td>Married</td><td>bar</td></tr>
<tr></tr>
<tr><td></td><td></td><td></td></tr>
<tr><td>e</td><td>f</td><td>g</td><td>h</td></tr>
</table>
</body>
</html>
"#;
const HTML_NO_TABLE: &str = r#"
<!doctype HTML>
<html>
<head><title>foo</title></head>
<body><p>Hi.</p></body>
</html>
"#;
const HTML_TWO_TABLES: &str = r#"
<!doctype HTML>
<html>
<head><title>foo</title></head>
<body>
<table id="first">
<tr><th>Name</th><th>Age</th></tr>
<tr><td>John</td><td>20</td></tr>
</table>
<table id="second">
<tr><th>Name</th><th>Weight</th></tr>
<tr><td>John</td><td>150</td></tr>
</table>
</body>
</html>
"#;
const HTML_TABLE_FRAGMENT: &str = r#"
<table id="first">
<tr><th>Name</th><th>Age</th></tr>
<tr><td>John</td><td>20</td></tr>
</table>
</body>
</html>
"#;
/*
const HTML_TABLE_WIKIPEDIA_WITH_COLUMN_NAMES: &str = r#"
<table class="wikitable">
<caption>Excel 2007 formats
</caption>
<tbody><tr>
<th>Format
</th>
<th>Extension
</th>
<th>Description
</th></tr>
<tr>
<td>Excel Workbook
</td>
<td><code class="mw-highlight mw-highlight-lang-text mw-content-ltr" id="" style="" dir="ltr">.xlsx</code>
</td>
<td>The default Excel 2007 and later workbook format. In reality, a <a href="/wiki/Zip_(file_format)" class="medirect" title="Zip (file format)">Zip</a> compressed archive with a directory structure of <a href="/wiki/XML" title="XML">XML</a> text documents.Functions as the primary replacement for the former binary .xls format, although it does not support Excel macroor security reasons. Saving as .xlsx offers file size reduction over .xls<sup id="cite_ref-38" class="referencea href="#cite_note-38">[38]</a></sup>
</td></tr> <tr>
<td>Excel ro-enabled Workbook
</td> <td><code class="mw-highlight mw-highlight-lang-text mw-content-ltr" id="" style="" dir="ltr">.xlsm<de> </td>
<As Excel Workbook, but with macro support.
<></tr>
<
<Excel Binary Workbook
<>
<<code class="mw-highlight mw-highlight-lang-text mw-content-ltr" id="" style="" dir="ltr">.xlsb</code>
<>
<As Excel Macro-enabled Workbook, but storing information in binary form rather than XML documents for openingd ing documents more quickly and efficiently. Intended especially for very large documents with tens of thousands s, and/or several hundreds
f umns. This format is very useful for shrinking large Excel files as is often the case when doing data analysis. </td></tr>
<tr>
<td>Excel Macro-enabled Template
</td>
<td><code class="mw-highlight mw-highlight-lang-text mw-content-ltr" id="" style="" dir="ltr">.xltm</code>
</td>
<td>A template document that forms a basis for actual workbooks, with macro support. The replacement for the o.xlt format.
</td></tr> <tr>
<td>Excel -in
</td> <td><code class="mw-highlight mw-highlight-lang-text mw-content-ltr" id="" style="" dir="ltr">.xlam<de> </td>
<Excel add-in to add extra functionality and tools. Inherent macro support because of the file purpose.
<></tr></tbody></table>
"
ct HTML_TABLE_WIKIPEDIA_COLUMNS_AS_ROWS: &str = r#"
<tabllass="infobox vevent">
<caon class="infobox-title summary">
Mosoft Excel
</cion>
<tb>
<
d colspan="2" class="infobox-image">
<a
href="/wiki/File:Microsoft_Office_Excel_(2019%E2%80%93present).svg"
class="image"
><img
alt="Microsoft Office Excel (2019–present).svg"
src="//upload.wikimedia.org/wikipedia/commons/thumb/3/34/Microsoft_Office_Excel_%282019%E2%80%93present%2vgpx-Microsoft_Office_Excel_%282019%E2%80%93present%29.svg.png"
decoding="async" width="69"
height="64" srcset="
//upload.imedia.org/wikipedia/commons/thumb/3/34/Microsoft_Office_Excel_%282019%E2%80%93present%29.svgx-Microsoft_Office_el_%282019%E2%80%93present%29.svg.png 1.5x,
//uploadkimedia.org/wikipedia/commons/thumb/3/34/Microsoft_Office_Excel_%282019%E2%80%93present%29.svgx-Microsoft_Officecel_%282019%E2%80%93present%29.svg.png 2x
" data-file-width="512"
d-file-height="476"
/></a/ </td>
/tr> tr>
<tdlspan="2" class="infobox-image">
<ref="/wiki/File:Microsoft_Excel.png" class="image"
img
alt="Microsoft Excel.png"
src="//upload.wikimedia.org/wikipedia/en/thumb/9/94/Microsoft_Excel.png/300px-Microsoft_Excel.png"
decoding="async"
width="300"
height="190"
srcset="
//upload.wikimedia.org/wikipedia/en/thumb/9/94/Microsoft_Excel.png/450px-Microsoft_Excel.png 1.5x,
//upload.wikimedia.org/wikipedia/en/thumb/9/94/Microsoft_Excel.png/600px-Microsoft_Excel.png 2x
"
data-file-width="800"
data-file-height="507"
/a>
< class="infobox-caption">
simple
href="/wiki/Line_chart" title="Line chart">line chart</a> being
created in Excel, running on
<a href="/wiki/Windows_10" title="Windows 10">Windows 10</a>
/div>
d>
</
<t// <th scope="row" class="infobox-label" style="white-space: nowrap">
a href="/wiki/Programmer" title="Programmer">Developer(s)</a>
h>
class="infobox-data">
a href="/wiki/Microsoft" title="Microsoft">Microsoft</a>
d>
</
<t// <th scope="row" class="infobox-label" style="white-space: nowrap">
nitial release
h>
class="infobox-data">
987<span class="noprint">; 34 years ago</span
<span style="display: none"
> (<span class="bday dtstart published updated">1987</span
>)</span
d>
</
<ttyle="display: none">
colspan="2" class="infobox-full-data"></td>
</
<t// <th scope="row" class="infobox-label" style="white-space: nowrap">
a
href="/wiki/Software_release_life_cycle"
title="Software release life cycle"
>Stable release</a
>
</th>
<td class="infobox-data">
<div style="margin: 0px">
2103 (16.0.13901.20400) / April 13, 2021<span class="noprint"
>; 4 months ago</span
><span style="display: none"
> (<span class="bday dtstart published updated"
>2021-04-13</span
>)</span
><sup id="cite_ref-1" class="reference"
><a href="#cite_note-1">[1]</a></sup
>
</div>
</td>
</tr>
<tr style="display: none">
<td colspan="2"></td>
</tr>
<tr>
<th scope="row" class="infobox-label" style="white-space: nowrap">
<a href="/wiki/Operating_system" title="Operating system"
>Operating system</a
>
</th>
<td class="infobox-data">
<a href="/wiki/Microsoft_Windows" title="Microsoft Windows"
>Microsoft Windows</a
>
</td>
</tr>
<tr>
<th scope="row" class="infobox-label" style="white-space: nowrap">
<a
href="/wiki/Software_categories#Categorization_approaches"
title="Software categories"
>Type</a
>
</th>
<td class="infobox-data">
<a href="/wiki/Spreadsheet" title="Spreadsheet">Spreadsheet</a>
</td>
</tr>
<tr>
<th scope="row" class="infobox-label" style="white-space: nowrap">
<a href="/wiki/Software_license" title="Software license">License</a>
</th>
<td class="infobox-data">
<a href="/wiki/Trialware" class="mw-redirect" title="Trialware"
>Trialware</a
><sup id="cite_ref-2" class="reference"
><a href="#cite_note-2">[2]</a></sup
>
</td>
</tr>
<tr>
<th scope="row" class="infobox-label" style="white-space: nowrap">
Website
</th>
<td class="infobox-data">
<span class="url"
><a
rel="nofollow"
class="external text"
href="http://products.office.com/en-us/excel"
>products<wbr />.office<wbr />.com<wbr />/en-us<wbr />/excel</a
></span
>
</td>
</tr>
</tbody>
</table>
"#;
*/
#[test]
fn test_find_first_none() {
assert_eq!(None, WebTable::find_first(""));
assert_eq!(None, WebTable::find_first("foo"));
assert_eq!(None, WebTable::find_first(HTML_NO_TABLE));
}
#[test]
fn test_find_first_empty() {
let empty = WebTable {
headers: HashMap::new(),
data: Vec::new(),
};
assert_eq!(Some(empty), WebTable::find_first(TABLE_EMPTY));
}
#[test]
fn test_find_first_some() {
assert!(WebTable::find_first(TABLE_TH).is_some());
assert!(WebTable::find_first(TABLE_TD).is_some());
}
#[test]
fn test_find_by_id_none() {
assert_eq!(None, WebTable::find_by_id("", ""));
assert_eq!(None, WebTable::find_by_id("foo", "id"));
assert_eq!(None, WebTable::find_by_id(HTML_NO_TABLE, "id"));
assert_eq!(None, WebTable::find_by_id(TABLE_EMPTY, "id"));
assert_eq!(None, WebTable::find_by_id(TABLE_TH, "id"));
assert_eq!(None, WebTable::find_by_id(TABLE_TH, ""));
assert_eq!(None, WebTable::find_by_id(HTML_TWO_TABLES, "id"));
}
#[test]
fn test_find_by_id_some() {
assert!(WebTable::find_by_id(HTML_TWO_TABLES, "first").is_some());
assert!(WebTable::find_by_id(HTML_TWO_TABLES, "second").is_some());
}
#[test]
fn test_find_by_headers_empty() {
let headers: [&str; 0] = [];
assert_eq!(None, WebTable::find_by_headers("", &headers, false));
assert_eq!(None, WebTable::find_by_headers("foo", &headers, false));
assert_eq!(
None,
WebTable::find_by_headers(HTML_NO_TABLE, &headers, false)
);
assert!(WebTable::find_by_headers(TABLE_EMPTY, &headers, false).is_some());
assert!(WebTable::find_by_headers(HTML_TWO_TABLES, &headers, false).is_some());
}
#[test]
fn test_find_by_headers_none() {
let headers = ["Name", "Age"];
let bad_headers = ["Name", "BAD"];
assert_eq!(None, WebTable::find_by_headers("", &headers, false));
assert_eq!(None, WebTable::find_by_headers("foo", &headers, false));
assert_eq!(
None,
WebTable::find_by_headers(HTML_NO_TABLE, &headers, false)
);
assert_eq!(
None,
WebTable::find_by_headers(TABLE_EMPTY, &bad_headers, false)
);
assert_eq!(
None,
WebTable::find_by_headers(TABLE_TH, &bad_headers, false)
);
assert_eq!(None, WebTable::find_by_headers(TABLE_TD, &headers, false));
assert_eq!(
None,
WebTable::find_by_headers(TABLE_TD, &bad_headers, false)
);
}
#[test]
fn test_find_by_headers_some() {
let headers: [&str; 0] = [];
assert!(WebTable::find_by_headers(TABLE_TH, &headers, false).is_some());
assert!(WebTable::find_by_headers(TABLE_TH_TD, &headers, false).is_some());
assert!(WebTable::find_by_headers(HTML_TWO_TABLES, &headers, false).is_some());
let headers = ["Name"];
assert!(WebTable::find_by_headers(TABLE_TH, &headers, false).is_some());
assert!(WebTable::find_by_headers(TABLE_TH_TD, &headers, false).is_some());
assert!(WebTable::find_by_headers(HTML_TWO_TABLES, &headers, false).is_some());
let headers = ["Age", "Name"];
assert!(WebTable::find_by_headers(TABLE_TH, &headers, false).is_some());
assert!(WebTable::find_by_headers(TABLE_TH_TD, &headers, false).is_some());
assert!(WebTable::find_by_headers(HTML_TWO_TABLES, &headers, false).is_some());
}
#[test]
fn test_find_first_incomplete_fragment() {
assert!(WebTable::find_first(HTML_TABLE_FRAGMENT).is_some());
}
#[test]
fn test_headers_empty() {
let empty = HashMap::new();
assert_eq!(&empty, WebTable::find_first(TABLE_TD).unwrap().headers());
assert_eq!(&empty, WebTable::find_first(TABLE_TD_TD).unwrap().headers());
}
#[test]
fn test_headers_nonempty() {
let mut headers = HashMap::new();
headers.insert("Name".to_string(), 0);
headers.insert("Age".to_string(), 1);
assert_eq!(&headers, WebTable::find_first(TABLE_TH).unwrap().headers());
assert_eq!(
&headers,
WebTable::find_first(TABLE_TH_TD).unwrap().headers()
);
assert_eq!(
&headers,
WebTable::find_first(TABLE_TH_TH).unwrap().headers()
);
headers.insert("Extra".to_string(), 2);
assert_eq!(
&headers,
WebTable::find_first(TABLE_COMPLEX).unwrap().headers()
);
}
#[test]
fn test_iter_empty() {
assert_eq!(0, WebTable::find_first(TABLE_EMPTY).unwrap().iter().count());
assert_eq!(0, WebTable::find_first(TABLE_TH).unwrap().iter().count());
}
#[test]
fn test_iter_nonempty() {
assert_eq!(1, WebTable::find_first(TABLE_TD).unwrap().iter().count());
assert_eq!(1, WebTable::find_first(TABLE_TH_TD).unwrap().iter().count());
assert_eq!(2, WebTable::find_first(TABLE_TD_TD).unwrap().iter().count());
assert_eq!(1, WebTable::find_first(TABLE_TH_TH).unwrap().iter().count());
assert_eq!(
5,
WebTable::find_first(TABLE_COMPLEX).unwrap().iter().count()
);
}
#[test]
fn test_row_is_empty() {
let table = WebTable::find_first(TABLE_TD).unwrap();
assert_eq!(
vec![false],
table.iter().map(|r| r.is_empty()).collect::<Vec<_>>()
);
let table = WebTable::find_first(TABLE_COMPLEX).unwrap();
assert_eq!(
vec![false, false, true, false, false],
table.iter().map(|r| r.is_empty()).collect::<Vec<_>>()
);
}
#[test]
fn test_row_len() {
let table = WebTable::find_first(TABLE_TD).unwrap();
assert_eq!(vec![2], table.iter().map(|r| r.len()).collect::<Vec<_>>());
let table = WebTable::find_first(TABLE_COMPLEX).unwrap();
assert_eq!(
vec![2, 3, 0, 3, 4],
table.iter().map(|r| r.len()).collect::<Vec<_>>()
);
}
#[test]
fn test_row_len_two_tables() {
let tables = WebTable::find_all_tables(HTML_TWO_TABLES).unwrap();
let mut tables_iter = tables.iter();
let table_1 = tables_iter.next().unwrap();
let table_2 = tables_iter.next().unwrap();
assert_eq!(vec![2], table_1.iter().map(|r| r.len()).collect::<Vec<_>>());
assert_eq!(vec![2], table_2.iter().map(|r| r.len()).collect::<Vec<_>>());
let tables = WebTable::find_all_tables(TWO_TABLES_COMPLEX).unwrap();
let mut tables_iter = tables.iter();
let table_1 = tables_iter.next().unwrap();
let table_2 = tables_iter.next().unwrap();
assert_eq!(
vec![2, 3, 0, 3, 4],
table_1.iter().map(|r| r.len()).collect::<Vec<_>>()
);
assert_eq!(
vec![2, 3, 0, 3, 4],
table_2.iter().map(|r| r.len()).collect::<Vec<_>>()
);
}
#[test]
fn test_row_get_without_headers() {
let table = WebTable::find_first(TABLE_TD).unwrap();
let mut iter = table.iter();
let row = iter.next().unwrap();
assert_eq!(None, row.get(""));
assert_eq!(None, row.get("foo"));
assert_eq!(None, row.get("Name"));
assert_eq!(None, row.get("Age"));
assert_eq!(None, iter.next());
}
#[test]
fn test_row_get_with_headers() {
let table = WebTable::find_first(TABLE_TH_TD).unwrap();
let mut iter = table.iter();
let row = iter.next().unwrap();
assert_eq!(None, row.get(""));
assert_eq!(None, row.get("foo"));
assert_eq!(Some("John"), row.get("Name"));
assert_eq!(Some("20"), row.get("Age"));
assert_eq!(None, iter.next());
}
#[test]
fn test_row_get_complex() {
let table = WebTable::find_first(TABLE_COMPLEX).unwrap();
let mut iter = table.iter();
let row = iter.next().unwrap();
assert_eq!(Some("John"), row.get("Name"));
assert_eq!(Some("20"), row.get("Age"));
assert_eq!(None, row.get("Extra"));
let row = iter.next().unwrap();
assert_eq!(Some("May"), row.get("Name"));
assert_eq!(Some("30"), row.get("Age"));
assert_eq!(Some("foo"), row.get("Extra"));
let row = iter.next().unwrap();
assert_eq!(None, row.get("Name"));
assert_eq!(None, row.get("Age"));
assert_eq!(None, row.get("Extra"));
let row = iter.next().unwrap();
assert_eq!(Some(""), row.get("Name"));
assert_eq!(Some(""), row.get("Age"));
assert_eq!(Some(""), row.get("Extra"));
let row = iter.next().unwrap();
assert_eq!(Some("a"), row.get("Name"));
assert_eq!(Some("b"), row.get("Age"));
assert_eq!(Some("c"), row.get("Extra"));
assert_eq!(None, iter.next());
}
#[test]
fn test_two_tables_row_get_complex() {
let tables = WebTable::find_all_tables(TWO_TABLES_COMPLEX).unwrap();
let mut tables_iter = tables.iter();
let table_1 = tables_iter.next().unwrap();
let table_2 = tables_iter.next().unwrap();
let mut iter_1 = table_1.iter();
let mut iter_2 = table_2.iter();
let row_table_1 = iter_1.next().unwrap();
let row_table_2 = iter_2.next().unwrap();
assert_eq!(Some("John"), row_table_1.get("Name"));
assert_eq!(Some("20"), row_table_1.get("Age"));
assert_eq!(None, row_table_1.get("Extra"));
assert_eq!(Some("Carpenter"), row_table_2.get("Profession"));
assert_eq!(Some("Single"), row_table_2.get("Civil State"));
assert_eq!(None, row_table_2.get("Extra"));
let row_table_1 = iter_1.next().unwrap();
let row_table_2 = iter_2.next().unwrap();
assert_eq!(Some("May"), row_table_1.get("Name"));
assert_eq!(Some("30"), row_table_1.get("Age"));
assert_eq!(Some("foo"), row_table_1.get("Extra"));
assert_eq!(Some("Mechanic"), row_table_2.get("Profession"));
assert_eq!(Some("Married"), row_table_2.get("Civil State"));
assert_eq!(Some("bar"), row_table_2.get("Extra"));
let row_table_1 = iter_1.next().unwrap();
let row_table_2 = iter_2.next().unwrap();
assert_eq!(None, row_table_1.get("Name"));
assert_eq!(None, row_table_1.get("Age"));
assert_eq!(None, row_table_1.get("Extra"));
assert_eq!(None, row_table_2.get("Name"));
assert_eq!(None, row_table_2.get("Age"));
assert_eq!(None, row_table_2.get("Extra"));
let row_table_1 = iter_1.next().unwrap();
let row_table_2 = iter_2.next().unwrap();
assert_eq!(Some(""), row_table_1.get("Name"));
assert_eq!(Some(""), row_table_1.get("Age"));
assert_eq!(Some(""), row_table_1.get("Extra"));
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | true |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_query/src/query.rs | crates/nu_plugin_query/src/query.rs | use crate::{
query_json::QueryJson, query_web::QueryWeb, query_webpage_info::QueryWebpageInfo,
query_xml::QueryXml,
};
use nu_plugin::{EvaluatedCall, Plugin, PluginCommand, SimplePluginCommand};
use nu_protocol::{Category, LabeledError, Signature, Value};
#[derive(Default)]
pub struct Query;
impl Query {
pub fn new() -> Self {
Default::default()
}
}
impl Plugin for Query {
fn version(&self) -> String {
env!("CARGO_PKG_VERSION").into()
}
fn commands(&self) -> Vec<Box<dyn PluginCommand<Plugin = Self>>> {
vec![
Box::new(QueryCommand),
Box::new(QueryJson),
Box::new(QueryXml),
Box::new(QueryWeb),
Box::new(QueryWebpageInfo),
]
}
}
// With no subcommand
pub struct QueryCommand;
impl SimplePluginCommand for QueryCommand {
type Plugin = Query;
fn name(&self) -> &str {
"query"
}
fn description(&self) -> &str {
"Show all the query commands"
}
fn signature(&self) -> Signature {
Signature::build(PluginCommand::name(self)).category(Category::Filters)
}
fn run(
&self,
_plugin: &Query,
engine: &nu_plugin::EngineInterface,
call: &EvaluatedCall,
_input: &Value,
) -> Result<Value, LabeledError> {
Ok(Value::string(engine.get_help()?, call.head))
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_query/src/main.rs | crates/nu_plugin_query/src/main.rs | use nu_plugin::{JsonSerializer, serve_plugin};
use nu_plugin_query::Query;
fn main() {
serve_plugin(&Query {}, JsonSerializer {})
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_query/src/query_webpage_info.rs | crates/nu_plugin_query/src/query_webpage_info.rs | use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand};
use nu_protocol::{Category, Example, LabeledError, Record, Signature, Span, Type, Value};
use crate::Query;
pub struct QueryWebpageInfo;
impl SimplePluginCommand for QueryWebpageInfo {
type Plugin = Query;
fn name(&self) -> &str {
"query webpage-info"
}
fn description(&self) -> &str {
"uses the webpage crate to extract info from html: title, description, language, links, RSS feeds, Opengraph, Schema.org, and more"
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.input_output_type(Type::String, Type::record())
.category(Category::Network)
}
fn examples(&self) -> Vec<Example<'_>> {
web_examples()
}
fn run(
&self,
_plugin: &Query,
_engine: &EngineInterface,
_call: &EvaluatedCall,
input: &Value,
) -> Result<Value, LabeledError> {
let span = input.span();
match input {
Value::String { val, .. } => execute_webpage(val, span),
_ => Err(LabeledError::new("Requires text input")
.with_label("expected text from pipeline", span)),
}
}
}
pub fn web_examples() -> Vec<Example<'static>> {
vec![Example {
example: "http get https://phoronix.com | query webpage-info",
description: "extract detailed info from phoronix.com website",
result: None,
}]
}
fn execute_webpage(html: &str, span: Span) -> Result<Value, LabeledError> {
let info = webpage::HTML::from_string(html.to_string(), None)
.map_err(|e| LabeledError::new(e.to_string()).with_label("error parsing html", span))?;
let value = to_value(info, span).map_err(|e| {
LabeledError::new(e.to_string()).with_label("error convert Value::Record", span)
})?;
Ok(value)
}
// revive nu-serde sketch
use serde::Serialize;
/// Convert any serde:Serialize into a `nu_protocol::Value`
pub fn to_value<T>(value: T, span: Span) -> Result<Value, Error>
where
T: Serialize,
{
value.serialize(&ValueSerializer { span })
}
struct ValueSerializer {
span: Span,
}
struct MapSerializer<'a> {
record: Record,
serializer: &'a ValueSerializer,
current_key: Option<String>,
}
impl<'a> serde::Serializer for &'a ValueSerializer {
type Ok = Value;
type Error = Error;
type SerializeSeq = SeqSerializer<'a>;
type SerializeTuple = SeqSerializer<'a>;
type SerializeTupleStruct = SeqSerializer<'a>;
type SerializeTupleVariant = SeqSerializer<'a>;
type SerializeMap = MapSerializer<'a>;
type SerializeStruct = MapSerializer<'a>;
type SerializeStructVariant = MapSerializer<'a>;
fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
Ok(Value::bool(v, self.span))
}
fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
Ok(Value::int(v.into(), self.span))
}
fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
Ok(Value::int(v.into(), self.span))
}
fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
Ok(Value::int(v.into(), self.span))
}
fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
Ok(Value::int(v, self.span))
}
fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
Ok(Value::int(v.into(), self.span))
}
fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
Ok(Value::int(v.into(), self.span))
}
fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
Ok(Value::int(v.into(), self.span))
}
fn serialize_u64(self, _v: u64) -> Result<Self::Ok, Self::Error> {
// TODO: how to represent a u64 value a Value<i64>?
Err(Error::new("the numbers are too big"))
// Ok(Value::int(v.into(), self.span))
}
fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
Ok(Value::float(v.into(), self.span))
}
fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
Ok(Value::float(v, self.span))
}
fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
Ok(Value::string(v, self.span))
}
fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
Ok(Value::string(v, self.span))
}
fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> {
Ok(Value::binary(v, self.span))
}
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
Ok(Value::nothing(self.span))
}
fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: Serialize + ?Sized,
{
value.serialize(self)
}
fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
// TODO: is this OK?
Ok(Value::nothing(self.span))
}
fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
// TODO: is this OK?
Ok(Value::nothing(self.span))
}
fn serialize_unit_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
) -> Result<Self::Ok, Self::Error> {
// TODO: is this OK?
Ok(Value::nothing(self.span))
}
fn serialize_newtype_struct<T>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: Serialize + ?Sized,
{
value.serialize(self)
}
fn serialize_newtype_variant<T>(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: Serialize + ?Sized,
{
value.serialize(self)
}
fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
Ok(SeqSerializer::new(self))
}
fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> {
Ok(SeqSerializer::new(self))
}
fn serialize_tuple_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleStruct, Self::Error> {
Ok(SeqSerializer::new(self))
}
fn serialize_tuple_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleVariant, Self::Error> {
Ok(SeqSerializer::new(self))
}
fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
Ok(MapSerializer::new(self))
}
fn serialize_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeStruct, Self::Error> {
Ok(MapSerializer::new(self))
}
fn serialize_struct_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_len: usize,
) -> Result<Self::SerializeStructVariant, Self::Error> {
Ok(MapSerializer::new(self))
}
}
pub struct Error {
message: String,
}
impl Error {
pub fn new<T: std::fmt::Display>(msg: T) -> Self {
Error {
message: msg.to_string(),
}
}
}
impl serde::ser::Error for Error {
fn custom<T: std::fmt::Display>(msg: T) -> Self {
Error::new(msg.to_string())
}
}
impl std::fmt::Debug for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.message)
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.message)
}
}
impl std::error::Error for Error {}
//
// maps
impl<'a> MapSerializer<'a> {
fn new(serializer: &'a ValueSerializer) -> Self {
Self {
record: Record::new(),
current_key: None,
serializer,
}
}
}
impl serde::ser::SerializeStruct for MapSerializer<'_> {
type Ok = Value;
type Error = Error;
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
self.record
.insert(key.to_owned(), value.serialize(self.serializer)?);
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(Value::record(self.record, self.serializer.span))
}
}
impl serde::ser::SerializeMap for MapSerializer<'_> {
type Ok = Value;
type Error = Error;
fn serialize_key<T>(&mut self, key: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
let value = serde_json::to_value(key).map_err(Error::new)?;
let key = value
.as_str()
.ok_or(Error::new("key must be a string"))?
.to_string();
self.current_key = Some(key);
Ok(())
}
fn serialize_value<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
let key = self.current_key.take().ok_or(Error::new("key expected"))?;
self.record.insert(key, value.serialize(self.serializer)?);
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(Value::record(self.record, self.serializer.span))
}
}
impl serde::ser::SerializeStructVariant for MapSerializer<'_> {
type Ok = Value;
type Error = Error;
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
self.record
.insert(key.to_owned(), value.serialize(self.serializer)?);
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(Value::record(self.record, self.serializer.span))
}
}
//
// sequences
struct SeqSerializer<'a> {
seq: Vec<Value>,
serializer: &'a ValueSerializer,
}
impl<'a> SeqSerializer<'a> {
fn new(serializer: &'a ValueSerializer) -> Self {
Self {
seq: Vec::new(),
serializer,
}
}
}
impl serde::ser::SerializeSeq for SeqSerializer<'_> {
type Ok = Value;
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
self.seq.push(value.serialize(self.serializer)?);
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(Value::list(self.seq, self.serializer.span))
}
}
impl serde::ser::SerializeTuple for SeqSerializer<'_> {
type Ok = Value;
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
self.seq.push(value.serialize(self.serializer)?);
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(Value::list(self.seq, self.serializer.span))
}
}
impl serde::ser::SerializeTupleStruct for SeqSerializer<'_> {
type Ok = Value;
type Error = Error;
fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
self.seq.push(value.serialize(self.serializer)?);
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(Value::list(self.seq, self.serializer.span))
}
}
impl serde::ser::SerializeTupleVariant for SeqSerializer<'_> {
type Ok = Value;
type Error = Error;
fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
self.seq.push(value.serialize(self.serializer)?);
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(Value::list(self.seq, self.serializer.span))
}
}
#[cfg(test)]
mod tests {
use super::*;
const HTML: &str = r#"
<html><head><meta><title>My Title</title></head></html>
"#;
#[test]
fn test_basics() {
let info = execute_webpage(HTML, Span::test_data()).unwrap();
let record = info.as_record().unwrap();
assert_eq!(record.get("title").unwrap().as_str().unwrap(), "My Title");
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-color-config/src/color_config.rs | crates/nu-color-config/src/color_config.rs | use crate::{
NuStyle,
nu_style::{color_from_hex, lookup_style},
parse_nustyle,
};
use nu_ansi_term::Style;
use nu_protocol::{Record, Value};
use std::collections::HashMap;
pub fn lookup_ansi_color_style(s: &str) -> Style {
if s.starts_with('#') {
color_from_hex(s)
.ok()
.and_then(|c| c.map(|c| c.normal()))
.unwrap_or_default()
} else if s.starts_with('{') {
color_string_to_nustyle(s)
} else {
lookup_style(s)
}
}
pub fn get_color_map(colors: &HashMap<String, Value>) -> HashMap<String, Style> {
let mut hm: HashMap<String, Style> = HashMap::new();
for (key, value) in colors {
parse_map_entry(&mut hm, key, value);
}
hm
}
fn parse_map_entry(hm: &mut HashMap<String, Style>, key: &str, value: &Value) {
let value = match value {
Value::String { val, .. } => Some(lookup_ansi_color_style(val)),
Value::Record { val, .. } => get_style_from_value(val).map(parse_nustyle),
_ => None,
};
if let Some(value) = value {
hm.entry(key.to_owned()).or_insert(value);
}
}
fn get_style_from_value(record: &Record) -> Option<NuStyle> {
let mut was_set = false;
let mut style = NuStyle::from(Style::default());
for (col, val) in record {
match col.as_str() {
"bg" => {
if let Value::String { val, .. } = val {
style.bg = Some(val.clone());
was_set = true;
}
}
"fg" => {
if let Value::String { val, .. } = val {
style.fg = Some(val.clone());
was_set = true;
}
}
"attr" => {
if let Value::String { val, .. } = val {
style.attr = Some(val.clone());
was_set = true;
}
}
_ => (),
}
}
if was_set { Some(style) } else { None }
}
fn color_string_to_nustyle(color_string: &str) -> Style {
// eprintln!("color_string: {}", &color_string);
if color_string.is_empty() {
return Style::default();
}
let nu_style = match nu_json::from_str::<NuStyle>(color_string) {
Ok(s) => s,
Err(_) => return Style::default(),
};
parse_nustyle(nu_style)
}
#[cfg(test)]
mod tests {
use super::*;
use nu_ansi_term::{Color, Style};
use nu_protocol::{Span, Value, record};
#[test]
fn test_color_string_to_nustyle_empty_string() {
let color_string = String::new();
let style = color_string_to_nustyle(&color_string);
assert_eq!(style, Style::default());
}
#[test]
fn test_color_string_to_nustyle_valid_string() {
let color_string = r#"{"fg": "black", "bg": "white", "attr": "b"}"#;
let style = color_string_to_nustyle(color_string);
assert_eq!(style.foreground, Some(Color::Black));
assert_eq!(style.background, Some(Color::White));
assert!(style.is_bold);
}
#[test]
fn test_color_string_to_nustyle_invalid_string() {
let color_string = "invalid string";
let style = color_string_to_nustyle(color_string);
assert_eq!(style, Style::default());
}
#[test]
fn test_get_style_from_value() {
// Test case 1: all values are valid
let record = record! {
"bg" => Value::test_string("red"),
"fg" => Value::test_string("blue"),
"attr" => Value::test_string("bold"),
};
let expected_style = NuStyle {
bg: Some("red".to_string()),
fg: Some("blue".to_string()),
attr: Some("bold".to_string()),
};
assert_eq!(get_style_from_value(&record), Some(expected_style));
// Test case 2: no values are valid
let record = record! {
"invalid" => Value::nothing(Span::test_data()),
};
assert_eq!(get_style_from_value(&record), None);
// Test case 3: some values are valid
let record = record! {
"bg" => Value::test_string("green"),
"invalid" => Value::nothing(Span::unknown()),
};
let expected_style = NuStyle {
bg: Some("green".to_string()),
fg: None,
attr: None,
};
assert_eq!(get_style_from_value(&record), Some(expected_style));
}
#[test]
fn test_parse_map_entry() {
let mut hm = HashMap::new();
let key = "test_key".to_owned();
let value = Value::string("red", Span::unknown());
parse_map_entry(&mut hm, &key, &value);
assert_eq!(hm.get(&key), Some(&lookup_ansi_color_style("red")));
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-color-config/src/nu_style.rs | crates/nu-color-config/src/nu_style.rs | use nu_ansi_term::{Color, Style};
use nu_protocol::Value;
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize, PartialEq, Eq, Debug)]
pub struct NuStyle {
pub fg: Option<String>,
pub bg: Option<String>,
pub attr: Option<String>,
}
impl From<Style> for NuStyle {
fn from(s: Style) -> Self {
Self {
bg: s.background.and_then(color_to_string),
fg: s.foreground.and_then(color_to_string),
attr: style_get_attr(s),
}
}
}
fn style_get_attr(s: Style) -> Option<String> {
let mut attrs = String::new();
if s.is_blink {
attrs.push('l');
};
if s.is_bold {
attrs.push('b');
};
if s.is_dimmed {
attrs.push('d');
};
if s.is_hidden {
attrs.push('h');
};
if s.is_italic {
attrs.push('i');
};
if s.is_reverse {
attrs.push('r');
};
if s.is_strikethrough {
attrs.push('s');
};
if s.is_underline {
attrs.push('u');
};
if attrs.is_empty() { None } else { Some(attrs) }
}
fn color_to_string(color: Color) -> Option<String> {
match color {
Color::Black => Some(String::from("black")),
Color::DarkGray => Some(String::from("dark_gray")),
Color::Red => Some(String::from("red")),
Color::LightRed => Some(String::from("light_red")),
Color::Green => Some(String::from("green")),
Color::LightGreen => Some(String::from("light_green")),
Color::Yellow => Some(String::from("yellow")),
Color::LightYellow => Some(String::from("light_yellow")),
Color::Blue => Some(String::from("blue")),
Color::LightBlue => Some(String::from("light_blue")),
Color::Purple => Some(String::from("purple")),
Color::LightPurple => Some(String::from("light_purple")),
Color::Magenta => Some(String::from("magenta")),
Color::LightMagenta => Some(String::from("light_magenta")),
Color::Cyan => Some(String::from("cyan")),
Color::LightCyan => Some(String::from("light_cyan")),
Color::White => Some(String::from("white")),
Color::LightGray => Some(String::from("light_gray")),
Color::Default => Some(String::from("default")),
Color::Rgb(r, g, b) => Some(format!("#{r:X}{g:X}{b:X}")),
Color::Fixed(_) => None,
}
}
pub fn parse_nustyle(nu_style: NuStyle) -> Style {
let mut style = Style {
foreground: nu_style.fg.and_then(|fg| lookup_color_str(&fg)),
background: nu_style.bg.and_then(|bg| lookup_color_str(&bg)),
..Default::default()
};
if let Some(attrs) = nu_style.attr {
fill_modifiers(&attrs, &mut style)
}
style
}
// Converts the color_config records, { fg, bg, attr }, into a Style.
pub fn color_record_to_nustyle(value: &Value) -> Style {
let mut fg = None;
let mut bg = None;
let mut attr = None;
let v = value.as_record();
if let Ok(record) = v {
for (k, v) in record {
// Because config already type-checked the color_config records, this doesn't bother giving errors
// if there are unrecognised keys or bad values.
if let Ok(v) = v.coerce_string() {
match k.as_str() {
"fg" => fg = Some(v),
"bg" => bg = Some(v),
"attr" => attr = Some(v),
_ => (),
}
}
}
}
parse_nustyle(NuStyle { fg, bg, attr })
}
pub fn color_from_hex(
hex_color: &str,
) -> std::result::Result<Option<Color>, std::num::ParseIntError> {
// right now we only allow hex colors with hashtag and 6 characters
let trimmed = hex_color.trim_matches('#');
if trimmed.len() != 6 {
Ok(None)
} else {
// make a nu_ansi_term::Color::Rgb color by converting hex to decimal
Ok(Some(Color::Rgb(
u8::from_str_radix(&trimmed[..2], 16)?,
u8::from_str_radix(&trimmed[2..4], 16)?,
u8::from_str_radix(&trimmed[4..6], 16)?,
)))
}
}
pub fn lookup_style(s: &str) -> Style {
match s {
"g" | "green" => Color::Green.normal(),
"gb" | "green_bold" => Color::Green.bold(),
"gu" | "green_underline" => Color::Green.underline(),
"gi" | "green_italic" => Color::Green.italic(),
"gd" | "green_dimmed" => Color::Green.dimmed(),
"gr" | "green_reverse" => Color::Green.reverse(),
"gbl" | "green_blink" => Color::Green.blink(),
"gst" | "green_strike" => Color::Green.strikethrough(),
"lg" | "light_green" => Color::LightGreen.normal(),
"lgb" | "light_green_bold" => Color::LightGreen.bold(),
"lgu" | "light_green_underline" => Color::LightGreen.underline(),
"lgi" | "light_green_italic" => Color::LightGreen.italic(),
"lgd" | "light_green_dimmed" => Color::LightGreen.dimmed(),
"lgr" | "light_green_reverse" => Color::LightGreen.reverse(),
"lgbl" | "light_green_blink" => Color::LightGreen.blink(),
"lgst" | "light_green_strike" => Color::LightGreen.strikethrough(),
"r" | "red" => Color::Red.normal(),
"rb" | "red_bold" => Color::Red.bold(),
"ru" | "red_underline" => Color::Red.underline(),
"ri" | "red_italic" => Color::Red.italic(),
"rd" | "red_dimmed" => Color::Red.dimmed(),
"rr" | "red_reverse" => Color::Red.reverse(),
"rbl" | "red_blink" => Color::Red.blink(),
"rst" | "red_strike" => Color::Red.strikethrough(),
"lr" | "light_red" => Color::LightRed.normal(),
"lrb" | "light_red_bold" => Color::LightRed.bold(),
"lru" | "light_red_underline" => Color::LightRed.underline(),
"lri" | "light_red_italic" => Color::LightRed.italic(),
"lrd" | "light_red_dimmed" => Color::LightRed.dimmed(),
"lrr" | "light_red_reverse" => Color::LightRed.reverse(),
"lrbl" | "light_red_blink" => Color::LightRed.blink(),
"lrst" | "light_red_strike" => Color::LightRed.strikethrough(),
"u" | "blue" => Color::Blue.normal(),
"ub" | "blue_bold" => Color::Blue.bold(),
"uu" | "blue_underline" => Color::Blue.underline(),
"ui" | "blue_italic" => Color::Blue.italic(),
"ud" | "blue_dimmed" => Color::Blue.dimmed(),
"ur" | "blue_reverse" => Color::Blue.reverse(),
"ubl" | "blue_blink" => Color::Blue.blink(),
"ust" | "blue_strike" => Color::Blue.strikethrough(),
"lu" | "light_blue" => Color::LightBlue.normal(),
"lub" | "light_blue_bold" => Color::LightBlue.bold(),
"luu" | "light_blue_underline" => Color::LightBlue.underline(),
"lui" | "light_blue_italic" => Color::LightBlue.italic(),
"lud" | "light_blue_dimmed" => Color::LightBlue.dimmed(),
"lur" | "light_blue_reverse" => Color::LightBlue.reverse(),
"lubl" | "light_blue_blink" => Color::LightBlue.blink(),
"lust" | "light_blue_strike" => Color::LightBlue.strikethrough(),
"b" | "black" => Color::Black.normal(),
"bb" | "black_bold" => Color::Black.bold(),
"bu" | "black_underline" => Color::Black.underline(),
"bi" | "black_italic" => Color::Black.italic(),
"bd" | "black_dimmed" => Color::Black.dimmed(),
"br" | "black_reverse" => Color::Black.reverse(),
"bbl" | "black_blink" => Color::Black.blink(),
"bst" | "black_strike" => Color::Black.strikethrough(),
"ligr" | "light_gray" => Color::LightGray.normal(),
"ligrb" | "light_gray_bold" => Color::LightGray.bold(),
"ligru" | "light_gray_underline" => Color::LightGray.underline(),
"ligri" | "light_gray_italic" => Color::LightGray.italic(),
"ligrd" | "light_gray_dimmed" => Color::LightGray.dimmed(),
"ligrr" | "light_gray_reverse" => Color::LightGray.reverse(),
"ligrbl" | "light_gray_blink" => Color::LightGray.blink(),
"ligrst" | "light_gray_strike" => Color::LightGray.strikethrough(),
"y" | "yellow" => Color::Yellow.normal(),
"yb" | "yellow_bold" => Color::Yellow.bold(),
"yu" | "yellow_underline" => Color::Yellow.underline(),
"yi" | "yellow_italic" => Color::Yellow.italic(),
"yd" | "yellow_dimmed" => Color::Yellow.dimmed(),
"yr" | "yellow_reverse" => Color::Yellow.reverse(),
"ybl" | "yellow_blink" => Color::Yellow.blink(),
"yst" | "yellow_strike" => Color::Yellow.strikethrough(),
"ly" | "light_yellow" => Color::LightYellow.normal(),
"lyb" | "light_yellow_bold" => Color::LightYellow.bold(),
"lyu" | "light_yellow_underline" => Color::LightYellow.underline(),
"lyi" | "light_yellow_italic" => Color::LightYellow.italic(),
"lyd" | "light_yellow_dimmed" => Color::LightYellow.dimmed(),
"lyr" | "light_yellow_reverse" => Color::LightYellow.reverse(),
"lybl" | "light_yellow_blink" => Color::LightYellow.blink(),
"lyst" | "light_yellow_strike" => Color::LightYellow.strikethrough(),
"p" | "purple" => Color::Purple.normal(),
"pb" | "purple_bold" => Color::Purple.bold(),
"pu" | "purple_underline" => Color::Purple.underline(),
"pi" | "purple_italic" => Color::Purple.italic(),
"pd" | "purple_dimmed" => Color::Purple.dimmed(),
"pr" | "purple_reverse" => Color::Purple.reverse(),
"pbl" | "purple_blink" => Color::Purple.blink(),
"pst" | "purple_strike" => Color::Purple.strikethrough(),
"lp" | "light_purple" => Color::LightPurple.normal(),
"lpb" | "light_purple_bold" => Color::LightPurple.bold(),
"lpu" | "light_purple_underline" => Color::LightPurple.underline(),
"lpi" | "light_purple_italic" => Color::LightPurple.italic(),
"lpd" | "light_purple_dimmed" => Color::LightPurple.dimmed(),
"lpr" | "light_purple_reverse" => Color::LightPurple.reverse(),
"lpbl" | "light_purple_blink" => Color::LightPurple.blink(),
"lpst" | "light_purple_strike" => Color::LightPurple.strikethrough(),
"m" | "magenta" => Color::Magenta.normal(),
"mb" | "magenta_bold" => Color::Magenta.bold(),
"mu" | "magenta_underline" => Color::Magenta.underline(),
"mi" | "magenta_italic" => Color::Magenta.italic(),
"md" | "magenta_dimmed" => Color::Magenta.dimmed(),
"mr" | "magenta_reverse" => Color::Magenta.reverse(),
"mbl" | "magenta_blink" => Color::Magenta.blink(),
"mst" | "magenta_strike" => Color::Magenta.strikethrough(),
"lm" | "light_magenta" => Color::LightMagenta.normal(),
"lmb" | "light_magenta_bold" => Color::LightMagenta.bold(),
"lmu" | "light_magenta_underline" => Color::LightMagenta.underline(),
"lmi" | "light_magenta_italic" => Color::LightMagenta.italic(),
"lmd" | "light_magenta_dimmed" => Color::LightMagenta.dimmed(),
"lmr" | "light_magenta_reverse" => Color::LightMagenta.reverse(),
"lmbl" | "light_magenta_blink" => Color::LightMagenta.blink(),
"lmst" | "light_magenta_strike" => Color::LightMagenta.strikethrough(),
"c" | "cyan" => Color::Cyan.normal(),
"cb" | "cyan_bold" => Color::Cyan.bold(),
"cu" | "cyan_underline" => Color::Cyan.underline(),
"ci" | "cyan_italic" => Color::Cyan.italic(),
"cd" | "cyan_dimmed" => Color::Cyan.dimmed(),
"cr" | "cyan_reverse" => Color::Cyan.reverse(),
"cbl" | "cyan_blink" => Color::Cyan.blink(),
"cst" | "cyan_strike" => Color::Cyan.strikethrough(),
"lc" | "light_cyan" => Color::LightCyan.normal(),
"lcb" | "light_cyan_bold" => Color::LightCyan.bold(),
"lcu" | "light_cyan_underline" => Color::LightCyan.underline(),
"lci" | "light_cyan_italic" => Color::LightCyan.italic(),
"lcd" | "light_cyan_dimmed" => Color::LightCyan.dimmed(),
"lcr" | "light_cyan_reverse" => Color::LightCyan.reverse(),
"lcbl" | "light_cyan_blink" => Color::LightCyan.blink(),
"lcst" | "light_cyan_strike" => Color::LightCyan.strikethrough(),
"w" | "white" => Color::White.normal(),
"wb" | "white_bold" => Color::White.bold(),
"wu" | "white_underline" => Color::White.underline(),
"wi" | "white_italic" => Color::White.italic(),
"wd" | "white_dimmed" => Color::White.dimmed(),
"wr" | "white_reverse" => Color::White.reverse(),
"wbl" | "white_blink" => Color::White.blink(),
"wst" | "white_strike" => Color::White.strikethrough(),
"dgr" | "dark_gray" => Color::DarkGray.normal(),
"dgrb" | "dark_gray_bold" => Color::DarkGray.bold(),
"dgru" | "dark_gray_underline" => Color::DarkGray.underline(),
"dgri" | "dark_gray_italic" => Color::DarkGray.italic(),
"dgrd" | "dark_gray_dimmed" => Color::DarkGray.dimmed(),
"dgrr" | "dark_gray_reverse" => Color::DarkGray.reverse(),
"dgrbl" | "dark_gray_blink" => Color::DarkGray.blink(),
"dgrst" | "dark_gray_strike" => Color::DarkGray.strikethrough(),
"def" | "default" => Color::Default.normal(),
"defb" | "default_bold" => Color::Default.bold(),
"defu" | "default_underline" => Color::Default.underline(),
"defi" | "default_italic" => Color::Default.italic(),
"defd" | "default_dimmed" => Color::Default.dimmed(),
"defr" | "default_reverse" => Color::Default.reverse(),
// Add xterm 256 colors adding an x prefix where the name conflicts
"xblack" | "xterm_black" => Color::Fixed(0).normal(),
"maroon" | "xterm_maroon" => Color::Fixed(1).normal(),
"xgreen" | "xterm_green" => Color::Fixed(2).normal(),
"olive" | "xterm_olive" => Color::Fixed(3).normal(),
"navy" | "xterm_navy" => Color::Fixed(4).normal(),
"xpurplea" | "xterm_purplea" => Color::Fixed(5).normal(),
"teal" | "xterm_teal" => Color::Fixed(6).normal(),
"silver" | "xterm_silver" => Color::Fixed(7).normal(),
"grey" | "xterm_grey" => Color::Fixed(8).normal(),
"xred" | "xterm_red" => Color::Fixed(9).normal(),
"lime" | "xterm_lime" => Color::Fixed(10).normal(),
"xyellow" | "xterm_yellow" => Color::Fixed(11).normal(),
"xblue" | "xterm_blue" => Color::Fixed(12).normal(),
"fuchsia" | "xterm_fuchsia" => Color::Fixed(13).normal(),
"aqua" | "xterm_aqua" => Color::Fixed(14).normal(),
"xwhite" | "xterm_white" => Color::Fixed(15).normal(),
"grey0" | "xterm_grey0" => Color::Fixed(16).normal(),
"navyblue" | "xterm_navyblue" => Color::Fixed(17).normal(),
"darkblue" | "xterm_darkblue" => Color::Fixed(18).normal(),
"blue3a" | "xterm_blue3a" => Color::Fixed(19).normal(),
"blue3b" | "xterm_blue3b" => Color::Fixed(20).normal(),
"blue1" | "xterm_blue1" => Color::Fixed(21).normal(),
"darkgreen" | "xterm_darkgreen" => Color::Fixed(22).normal(),
"deepskyblue4a" | "xterm_deepskyblue4a" => Color::Fixed(23).normal(),
"deepskyblue4b" | "xterm_deepskyblue4b" => Color::Fixed(24).normal(),
"deepskyblue4c" | "xterm_deepskyblue4c" => Color::Fixed(25).normal(),
"dodgerblue3" | "xterm_dodgerblue3" => Color::Fixed(26).normal(),
"dodgerblue2" | "xterm_dodgerblue2" => Color::Fixed(27).normal(),
"green4" | "xterm_green4" => Color::Fixed(28).normal(),
"springgreen4" | "xterm_springgreen4" => Color::Fixed(29).normal(),
"turquoise4" | "xterm_turquoise4" => Color::Fixed(30).normal(),
"deepskyblue3a" | "xterm_deepskyblue3a" => Color::Fixed(31).normal(),
"deepskyblue3b" | "xterm_deepskyblue3b" => Color::Fixed(32).normal(),
"dodgerblue1" | "xterm_dodgerblue1" => Color::Fixed(33).normal(),
"green3a" | "xterm_green3a" => Color::Fixed(34).normal(),
"springgreen3a" | "xterm_springgreen3a" => Color::Fixed(35).normal(),
"darkcyan" | "xterm_darkcyan" => Color::Fixed(36).normal(),
"lightseagreen" | "xterm_lightseagreen" => Color::Fixed(37).normal(),
"deepskyblue2" | "xterm_deepskyblue2" => Color::Fixed(38).normal(),
"deepskyblue1" | "xterm_deepskyblue1" => Color::Fixed(39).normal(),
"green3b" | "xterm_green3b" => Color::Fixed(40).normal(),
"springgreen3b" | "xterm_springgreen3b" => Color::Fixed(41).normal(),
"springgreen2a" | "xterm_springgreen2a" => Color::Fixed(42).normal(),
"cyan3" | "xterm_cyan3" => Color::Fixed(43).normal(),
"darkturquoise" | "xterm_darkturquoise" => Color::Fixed(44).normal(),
"turquoise2" | "xterm_turquoise2" => Color::Fixed(45).normal(),
"green1" | "xterm_green1" => Color::Fixed(46).normal(),
"springgreen2b" | "xterm_springgreen2b" => Color::Fixed(47).normal(),
"springgreen1" | "xterm_springgreen1" => Color::Fixed(48).normal(),
"mediumspringgreen" | "xterm_mediumspringgreen" => Color::Fixed(49).normal(),
"cyan2" | "xterm_cyan2" => Color::Fixed(50).normal(),
"cyan1" | "xterm_cyan1" => Color::Fixed(51).normal(),
"darkreda" | "xterm_darkreda" => Color::Fixed(52).normal(),
"deeppink4a" | "xterm_deeppink4a" => Color::Fixed(53).normal(),
"purple4a" | "xterm_purple4a" => Color::Fixed(54).normal(),
"purple4b" | "xterm_purple4b" => Color::Fixed(55).normal(),
"purple3" | "xterm_purple3" => Color::Fixed(56).normal(),
"blueviolet" | "xterm_blueviolet" => Color::Fixed(57).normal(),
"orange4a" | "xterm_orange4a" => Color::Fixed(58).normal(),
"grey37" | "xterm_grey37" => Color::Fixed(59).normal(),
"mediumpurple4" | "xterm_mediumpurple4" => Color::Fixed(60).normal(),
"slateblue3a" | "xterm_slateblue3a" => Color::Fixed(61).normal(),
"slateblue3b" | "xterm_slateblue3b" => Color::Fixed(62).normal(),
"royalblue1" | "xterm_royalblue1" => Color::Fixed(63).normal(),
"chartreuse4" | "xterm_chartreuse4" => Color::Fixed(64).normal(),
"darkseagreen4a" | "xterm_darkseagreen4a" => Color::Fixed(65).normal(),
"paleturquoise4" | "xterm_paleturquoise4" => Color::Fixed(66).normal(),
"steelblue" | "xterm_steelblue" => Color::Fixed(67).normal(),
"steelblue3" | "xterm_steelblue3" => Color::Fixed(68).normal(),
"cornflowerblue" | "xterm_cornflowerblue" => Color::Fixed(69).normal(),
"chartreuse3a" | "xterm_chartreuse3a" => Color::Fixed(70).normal(),
"darkseagreen4b" | "xterm_darkseagreen4b" => Color::Fixed(71).normal(),
"cadetbluea" | "xterm_cadetbluea" => Color::Fixed(72).normal(),
"cadetblueb" | "xterm_cadetblueb" => Color::Fixed(73).normal(),
"skyblue3" | "xterm_skyblue3" => Color::Fixed(74).normal(),
"steelblue1a" | "xterm_steelblue1a" => Color::Fixed(75).normal(),
"chartreuse3b" | "xterm_chartreuse3b" => Color::Fixed(76).normal(),
"palegreen3a" | "xterm_palegreen3a" => Color::Fixed(77).normal(),
"seagreen3" | "xterm_seagreen3" => Color::Fixed(78).normal(),
"aquamarine3" | "xterm_aquamarine3" => Color::Fixed(79).normal(),
"mediumturquoise" | "xterm_mediumturquoise" => Color::Fixed(80).normal(),
"steelblue1b" | "xterm_steelblue1b" => Color::Fixed(81).normal(),
"chartreuse2a" | "xterm_chartreuse2a" => Color::Fixed(82).normal(),
"seagreen2" | "xterm_seagreen2" => Color::Fixed(83).normal(),
"seagreen1a" | "xterm_seagreen1a" => Color::Fixed(84).normal(),
"seagreen1b" | "xterm_seagreen1b" => Color::Fixed(85).normal(),
"aquamarine1a" | "xterm_aquamarine1a" => Color::Fixed(86).normal(),
"darkslategray2" | "xterm_darkslategray2" => Color::Fixed(87).normal(),
"darkredb" | "xterm_darkredb" => Color::Fixed(88).normal(),
"deeppink4b" | "xterm_deeppink4b" => Color::Fixed(89).normal(),
"darkmagentaa" | "xterm_darkmagentaa" => Color::Fixed(90).normal(),
"darkmagentab" | "xterm_darkmagentab" => Color::Fixed(91).normal(),
"darkvioleta" | "xterm_darkvioleta" => Color::Fixed(92).normal(),
"xpurpleb" | "xterm_purpleb" => Color::Fixed(93).normal(),
"orange4b" | "xterm_orange4b" => Color::Fixed(94).normal(),
"lightpink4" | "xterm_lightpink4" => Color::Fixed(95).normal(),
"plum4" | "xterm_plum4" => Color::Fixed(96).normal(),
"mediumpurple3a" | "xterm_mediumpurple3a" => Color::Fixed(97).normal(),
"mediumpurple3b" | "xterm_mediumpurple3b" => Color::Fixed(98).normal(),
"slateblue1" | "xterm_slateblue1" => Color::Fixed(99).normal(),
"yellow4a" | "xterm_yellow4a" => Color::Fixed(100).normal(),
"wheat4" | "xterm_wheat4" => Color::Fixed(101).normal(),
"grey53" | "xterm_grey53" => Color::Fixed(102).normal(),
"lightslategrey" | "xterm_lightslategrey" => Color::Fixed(103).normal(),
"mediumpurple" | "xterm_mediumpurple" => Color::Fixed(104).normal(),
"lightslateblue" | "xterm_lightslateblue" => Color::Fixed(105).normal(),
"yellow4b" | "xterm_yellow4b" => Color::Fixed(106).normal(),
"darkolivegreen3a" | "xterm_darkolivegreen3a" => Color::Fixed(107).normal(),
"darkseagreen" | "xterm_darkseagreen" => Color::Fixed(108).normal(),
"lightskyblue3a" | "xterm_lightskyblue3a" => Color::Fixed(109).normal(),
"lightskyblue3b" | "xterm_lightskyblue3b" => Color::Fixed(110).normal(),
"skyblue2" | "xterm_skyblue2" => Color::Fixed(111).normal(),
"chartreuse2b" | "xterm_chartreuse2b" => Color::Fixed(112).normal(),
"darkolivegreen3b" | "xterm_darkolivegreen3b" => Color::Fixed(113).normal(),
"palegreen3b" | "xterm_palegreen3b" => Color::Fixed(114).normal(),
"darkseagreen3a" | "xterm_darkseagreen3a" => Color::Fixed(115).normal(),
"darkslategray3" | "xterm_darkslategray3" => Color::Fixed(116).normal(),
"skyblue1" | "xterm_skyblue1" => Color::Fixed(117).normal(),
"chartreuse1" | "xterm_chartreuse1" => Color::Fixed(118).normal(),
"lightgreena" | "xterm_lightgreena" => Color::Fixed(119).normal(),
"lightgreenb" | "xterm_lightgreenb" => Color::Fixed(120).normal(),
"palegreen1a" | "xterm_palegreen1a" => Color::Fixed(121).normal(),
"aquamarine1b" | "xterm_aquamarine1b" => Color::Fixed(122).normal(),
"darkslategray1" | "xterm_darkslategray1" => Color::Fixed(123).normal(),
"red3a" | "xterm_red3a" => Color::Fixed(124).normal(),
"deeppink4c" | "xterm_deeppink4c" => Color::Fixed(125).normal(),
"mediumvioletred" | "xterm_mediumvioletred" => Color::Fixed(126).normal(),
"magenta3" | "xterm_magenta3" => Color::Fixed(127).normal(),
"darkvioletb" | "xterm_darkvioletb" => Color::Fixed(128).normal(),
"purplec" | "xterm_purplec" => Color::Fixed(129).normal(),
"darkorange3a" | "xterm_darkorange3a" => Color::Fixed(130).normal(),
"indianreda" | "xterm_indianreda" => Color::Fixed(131).normal(),
"hotpink3a" | "xterm_hotpink3a" => Color::Fixed(132).normal(),
"mediumorchid3" | "xterm_mediumorchid3" => Color::Fixed(133).normal(),
"mediumorchid" | "xterm_mediumorchid" => Color::Fixed(134).normal(),
"mediumpurple2a" | "xterm_mediumpurple2a" => Color::Fixed(135).normal(),
"darkgoldenrod" | "xterm_darkgoldenrod" => Color::Fixed(136).normal(),
"lightsalmon3a" | "xterm_lightsalmon3a" => Color::Fixed(137).normal(),
"rosybrown" | "xterm_rosybrown" => Color::Fixed(138).normal(),
"grey63" | "xterm_grey63" => Color::Fixed(139).normal(),
"mediumpurple2b" | "xterm_mediumpurple2b" => Color::Fixed(140).normal(),
"mediumpurple1" | "xterm_mediumpurple1" => Color::Fixed(141).normal(),
"gold3a" | "xterm_gold3a" => Color::Fixed(142).normal(),
"darkkhaki" | "xterm_darkkhaki" => Color::Fixed(143).normal(),
"navajowhite3" | "xterm_navajowhite3" => Color::Fixed(144).normal(),
"grey69" | "xterm_grey69" => Color::Fixed(145).normal(),
"lightsteelblue3" | "xterm_lightsteelblue3" => Color::Fixed(146).normal(),
"lightsteelblue" | "xterm_lightsteelblue" => Color::Fixed(147).normal(),
"yellow3a" | "xterm_yellow3a" => Color::Fixed(148).normal(),
"darkolivegreen3c" | "xterm_darkolivegreen3c" => Color::Fixed(149).normal(),
"darkseagreen3b" | "xterm_darkseagreen3b" => Color::Fixed(150).normal(),
"darkseagreen2a" | "xterm_darkseagreen2a" => Color::Fixed(151).normal(),
"lightcyan3" | "xterm_lightcyan3" => Color::Fixed(152).normal(),
"lightskyblue1" | "xterm_lightskyblue1" => Color::Fixed(153).normal(),
"greenyellow" | "xterm_greenyellow" => Color::Fixed(154).normal(),
"darkolivegreen2" | "xterm_darkolivegreen2" => Color::Fixed(155).normal(),
"palegreen1b" | "xterm_palegreen1b" => Color::Fixed(156).normal(),
"darkseagreen2b" | "xterm_darkseagreen2b" => Color::Fixed(157).normal(),
"darkseagreen1a" | "xterm_darkseagreen1a" => Color::Fixed(158).normal(),
"paleturquoise1" | "xterm_paleturquoise1" => Color::Fixed(159).normal(),
"red3b" | "xterm_red3b" => Color::Fixed(160).normal(),
"deeppink3a" | "xterm_deeppink3a" => Color::Fixed(161).normal(),
"deeppink3b" | "xterm_deeppink3b" => Color::Fixed(162).normal(),
"magenta3a" | "xterm_magenta3a" => Color::Fixed(163).normal(),
"magenta3b" | "xterm_magenta3b" => Color::Fixed(164).normal(),
"magenta2a" | "xterm_magenta2a" => Color::Fixed(165).normal(),
"darkorange3b" | "xterm_darkorange3b" => Color::Fixed(166).normal(),
"indianredb" | "xterm_indianredb" => Color::Fixed(167).normal(),
"hotpink3b" | "xterm_hotpink3b" => Color::Fixed(168).normal(),
"hotpink2" | "xterm_hotpink2" => Color::Fixed(169).normal(),
"orchid" | "xterm_orchid" => Color::Fixed(170).normal(),
"mediumorchid1a" | "xterm_mediumorchid1a" => Color::Fixed(171).normal(),
"orange3" | "xterm_orange3" => Color::Fixed(172).normal(),
"lightsalmon3b" | "xterm_lightsalmon3b" => Color::Fixed(173).normal(),
"lightpink3" | "xterm_lightpink3" => Color::Fixed(174).normal(),
"pink3" | "xterm_pink3" => Color::Fixed(175).normal(),
"plum3" | "xterm_plum3" => Color::Fixed(176).normal(),
"violet" | "xterm_violet" => Color::Fixed(177).normal(),
"gold3b" | "xterm_gold3b" => Color::Fixed(178).normal(),
"lightgoldenrod3" | "xterm_lightgoldenrod3" => Color::Fixed(179).normal(),
"tan" | "xterm_tan" => Color::Fixed(180).normal(),
"mistyrose3" | "xterm_mistyrose3" => Color::Fixed(181).normal(),
"thistle3" | "xterm_thistle3" => Color::Fixed(182).normal(),
"plum2" | "xterm_plum2" => Color::Fixed(183).normal(),
"yellow3b" | "xterm_yellow3b" => Color::Fixed(184).normal(),
"khaki3" | "xterm_khaki3" => Color::Fixed(185).normal(),
"lightgoldenrod2" | "xterm_lightgoldenrod2" => Color::Fixed(186).normal(),
"lightyellow3" | "xterm_lightyellow3" => Color::Fixed(187).normal(),
"grey84" | "xterm_grey84" => Color::Fixed(188).normal(),
"lightsteelblue1" | "xterm_lightsteelblue1" => Color::Fixed(189).normal(),
"yellow2" | "xterm_yellow2" => Color::Fixed(190).normal(),
"darkolivegreen1a" | "xterm_darkolivegreen1a" => Color::Fixed(191).normal(),
"darkolivegreen1b" | "xterm_darkolivegreen1b" => Color::Fixed(192).normal(),
"darkseagreen1b" | "xterm_darkseagreen1b" => Color::Fixed(193).normal(),
"honeydew2" | "xterm_honeydew2" => Color::Fixed(194).normal(),
"lightcyan1" | "xterm_lightcyan1" => Color::Fixed(195).normal(),
"red1" | "xterm_red1" => Color::Fixed(196).normal(),
"deeppink2" | "xterm_deeppink2" => Color::Fixed(197).normal(),
"deeppink1a" | "xterm_deeppink1a" => Color::Fixed(198).normal(),
"deeppink1b" | "xterm_deeppink1b" => Color::Fixed(199).normal(),
"magenta2b" | "xterm_magenta2b" => Color::Fixed(200).normal(),
"magenta1" | "xterm_magenta1" => Color::Fixed(201).normal(),
"orangered1" | "xterm_orangered1" => Color::Fixed(202).normal(),
"indianred1a" | "xterm_indianred1a" => Color::Fixed(203).normal(),
"indianred1b" | "xterm_indianred1b" => Color::Fixed(204).normal(),
"hotpinka" | "xterm_hotpinka" => Color::Fixed(205).normal(),
"hotpinkb" | "xterm_hotpinkb" => Color::Fixed(206).normal(),
"mediumorchid1b" | "xterm_mediumorchid1b" => Color::Fixed(207).normal(),
"darkorange" | "xterm_darkorange" => Color::Fixed(208).normal(),
"salmon1" | "xterm_salmon1" => Color::Fixed(209).normal(),
"lightcoral" | "xterm_lightcoral" => Color::Fixed(210).normal(),
"palevioletred1" | "xterm_palevioletred1" => Color::Fixed(211).normal(),
"orchid2" | "xterm_orchid2" => Color::Fixed(212).normal(),
"orchid1" | "xterm_orchid1" => Color::Fixed(213).normal(),
"orange1" | "xterm_orange1" => Color::Fixed(214).normal(),
"sandybrown" | "xterm_sandybrown" => Color::Fixed(215).normal(),
"lightsalmon1" | "xterm_lightsalmon1" => Color::Fixed(216).normal(),
"lightpink1" | "xterm_lightpink1" => Color::Fixed(217).normal(),
"pink1" | "xterm_pink1" => Color::Fixed(218).normal(),
"plum1" | "xterm_plum1" => Color::Fixed(219).normal(),
"gold1" | "xterm_gold1" => Color::Fixed(220).normal(),
"lightgoldenrod2a" | "xterm_lightgoldenrod2a" => Color::Fixed(221).normal(),
"lightgoldenrod2b" | "xterm_lightgoldenrod2b" => Color::Fixed(222).normal(),
"navajowhite1" | "xterm_navajowhite1" => Color::Fixed(223).normal(),
"mistyrose1" | "xterm_mistyrose1" => Color::Fixed(224).normal(),
"thistle1" | "xterm_thistle1" => Color::Fixed(225).normal(),
"yellow1" | "xterm_yellow1" => Color::Fixed(226).normal(),
"lightgoldenrod1" | "xterm_lightgoldenrod1" => Color::Fixed(227).normal(),
"khaki1" | "xterm_khaki1" => Color::Fixed(228).normal(),
"wheat1" | "xterm_wheat1" => Color::Fixed(229).normal(),
"cornsilk1" | "xterm_cornsilk1" => Color::Fixed(230).normal(),
"grey100" | "xterm_grey100" => Color::Fixed(231).normal(),
"grey3" | "xterm_grey3" => Color::Fixed(232).normal(),
"grey7" | "xterm_grey7" => Color::Fixed(233).normal(),
"grey11" | "xterm_grey11" => Color::Fixed(234).normal(),
"grey15" | "xterm_grey15" => Color::Fixed(235).normal(),
"grey19" | "xterm_grey19" => Color::Fixed(236).normal(),
"grey23" | "xterm_grey23" => Color::Fixed(237).normal(),
"grey27" | "xterm_grey27" => Color::Fixed(238).normal(),
"grey30" | "xterm_grey30" => Color::Fixed(239).normal(),
"grey35" | "xterm_grey35" => Color::Fixed(240).normal(),
"grey39" | "xterm_grey39" => Color::Fixed(241).normal(),
"grey42" | "xterm_grey42" => Color::Fixed(242).normal(),
"grey46" | "xterm_grey46" => Color::Fixed(243).normal(),
"grey50" | "xterm_grey50" => Color::Fixed(244).normal(),
"grey54" | "xterm_grey54" => Color::Fixed(245).normal(),
"grey58" | "xterm_grey58" => Color::Fixed(246).normal(),
"grey62" | "xterm_grey62" => Color::Fixed(247).normal(),
"grey66" | "xterm_grey66" => Color::Fixed(248).normal(),
"grey70" | "xterm_grey70" => Color::Fixed(249).normal(),
"grey74" | "xterm_grey74" => Color::Fixed(250).normal(),
"grey78" | "xterm_grey78" => Color::Fixed(251).normal(),
"grey82" | "xterm_grey82" => Color::Fixed(252).normal(),
"grey85" | "xterm_grey85" => Color::Fixed(253).normal(),
"grey89" | "xterm_grey89" => Color::Fixed(254).normal(),
"grey93" | "xterm_grey93" => Color::Fixed(255).normal(),
_ => Color::Default.normal(),
}
}
pub fn lookup_color(s: &str) -> Option<Color> {
lookup_style(s).foreground
}
fn fill_modifiers(attrs: &str, style: &mut Style) {
// setup the attributes available in nu_ansi_term::Style
//
// since we can combine styles like bold-italic, iterate through the chars
// and set the bools for later use in the nu_ansi_term::Style application
for ch in attrs.chars().map(|c| c.to_ascii_lowercase()) {
match ch {
'l' => style.is_blink = true,
'b' => style.is_bold = true,
'd' => style.is_dimmed = true,
'h' => style.is_hidden = true,
'i' => style.is_italic = true,
'r' => style.is_reverse = true,
's' => style.is_strikethrough = true,
'u' => style.is_underline = true,
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | true |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-color-config/src/lib.rs | crates/nu-color-config/src/lib.rs | #![doc = include_str!("../README.md")]
mod color_config;
mod matching_brackets_style;
mod nu_style;
mod shape_color;
mod style_computer;
mod text_style;
pub use color_config::*;
pub use matching_brackets_style::*;
pub use nu_style::*;
pub use shape_color::*;
pub use style_computer::*;
pub use text_style::*;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-color-config/src/matching_brackets_style.rs | crates/nu-color-config/src/matching_brackets_style.rs | use crate::color_config::lookup_ansi_color_style;
use nu_ansi_term::Style;
use nu_protocol::Config;
pub fn get_matching_brackets_style(default_style: Style, conf: &Config) -> Style {
const MATCHING_BRACKETS_CONFIG_KEY: &str = "shape_matching_brackets";
match conf.color_config.get(MATCHING_BRACKETS_CONFIG_KEY) {
Some(int_color) => match int_color.coerce_str() {
Ok(int_color) => merge_styles(default_style, lookup_ansi_color_style(&int_color)),
Err(_) => default_style,
},
None => default_style,
}
}
fn merge_styles(base: Style, extra: Style) -> Style {
Style {
foreground: extra.foreground.or(base.foreground),
background: extra.background.or(base.background),
is_bold: extra.is_bold || base.is_bold,
is_dimmed: extra.is_dimmed || base.is_dimmed,
is_italic: extra.is_italic || base.is_italic,
is_underline: extra.is_underline || base.is_underline,
is_blink: extra.is_blink || base.is_blink,
is_reverse: extra.is_reverse || base.is_reverse,
is_hidden: extra.is_hidden || base.is_hidden,
is_strikethrough: extra.is_strikethrough || base.is_strikethrough,
prefix_with_reset: false,
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-color-config/src/style_computer.rs | crates/nu-color-config/src/style_computer.rs | use crate::{TextStyle, color_record_to_nustyle, lookup_ansi_color_style, text_style::Alignment};
use nu_ansi_term::{Color, Style};
use nu_engine::ClosureEvalOnce;
use nu_protocol::{
Span, Value,
engine::{Closure, EngineState, Stack},
report_shell_error,
};
use std::{
collections::HashMap,
fmt::{Debug, Formatter, Result},
};
// ComputableStyle represents the valid user style types: a single color value, or a closure which
// takes an input value and produces a color value. The latter represents a value which
// is computed at use-time.
#[derive(Debug, Clone)]
pub enum ComputableStyle {
Static(Style),
Closure(Closure, Span),
}
// An alias for the mapping used internally by StyleComputer.
pub type StyleMapping = HashMap<String, ComputableStyle>;
//
// A StyleComputer is an all-in-one way to compute styles. A nu command can
// simply create it with from_config(), and then use it with compute().
// It stores the engine state and stack needed to run closures that
// may be defined as a user style.
//
pub struct StyleComputer<'a> {
engine_state: &'a EngineState,
stack: &'a Stack,
map: StyleMapping,
}
impl<'a> StyleComputer<'a> {
// This is NOT meant to be used in most cases - please use from_config() instead.
// This only exists for testing purposes.
pub fn new(
engine_state: &'a EngineState,
stack: &'a Stack,
map: StyleMapping,
) -> StyleComputer<'a> {
StyleComputer {
engine_state,
stack,
map,
}
}
// The main method. Takes a string name which maps to a color_config style name,
// and a Nu value to pipe into any closures that may have been defined there.
pub fn compute(&self, style_name: &str, value: &Value) -> Style {
match self.map.get(style_name) {
// Static values require no computation.
Some(ComputableStyle::Static(s)) => *s,
// Closures are run here.
Some(ComputableStyle::Closure(closure, span)) => {
let result = ClosureEvalOnce::new(self.engine_state, self.stack, closure.clone())
.debug(false)
.run_with_value(value.clone())
.and_then(|data| data.into_value(*span));
match result {
Ok(value) => {
// These should be the same color data forms supported by color_config.
match value {
Value::Record { .. } => color_record_to_nustyle(&value),
Value::String { val, .. } => lookup_ansi_color_style(&val),
_ => Style::default(),
}
}
Err(err) => {
report_shell_error(Some(self.stack), self.engine_state, &err);
Style::default()
}
}
}
// There should be no other kinds of values (due to create_map() in config.rs filtering them out)
// so this is just a fallback.
_ => Style::default(),
}
}
// Used only by the `table` command.
pub fn style_primitive(&self, value: &Value) -> TextStyle {
use Alignment::*;
let s = self.compute(&value.get_type().get_non_specified_string(), value);
match *value {
Value::Bool { .. } => TextStyle::with_style(Left, s),
Value::Int { .. } => TextStyle::with_style(Right, s),
Value::Filesize { .. } => TextStyle::with_style(Right, s),
Value::Duration { .. } => TextStyle::with_style(Right, s),
Value::Date { .. } => TextStyle::with_style(Left, s),
Value::Range { .. } => TextStyle::with_style(Left, s),
Value::Float { .. } => TextStyle::with_style(Right, s),
Value::String { .. } => TextStyle::with_style(Left, s),
Value::Glob { .. } => TextStyle::with_style(Left, s),
Value::Nothing { .. } => TextStyle::with_style(Left, s),
Value::Binary { .. } => TextStyle::with_style(Left, s),
Value::CellPath { .. } => TextStyle::with_style(Left, s),
Value::Record { .. } | Value::List { .. } => TextStyle::with_style(Left, s),
Value::Closure { .. } | Value::Custom { .. } | Value::Error { .. } => {
TextStyle::basic_left()
}
}
}
// The main constructor.
pub fn from_config(engine_state: &'a EngineState, stack: &'a Stack) -> StyleComputer<'a> {
let config = stack.get_config(engine_state);
// Create the hashmap
#[rustfmt::skip]
let mut map: StyleMapping = [
("separator".to_string(), ComputableStyle::Static(Color::Default.normal())),
("leading_trailing_space_bg".to_string(), ComputableStyle::Static(Style::default().on(Color::Rgb(128, 128, 128)))),
("header".to_string(), ComputableStyle::Static(Color::Green.bold())),
("empty".to_string(), ComputableStyle::Static(Color::Blue.normal())),
("bool".to_string(), ComputableStyle::Static(Color::LightCyan.normal())),
("int".to_string(), ComputableStyle::Static(Color::Default.normal())),
("filesize".to_string(), ComputableStyle::Static(Color::Cyan.normal())),
("duration".to_string(), ComputableStyle::Static(Color::Default.normal())),
("datetime".to_string(), ComputableStyle::Static(Color::Purple.normal())),
("range".to_string(), ComputableStyle::Static(Color::Default.normal())),
("float".to_string(), ComputableStyle::Static(Color::Default.normal())),
("string".to_string(), ComputableStyle::Static(Color::Default.normal())),
("nothing".to_string(), ComputableStyle::Static(Color::Default.normal())),
("binary".to_string(), ComputableStyle::Static(Color::Default.normal())),
("cell-path".to_string(), ComputableStyle::Static(Color::Default.normal())),
("row_index".to_string(), ComputableStyle::Static(Color::Green.bold())),
("record".to_string(), ComputableStyle::Static(Color::Default.normal())),
("list".to_string(), ComputableStyle::Static(Color::Default.normal())),
("block".to_string(), ComputableStyle::Static(Color::Default.normal())),
("hints".to_string(), ComputableStyle::Static(Color::DarkGray.normal())),
("search_result".to_string(), ComputableStyle::Static(Color::Default.normal().on(Color::Red))),
].into_iter().collect();
for (key, value) in &config.color_config {
let span = value.span();
match value {
Value::Closure { val, .. } => {
map.insert(
key.to_string(),
ComputableStyle::Closure(*val.clone(), span),
);
}
Value::Record { .. } => {
map.insert(
key.to_string(),
ComputableStyle::Static(color_record_to_nustyle(value)),
);
}
Value::String { val, .. } => {
// update the stylemap with the found key
let color = lookup_ansi_color_style(val.as_str());
if let Some(v) = map.get_mut(key) {
*v = ComputableStyle::Static(color);
} else {
map.insert(key.to_string(), ComputableStyle::Static(color));
}
}
// This should never occur.
_ => (),
}
}
StyleComputer::new(engine_state, stack, map)
}
}
// Because EngineState doesn't have Debug (Dec 2022),
// this incomplete representation must be used.
impl Debug for StyleComputer<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
f.debug_struct("StyleComputer")
.field("map", &self.map)
.finish()
}
}
#[test]
fn test_computable_style_static() {
use nu_protocol::Span;
let style1 = Style::default().italic();
let style2 = Style::default().underline();
// Create a "dummy" style_computer for this test.
let dummy_engine_state = EngineState::new();
let dummy_stack = Stack::new();
let style_computer = StyleComputer::new(
&dummy_engine_state,
&dummy_stack,
[
("string".into(), ComputableStyle::Static(style1)),
("row_index".into(), ComputableStyle::Static(style2)),
]
.into_iter()
.collect(),
);
assert_eq!(
style_computer.compute("string", &Value::nothing(Span::unknown())),
style1
);
assert_eq!(
style_computer.compute("row_index", &Value::nothing(Span::unknown())),
style2
);
}
// Because each closure currently runs in a separate environment, checks that the closures have run
// must use the filesystem.
#[test]
fn test_computable_style_closure_basic() {
use nu_test_support::{nu, nu_repl_code, playground::Playground};
Playground::setup("computable_style_closure_basic", |dirs, _| {
let inp = [
r#"$env.config = {
color_config: {
string: {|e| touch ($e + '.obj'); 'red' }
}
};"#,
"[bell book candle] | table | ignore",
"ls | get name | to nuon",
];
let actual_repl = nu!(cwd: dirs.test(), nu_repl_code(&inp));
assert_eq!(actual_repl.err, "");
assert_eq!(actual_repl.out, r#"["bell.obj", "book.obj", "candle.obj"]"#);
});
}
#[test]
fn test_computable_style_closure_errors() {
use nu_test_support::{nu, nu_repl_code};
let inp = [
r#"$env.config = {
color_config: {
string: {|e| $e + 2 }
}
};"#,
"[bell] | table",
];
let actual_repl = nu!(nu_repl_code(&inp));
// Check that the error was printed
assert!(
actual_repl
.err
.contains("nu::shell::operator_incompatible_types")
);
// Check that the value was printed
assert!(actual_repl.out.contains("bell"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-color-config/src/text_style.rs | crates/nu-color-config/src/text_style.rs | use nu_ansi_term::{Color, Style};
#[derive(Debug, Clone, Copy)]
pub enum Alignment {
Center,
Left,
Right,
}
#[derive(Debug, Clone, Copy)]
pub struct TextStyle {
pub alignment: Alignment,
pub color_style: Option<Style>,
}
impl TextStyle {
pub fn new() -> TextStyle {
TextStyle {
alignment: Alignment::Left,
color_style: Some(Style::default()),
}
}
pub fn bold(&self, bool_value: Option<bool>) -> TextStyle {
let bv = bool_value.unwrap_or(false);
TextStyle {
alignment: self.alignment,
color_style: Some(Style {
is_bold: bv,
..self.color_style.unwrap_or_default()
}),
}
}
pub fn is_bold(&self) -> bool {
self.color_style.unwrap_or_default().is_bold
}
pub fn dimmed(&self) -> TextStyle {
TextStyle {
alignment: self.alignment,
color_style: Some(Style {
is_dimmed: true,
..self.color_style.unwrap_or_default()
}),
}
}
pub fn is_dimmed(&self) -> bool {
self.color_style.unwrap_or_default().is_dimmed
}
pub fn italic(&self) -> TextStyle {
TextStyle {
alignment: self.alignment,
color_style: Some(Style {
is_italic: true,
..self.color_style.unwrap_or_default()
}),
}
}
pub fn is_italic(&self) -> bool {
self.color_style.unwrap_or_default().is_italic
}
pub fn underline(&self) -> TextStyle {
TextStyle {
alignment: self.alignment,
color_style: Some(Style {
is_underline: true,
..self.color_style.unwrap_or_default()
}),
}
}
pub fn is_underline(&self) -> bool {
self.color_style.unwrap_or_default().is_underline
}
pub fn blink(&self) -> TextStyle {
TextStyle {
alignment: self.alignment,
color_style: Some(Style {
is_blink: true,
..self.color_style.unwrap_or_default()
}),
}
}
pub fn is_blink(&self) -> bool {
self.color_style.unwrap_or_default().is_blink
}
pub fn reverse(&self) -> TextStyle {
TextStyle {
alignment: self.alignment,
color_style: Some(Style {
is_reverse: true,
..self.color_style.unwrap_or_default()
}),
}
}
pub fn is_reverse(&self) -> bool {
self.color_style.unwrap_or_default().is_reverse
}
pub fn hidden(&self) -> TextStyle {
TextStyle {
alignment: self.alignment,
color_style: Some(Style {
is_hidden: true,
..self.color_style.unwrap_or_default()
}),
}
}
pub fn is_hidden(&self) -> bool {
self.color_style.unwrap_or_default().is_hidden
}
pub fn strikethrough(&self) -> TextStyle {
TextStyle {
alignment: self.alignment,
color_style: Some(Style {
is_strikethrough: true,
..self.color_style.unwrap_or_default()
}),
}
}
pub fn is_strikethrough(&self) -> bool {
self.color_style.unwrap_or_default().is_strikethrough
}
pub fn fg(&self, foreground: Color) -> TextStyle {
TextStyle {
alignment: self.alignment,
color_style: Some(Style {
foreground: Some(foreground),
..self.color_style.unwrap_or_default()
}),
}
}
pub fn on(&self, background: Color) -> TextStyle {
TextStyle {
alignment: self.alignment,
color_style: Some(Style {
background: Some(background),
..self.color_style.unwrap_or_default()
}),
}
}
pub fn bg(&self, background: Color) -> TextStyle {
TextStyle {
alignment: self.alignment,
color_style: Some(Style {
background: Some(background),
..self.color_style.unwrap_or_default()
}),
}
}
pub fn alignment(&self, align: Alignment) -> TextStyle {
TextStyle {
alignment: align,
color_style: self.color_style,
}
}
pub fn style(&self, style: Style) -> TextStyle {
TextStyle {
alignment: self.alignment,
color_style: Some(Style {
foreground: style.foreground,
background: style.background,
is_bold: style.is_bold,
is_dimmed: style.is_dimmed,
is_italic: style.is_italic,
is_underline: style.is_underline,
is_blink: style.is_blink,
is_reverse: style.is_reverse,
is_hidden: style.is_hidden,
is_strikethrough: style.is_strikethrough,
prefix_with_reset: false,
}),
}
}
pub fn basic_center() -> TextStyle {
TextStyle::new()
.alignment(Alignment::Center)
.style(Style::default())
}
pub fn basic_right() -> TextStyle {
TextStyle::new()
.alignment(Alignment::Right)
.style(Style::default())
}
pub fn basic_left() -> TextStyle {
TextStyle::new()
.alignment(Alignment::Left)
.style(Style::default())
}
pub fn default_header() -> TextStyle {
TextStyle::new()
.alignment(Alignment::Center)
.fg(Color::Green)
.bold(Some(true))
}
pub fn default_field() -> TextStyle {
TextStyle::new().fg(Color::Green).bold(Some(true))
}
pub fn with_attributes(bo: bool, al: Alignment, co: Color) -> TextStyle {
TextStyle::new().alignment(al).fg(co).bold(Some(bo))
}
pub fn with_style(al: Alignment, style: Style) -> TextStyle {
TextStyle::new().alignment(al).style(Style {
foreground: style.foreground,
background: style.background,
is_bold: style.is_bold,
is_dimmed: style.is_dimmed,
is_italic: style.is_italic,
is_underline: style.is_underline,
is_blink: style.is_blink,
is_reverse: style.is_reverse,
is_hidden: style.is_hidden,
is_strikethrough: style.is_strikethrough,
prefix_with_reset: false,
})
}
}
impl Default for TextStyle {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
use nu_ansi_term::Style;
#[test]
fn test_is_bold() {
let text_style = TextStyle {
alignment: Alignment::Left,
color_style: Some(Style {
is_bold: true,
..Default::default()
}),
};
assert!(text_style.is_bold());
}
#[test]
fn test_dimmed() {
let text_style = TextStyle {
alignment: Alignment::Left,
color_style: Some(Style {
..Default::default()
}),
};
let dimmed_style = text_style.dimmed();
assert!(dimmed_style.is_dimmed());
}
#[test]
fn test_is_dimmed() {
let text_style = TextStyle {
alignment: Alignment::Left,
color_style: Some(Style {
is_dimmed: true,
..Default::default()
}),
};
assert!(text_style.is_dimmed());
}
#[test]
fn test_italic() {
let text_style = TextStyle {
alignment: Alignment::Left,
color_style: Some(Style {
..Default::default()
}),
};
let italic_style = text_style.italic();
assert!(italic_style.is_italic());
}
#[test]
fn test_is_italic() {
let text_style = TextStyle {
alignment: Alignment::Left,
color_style: Some(Style {
is_italic: true,
..Default::default()
}),
};
assert!(text_style.is_italic());
}
#[test]
fn test_underline() {
let text_style = TextStyle {
alignment: Alignment::Left,
color_style: Some(Style {
..Default::default()
}),
};
let underline_style = text_style.underline();
assert!(underline_style.is_underline());
}
#[test]
fn test_is_underline() {
let text_style = TextStyle {
alignment: Alignment::Left,
color_style: Some(Style {
is_underline: true,
..Default::default()
}),
};
assert!(text_style.is_underline());
}
#[test]
fn test_blink() {
let text_style = TextStyle {
alignment: Alignment::Left,
color_style: Some(Style {
..Default::default()
}),
};
let blink_style = text_style.blink();
assert!(blink_style.is_blink());
}
#[test]
fn test_is_blink() {
let text_style = TextStyle {
alignment: Alignment::Left,
color_style: Some(Style {
is_blink: true,
..Default::default()
}),
};
assert!(text_style.is_blink());
}
#[test]
fn test_reverse() {
let text_style = TextStyle {
alignment: Alignment::Left,
color_style: Some(Style {
..Default::default()
}),
};
let reverse_style = text_style.reverse();
assert!(reverse_style.is_reverse());
}
#[test]
fn test_is_reverse() {
let text_style = TextStyle {
alignment: Alignment::Left,
color_style: Some(Style {
is_reverse: true,
..Default::default()
}),
};
assert!(text_style.is_reverse());
}
#[test]
fn test_hidden() {
let text_style = TextStyle {
alignment: Alignment::Left,
color_style: Some(Style {
..Default::default()
}),
};
let hidden_style = text_style.hidden();
assert!(hidden_style.is_hidden());
}
#[test]
fn test_is_hidden() {
let text_style = TextStyle {
alignment: Alignment::Left,
color_style: Some(Style {
is_hidden: true,
..Default::default()
}),
};
assert!(text_style.is_hidden());
}
#[test]
fn test_strikethrough() {
let text_style = TextStyle {
alignment: Alignment::Left,
color_style: Some(Style {
..Default::default()
}),
};
let strikethrough_style = text_style.strikethrough();
assert!(strikethrough_style.is_strikethrough());
}
#[test]
fn test_is_strikethrough() {
let text_style = TextStyle {
alignment: Alignment::Left,
color_style: Some(Style {
is_strikethrough: true,
..Default::default()
}),
};
assert!(text_style.is_strikethrough());
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-color-config/src/shape_color.rs | crates/nu-color-config/src/shape_color.rs | use crate::{color_config::lookup_ansi_color_style, color_record_to_nustyle};
use nu_ansi_term::{Color, Style};
use nu_protocol::{Config, Value};
// The default colors for shapes, used when there is no config for them.
pub fn default_shape_color(shape: &str) -> Style {
match shape {
"shape_binary" => Style::new().fg(Color::Purple).bold(),
"shape_block" => Style::new().fg(Color::Blue).bold(),
"shape_bool" => Style::new().fg(Color::LightCyan),
"shape_closure" => Style::new().fg(Color::Green).bold(),
"shape_custom" => Style::new().fg(Color::Green),
"shape_datetime" => Style::new().fg(Color::Cyan).bold(),
"shape_directory" => Style::new().fg(Color::Cyan),
"shape_external" => Style::new().fg(Color::Cyan),
"shape_externalarg" => Style::new().fg(Color::Green).bold(),
"shape_external_resolved" => Style::new().fg(Color::LightYellow).bold(),
"shape_filepath" => Style::new().fg(Color::Cyan),
"shape_flag" => Style::new().fg(Color::Blue).bold(),
"shape_float" => Style::new().fg(Color::Purple).bold(),
"shape_garbage" => Style::new().fg(Color::Default).on(Color::Red).bold(),
"shape_glob_interpolation" => Style::new().fg(Color::Cyan).bold(),
"shape_globpattern" => Style::new().fg(Color::Cyan).bold(),
"shape_int" => Style::new().fg(Color::Purple).bold(),
"shape_internalcall" => Style::new().fg(Color::Cyan).bold(),
"shape_keyword" => Style::new().fg(Color::Cyan).bold(),
"shape_list" => Style::new().fg(Color::Cyan).bold(),
"shape_literal" => Style::new().fg(Color::Blue),
"shape_match_pattern" => Style::new().fg(Color::Green),
"shape_nothing" => Style::new().fg(Color::LightCyan),
"shape_operator" => Style::new().fg(Color::Yellow),
"shape_pipe" => Style::new().fg(Color::Purple).bold(),
"shape_range" => Style::new().fg(Color::Yellow).bold(),
"shape_raw_string" => Style::new().fg(Color::LightMagenta).bold(),
"shape_record" => Style::new().fg(Color::Cyan).bold(),
"shape_redirection" => Style::new().fg(Color::Purple).bold(),
"shape_signature" => Style::new().fg(Color::Green).bold(),
"shape_string" => Style::new().fg(Color::Green),
"shape_string_interpolation" => Style::new().fg(Color::Cyan).bold(),
"shape_table" => Style::new().fg(Color::Blue).bold(),
"shape_variable" => Style::new().fg(Color::Purple),
"shape_vardecl" => Style::new().fg(Color::Purple),
_ => Style::default(),
}
}
pub fn get_shape_color(shape: &str, conf: &Config) -> Style {
match conf.color_config.get(shape) {
Some(int_color) => {
// Shapes do not use color_config closures, currently.
match int_color {
Value::Record { .. } => color_record_to_nustyle(int_color),
Value::String { val, .. } => lookup_ansi_color_style(val),
// Defer to the default in the event of incorrect types being given
// (i.e. treat null, etc. as the value being unset)
_ => default_shape_color(shape),
}
}
None => default_shape_color(shape),
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-pretty-hex/src/lib.rs | crates/nu-pretty-hex/src/lib.rs | //! A Rust library providing pretty hex dump.
//!
//! A `simple_hex()` way renders one-line hex dump, and a `pretty_hex()` way renders
//! columned multi-line hex dump with addressing and ASCII representation.
//! A `config_hex()` way renders hex dump in specified format.
//!
//! ## Example of `simple_hex()`
//! ```
//! use nu_pretty_hex::*;
//!
//! let v = vec![222, 173, 190, 239, 202, 254, 32, 24];
//! # #[cfg(feature = "alloc")]
//! assert_eq!(simple_hex(&v), format!("{}", v.hex_dump()));
//!
//! println!("{}", v.hex_dump());
//! ```
//! Output:
//!
//! ```text
//! de ad be ef ca fe 20 18
//! ```
//! ## Example of `pretty_hex()`
//! ```
//! use nu_pretty_hex::*;
//!
//! let v = &include_bytes!("../tests/data");
//! # #[cfg(feature = "alloc")]
//! assert_eq!(pretty_hex(&v), format!("{:?}", v.hex_dump()));
//!
//! println!("{:?}", v.hex_dump());
//! ```
//! Output:
//!
//! ```text
//! Length: 30 (0x1e) bytes
//! 0000: 6b 4e 1a c3 af 03 d2 1e 7e 73 ba c8 bd 84 0f 83 kN......~s......
//! 0010: 89 d5 cf 90 23 67 4b 48 db b1 bc 35 bf ee ....#gKH...5..
//! ```
//! ## Example of `config_hex()`
//! ```
//! use nu_pretty_hex::*;
//!
//! let cfg = HexConfig {title: false, width: 8, group: 0, ..HexConfig::default() };
//!
//! let v = &include_bytes!("../tests/data");
//! # #[cfg(feature = "alloc")]
//! assert_eq!(config_hex(&v, cfg), format!("{:?}", v.hex_conf(cfg)));
//!
//! println!("{:?}", v.hex_conf(cfg));
//! ```
//! Output:
//!
//! ```text
//! 0000: 6b 4e 1a c3 af 03 d2 1e kN......
//! 0008: 7e 73 ba c8 bd 84 0f 83 ~s......
//! 0010: 89 d5 cf 90 23 67 4b 48 ....#gKH
//! 0018: db b1 bc 35 bf ee ...5..
//! ```
mod pretty_hex;
pub use pretty_hex::*;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-pretty-hex/src/pretty_hex.rs | crates/nu-pretty-hex/src/pretty_hex.rs | use core::fmt;
use nu_ansi_term::{Color, Style};
/// Returns a one-line hexdump of `source` grouped in default format without header
/// and ASCII column.
pub fn simple_hex<T: AsRef<[u8]>>(source: &T) -> String {
let mut writer = String::new();
hex_write(&mut writer, source, HexConfig::simple(), None).unwrap_or(());
writer
}
/// Dump `source` as hex octets in default format without header and ASCII column to the `writer`.
pub fn simple_hex_write<T, W>(writer: &mut W, source: &T) -> fmt::Result
where
T: AsRef<[u8]>,
W: fmt::Write,
{
hex_write(writer, source, HexConfig::simple(), None)
}
/// Return a multi-line hexdump in default format complete with addressing, hex digits,
/// and ASCII representation.
pub fn pretty_hex<T: AsRef<[u8]>>(source: &T) -> String {
let mut writer = String::new();
hex_write(&mut writer, source, HexConfig::default(), Some(true)).unwrap_or(());
writer
}
/// Write multi-line hexdump in default format complete with addressing, hex digits,
/// and ASCII representation to the writer.
pub fn pretty_hex_write<T, W>(writer: &mut W, source: &T) -> fmt::Result
where
T: AsRef<[u8]>,
W: fmt::Write,
{
hex_write(writer, source, HexConfig::default(), Some(true))
}
/// Return a hexdump of `source` in specified format.
pub fn config_hex<T: AsRef<[u8]>>(source: &T, cfg: HexConfig) -> String {
let mut writer = String::new();
hex_write(&mut writer, source, cfg, Some(true)).unwrap_or(());
writer
}
/// Configuration parameters for hexdump.
#[derive(Clone, Copy, Debug)]
pub struct HexConfig {
/// Write first line header with data length.
pub title: bool,
/// Append ASCII representation column.
pub ascii: bool,
/// Source bytes per row. 0 for single row without address prefix.
pub width: usize,
/// Chunks count per group. 0 for single group (column).
pub group: usize,
/// Source bytes per chunk (word). 0 for single word.
pub chunk: usize,
/// Offset to start counting addresses from
pub address_offset: usize,
/// Bytes from 0 to skip
pub skip: Option<usize>,
/// Length to return
pub length: Option<usize>,
}
/// Default configuration with `title`, `ascii`, 16 source bytes `width` grouped to 4 separate
/// hex bytes. Using in `pretty_hex`, `pretty_hex_write` and `fmt::Debug` implementation.
impl Default for HexConfig {
fn default() -> HexConfig {
HexConfig {
title: true,
ascii: true,
width: 16,
group: 4,
chunk: 1,
address_offset: 0,
skip: None,
length: None,
}
}
}
impl HexConfig {
/// Returns configuration for `simple_hex`, `simple_hex_write` and `fmt::Display` implementation.
pub fn simple() -> Self {
HexConfig::default().to_simple()
}
fn delimiter(&self, i: usize) -> &'static str {
if i > 0 && self.chunk > 0 && i.is_multiple_of(self.chunk) {
if self.group > 0 && i.is_multiple_of(self.group * self.chunk) {
" "
} else {
" "
}
} else {
""
}
}
fn to_simple(self) -> Self {
HexConfig {
title: false,
ascii: false,
width: 0,
..self
}
}
}
pub fn categorize_byte(byte: &u8) -> (Style, Option<char>) {
// This section is here so later we can configure these items
let null_char_style = Style::default().fg(Color::Fixed(242));
let null_char = Some('0');
let ascii_printable_style = Style::default().fg(Color::Cyan).bold();
let ascii_printable = None;
let ascii_space_style = Style::default().fg(Color::Green).bold();
let ascii_space = Some(' ');
let ascii_white_space_style = Style::default().fg(Color::Green).bold();
let ascii_white_space = Some('_');
let ascii_other_style = Style::default().fg(Color::Purple).bold();
let ascii_other = Some('•');
let non_ascii_style = Style::default().fg(Color::Yellow).bold();
let non_ascii = Some('×'); // or Some('.')
if byte == &0 {
(null_char_style, null_char)
} else if byte.is_ascii_graphic() {
(ascii_printable_style, ascii_printable)
} else if byte.is_ascii_whitespace() {
// 0x20 == 32 decimal - replace with a real space
if byte == &32 {
(ascii_space_style, ascii_space)
} else {
(ascii_white_space_style, ascii_white_space)
}
} else if byte.is_ascii() {
(ascii_other_style, ascii_other)
} else {
(non_ascii_style, non_ascii)
}
}
/// Write hex dump in specified format.
pub fn hex_write<T, W>(
writer: &mut W,
source: &T,
cfg: HexConfig,
with_color: Option<bool>,
) -> fmt::Result
where
T: AsRef<[u8]>,
W: fmt::Write,
{
let use_color = with_color.unwrap_or(false);
if source.as_ref().is_empty() {
return Ok(());
}
let amount = cfg.length.unwrap_or_else(|| source.as_ref().len());
let skip = cfg.skip.unwrap_or(0);
let address_offset = cfg.address_offset;
let source_part_vec: Vec<u8> = source
.as_ref()
.iter()
.skip(skip)
.take(amount)
.copied()
.collect();
if cfg.title {
write_title(
writer,
HexConfig {
length: Some(source_part_vec.len()),
..cfg
},
use_color,
)?;
}
let lines = source_part_vec.chunks(if cfg.width > 0 {
cfg.width
} else {
source_part_vec.len()
});
let lines_len = lines.len();
for (i, row) in lines.enumerate() {
if cfg.width > 0 {
let style = Style::default().fg(Color::Cyan);
if use_color {
write!(
writer,
"{}{:08x}{}: ",
style.prefix(),
i * cfg.width + skip + address_offset,
style.suffix()
)?;
} else {
write!(writer, "{:08x}: ", i * cfg.width + skip + address_offset,)?;
}
}
for (i, x) in row.as_ref().iter().enumerate() {
if use_color {
let (style, _char) = categorize_byte(x);
write!(
writer,
"{}{}{:02x}{}",
cfg.delimiter(i),
style.prefix(),
x,
style.suffix()
)?;
} else {
write!(writer, "{}{:02x}", cfg.delimiter(i), x,)?;
}
}
if cfg.ascii {
for j in row.len()..cfg.width {
write!(writer, "{} ", cfg.delimiter(j))?;
}
write!(writer, " ")?;
for x in row {
let (style, a_char) = categorize_byte(x);
let replacement_char = a_char.unwrap_or(*x as char);
if use_color {
write!(
writer,
"{}{}{}",
style.prefix(),
replacement_char,
style.suffix()
)?;
} else {
write!(writer, "{replacement_char}",)?;
}
}
}
if i + 1 < lines_len {
writeln!(writer)?;
}
}
Ok(())
}
/// Write the title for the given config. The length will be taken from `cfg.length`.
pub fn write_title<W>(writer: &mut W, cfg: HexConfig, use_color: bool) -> Result<(), fmt::Error>
where
W: fmt::Write,
{
let write = |writer: &mut W, length: fmt::Arguments<'_>| {
if use_color {
writeln!(
writer,
"Length: {length} | {0}printable {1}whitespace {2}ascii_other {3}non_ascii{4}",
Style::default().fg(Color::Cyan).bold().prefix(),
Style::default().fg(Color::Green).bold().prefix(),
Style::default().fg(Color::Purple).bold().prefix(),
Style::default().fg(Color::Yellow).bold().prefix(),
Style::default().fg(Color::Yellow).suffix()
)
} else {
writeln!(writer, "Length: {length}")
}
};
if let Some(len) = cfg.length {
write(writer, format_args!("{len} (0x{len:x}) bytes"))
} else {
write(writer, format_args!("unknown (stream)"))
}
}
/// Reference wrapper for use in arguments formatting.
pub struct Hex<'a, T: 'a>(&'a T, HexConfig);
impl<'a, T: 'a + AsRef<[u8]>> fmt::Display for Hex<'a, T> {
/// Formats the value by `simple_hex_write` using the given formatter.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
hex_write(f, self.0, self.1.to_simple(), None)
}
}
impl<'a, T: 'a + AsRef<[u8]>> fmt::Debug for Hex<'a, T> {
/// Formats the value by `pretty_hex_write` using the given formatter.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
hex_write(f, self.0, self.1, None)
}
}
/// Allows generates hex dumps to a formatter.
pub trait PrettyHex: Sized {
/// Wrap self reference for use in `std::fmt::Display` and `std::fmt::Debug`
/// formatting as hex dumps.
fn hex_dump(&self) -> Hex<'_, Self>;
/// Wrap self reference for use in `std::fmt::Display` and `std::fmt::Debug`
/// formatting as hex dumps in specified format.
fn hex_conf(&self, cfg: HexConfig) -> Hex<'_, Self>;
}
impl<T> PrettyHex for T
where
T: AsRef<[u8]>,
{
fn hex_dump(&self) -> Hex<'_, Self> {
Hex(self, HexConfig::default())
}
fn hex_conf(&self, cfg: HexConfig) -> Hex<'_, Self> {
Hex(self, cfg)
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-pretty-hex/tests/tests.rs | crates/nu-pretty-hex/tests/tests.rs | use nu_pretty_hex::*;
// #[test]
// fn test_simple() {
// let bytes: Vec<u8> = (0..16).collect();
// let expected = "00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f";
// assert_eq!(expected, simple_hex(&bytes));
// assert_eq!(expected, bytes.hex_dump().to_string());
// assert_eq!(simple_hex(&bytes), config_hex(&bytes, HexConfig::simple()));
//
// let mut have = String::new();
// simple_hex_write(&mut have, &bytes).unwrap();
// assert_eq!(expected, have);
//
// let str = "string";
// let string: String = String::from("string");
// let slice: &[u8] = &[0x73, 0x74, 0x72, 0x69, 0x6e, 0x67];
// assert_eq!(simple_hex(&str), "73 74 72 69 6e 67");
// assert_eq!(simple_hex(&str), simple_hex(&string));
// assert_eq!(simple_hex(&str), simple_hex(&slice));
//
// assert!(simple_hex(&vec![]).is_empty());
// }
//
// #[test]
// fn test_pretty() {
// let bytes: Vec<u8> = (0..256).map(|x| x as u8).collect();
// let want = include_str!("256.txt");
//
// let mut hex = String::new();
// pretty_hex_write(&mut hex, &bytes).unwrap();
// assert_eq!(want, hex);
// assert_eq!(want, format!("{:?}", bytes.hex_dump()));
// assert_eq!(want, pretty_hex(&bytes));
// assert_eq!(want, config_hex(&bytes, HexConfig::default()));
//
// assert_eq!("Length: 0 (0x0) bytes\n", pretty_hex(&vec![]));
// }
//
// #[test]
// fn test_config() {
// let cfg = HexConfig {
// title: false,
// ascii: false,
// width: 0,
// group: 0,
// chunk: 0,
// };
// assert!(config_hex(&vec![], cfg).is_empty());
// assert_eq!("2425262728", config_hex(&"$%&'(", cfg));
//
// let v = include_bytes!("data");
// let cfg = HexConfig {
// title: false,
// group: 8,
// ..HexConfig::default()
// };
// let hex = "0000: 6b 4e 1a c3 af 03 d2 1e 7e 73 ba c8 bd 84 0f 83 kN......~s......\n\
// 0010: 89 d5 cf 90 23 67 4b 48 db b1 bc 35 bf ee ....#gKH...5..";
// assert_eq!(hex, config_hex(&v, cfg));
// assert_eq!(hex, format!("{:?}", v.hex_conf(cfg)));
// let mut str = String::new();
// hex_write(&mut str, v, cfg).unwrap();
// assert_eq!(hex, str);
//
// assert_eq!(
// config_hex(
// &v,
// HexConfig {
// ascii: false,
// ..cfg
// }
// ),
// "0000: 6b 4e 1a c3 af 03 d2 1e 7e 73 ba c8 bd 84 0f 83\n\
// 0010: 89 d5 cf 90 23 67 4b 48 db b1 bc 35 bf ee"
// );
//
// assert_eq!(
// config_hex(
// &v,
// HexConfig {
// ascii: false,
// group: 4,
// chunk: 2,
// ..cfg
// }
// ),
// "0000: 6b4e 1ac3 af03 d21e 7e73 bac8 bd84 0f83\n\
// 0010: 89d5 cf90 2367 4b48 dbb1 bc35 bfee"
// );
//
// let v: Vec<u8> = (0..21).collect();
// let want = r##"Length: 21 (0x15) bytes
// 0000: 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f ................
// 0010: 10 11 12 13 14 ....."##;
// assert_eq!(want, pretty_hex(&v));
//
// let v: Vec<u8> = (0..13).collect();
// assert_eq!(
// config_hex(
// &v,
// HexConfig {
// title: false,
// ascii: true,
// width: 11,
// group: 2,
// chunk: 3
// }
// ),
// "0000: 000102 030405 060708 090a ...........\n\
// 000b: 0b0c .."
// );
//
// let v: Vec<u8> = (0..19).collect();
// assert_eq!(
// config_hex(
// &v,
// HexConfig {
// title: false,
// ascii: true,
// width: 16,
// group: 3,
// chunk: 3
// }
// ),
// "0000: 000102 030405 060708 090a0b 0c0d0e 0f ................\n\
// 0010: 101112 ..."
// );
//
// let cfg = HexConfig {
// title: false,
// group: 0,
// ..HexConfig::default()
// };
// assert_eq!(
// format!("{:?}", v.hex_conf(cfg)),
// "0000: 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f ................\n\
// 0010: 10 11 12 ..."
// );
// assert_eq!(
// v.hex_conf(cfg).to_string(),
// "00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12"
// );
// }
// This test case checks that hex_write works even without the alloc crate.
// Decorators to this function like simple_hex_write or PrettyHex::hex_dump()
// will be tested when the alloc feature is selected because it feels quite
// cumbersome to set up these tests without the commodity from `alloc`.
#[test]
fn test_hex_write_with_simple_config() {
let config = HexConfig::simple();
let bytes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
let expected =
core::str::from_utf8(b"00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f").unwrap();
// let expected =
// "\u{1b}[38;5;242m00\u{1b}[0m \u{1b}[1;35m01\u{1b}[0m \u{1b}[1;35m02\u{1b}[0m \u{1b}[1;";
let mut buffer = heapless::Vec::<u8, 50>::new();
hex_write(&mut buffer, &bytes, config, None).unwrap();
let have = core::str::from_utf8(&buffer).unwrap();
assert_eq!(expected, have);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-pretty-hex/examples/hex_demo.rs | crates/nu-pretty-hex/examples/hex_demo.rs | use nu_pretty_hex::*;
fn main() {
let config = HexConfig {
title: true,
ascii: true,
width: 16,
group: 4,
chunk: 1,
address_offset: 0,
skip: Some(10),
// length: Some(5),
// length: None,
length: Some(50),
};
let my_string = "Darren Schroeder 😉";
println!("ConfigHex\n{}\n", config_hex(&my_string, config));
println!("SimpleHex\n{}\n", simple_hex(&my_string));
println!("PrettyHex\n{}\n", pretty_hex(&my_string));
println!("ConfigHex\n{}\n", config_hex(&my_string, config));
// let mut my_str = String::new();
// for x in 0..256 {
// my_str.push(x as u8);
// }
let mut v: Vec<u8> = vec![];
for x in 0..=127 {
v.push(x);
}
let my_str = String::from_utf8_lossy(&v[..]);
println!("First128\n{}\n", pretty_hex(&my_str.as_bytes()));
println!(
"First128-Param\n{}\n",
config_hex(&my_str.as_bytes(), config)
);
let mut r_str = String::new();
for _ in 0..=127 {
r_str.push(rand::random::<u8>() as char);
}
println!("Random127\n{}\n", pretty_hex(&r_str));
}
//chunk 0 44617272656e20536368726f65646572 Darren Schroeder
//chunk 1 44 61 72 72 65 6e 20 53 63 68 72 6f 65 64 65 72 Darren Schroeder
//chunk 2 461 7272 656e 2053 6368 726f 6564 6572 Darren Schroeder
//chunk 3 46172 72656e 205363 68726f 656465 72 Darren Schroeder
//chunk 4 44617272 656e2053 6368726f 65646572 Darren Schroeder
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-test-support/src/locale_override.rs | crates/nu-test-support/src/locale_override.rs | #![cfg(debug_assertions)]
use std::sync::Mutex;
use nu_utils::locale::LOCALE_OVERRIDE_ENV_VAR;
static LOCALE_OVERRIDE_MUTEX: Mutex<()> = Mutex::new(());
/// Run a closure in a fake locale environment.
///
/// Before the closure is executed, an environment variable whose name is
/// defined in `nu_utils::locale::LOCALE_OVERRIDE_ENV_VAR` is set to the value
/// provided by `locale_string`. When the closure is done, the previous value is
/// restored.
///
/// Environment variables are global values. So when they are changed by one
/// thread they are changed for all others. To prevent a test from overwriting
/// the environment variable of another test, a mutex is used.
pub fn with_locale_override<T>(locale_string: &str, func: fn() -> T) -> T {
let result = {
let _lock = LOCALE_OVERRIDE_MUTEX
.lock()
.expect("Failed to get mutex lock for locale override");
let saved = std::env::var(LOCALE_OVERRIDE_ENV_VAR).ok();
unsafe {
std::env::set_var(LOCALE_OVERRIDE_ENV_VAR, locale_string);
let result = std::panic::catch_unwind(func);
if let Some(locale_str) = saved {
std::env::set_var(LOCALE_OVERRIDE_ENV_VAR, locale_str);
} else {
std::env::remove_var(LOCALE_OVERRIDE_ENV_VAR);
}
result
}
};
result.unwrap_or_else(|err| std::panic::resume_unwind(err))
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-test-support/src/lib.rs | crates/nu-test-support/src/lib.rs | #![doc = include_str!("../README.md")]
pub mod commands;
pub mod fs;
pub mod locale_override;
pub mod macros;
pub mod playground;
use std::process::ExitStatus;
// Needs to be reexported for `nu!` macro
pub use nu_path;
#[derive(Debug)]
pub struct Outcome {
pub out: String,
pub err: String,
pub status: ExitStatus,
}
#[cfg(windows)]
pub const NATIVE_PATH_ENV_VAR: &str = "Path";
#[cfg(not(windows))]
pub const NATIVE_PATH_ENV_VAR: &str = "PATH";
#[cfg(windows)]
pub const NATIVE_PATH_ENV_SEPARATOR: char = ';';
#[cfg(not(windows))]
pub const NATIVE_PATH_ENV_SEPARATOR: char = ':';
impl Outcome {
pub fn new(out: String, err: String, status: ExitStatus) -> Outcome {
Outcome { out, err, status }
}
}
pub fn nu_repl_code(source_lines: &[&str]) -> String {
let mut out = String::from("nu --testbin=nu_repl ...[ ");
for line in source_lines.iter() {
out.push('`');
out.push_str(line);
out.push('`');
out.push(' ');
}
out.push(']');
out
}
pub fn shell_os_paths() -> Vec<std::path::PathBuf> {
let mut original_paths = vec![];
if let Some(paths) = std::env::var_os(NATIVE_PATH_ENV_VAR) {
original_paths = std::env::split_paths(&paths).collect::<Vec<_>>();
}
original_paths
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-test-support/src/fs.rs | crates/nu-test-support/src/fs.rs | use nu_path::{AbsolutePath, AbsolutePathBuf, Path};
use std::io::Read;
pub enum Stub<'a> {
FileWithContent(&'a str, &'a str),
FileWithContentToBeTrimmed(&'a str, &'a str),
EmptyFile(&'a str),
FileWithPermission(&'a str, bool),
}
pub fn file_contents(full_path: impl AsRef<AbsolutePath>) -> String {
let mut file = std::fs::File::open(full_path.as_ref()).expect("can not open file");
let mut contents = String::new();
file.read_to_string(&mut contents)
.expect("can not read file");
contents
}
pub fn file_contents_binary(full_path: impl AsRef<AbsolutePath>) -> Vec<u8> {
let mut file = std::fs::File::open(full_path.as_ref()).expect("can not open file");
let mut contents = Vec::new();
file.read_to_end(&mut contents).expect("can not read file");
contents
}
pub fn line_ending() -> String {
#[cfg(windows)]
{
String::from("\r\n")
}
#[cfg(not(windows))]
{
String::from("\n")
}
}
pub fn files_exist_at(files: &[impl AsRef<Path>], path: impl AsRef<AbsolutePath>) -> bool {
let path = path.as_ref();
files.iter().all(|f| path.join(f.as_ref()).exists())
}
pub fn executable_path() -> AbsolutePathBuf {
let mut path = binaries();
path.push("nu");
path
}
pub fn installed_nu_path() -> AbsolutePathBuf {
let path = std::env::var_os(crate::NATIVE_PATH_ENV_VAR);
if let Ok(path) = which::which_in("nu", path, ".") {
AbsolutePathBuf::try_from(path).expect("installed nushell path is absolute")
} else {
executable_path()
}
}
pub fn root() -> AbsolutePathBuf {
let manifest_dir = if let Ok(manifest_dir) = std::env::var("CARGO_MANIFEST_DIR") {
AbsolutePathBuf::try_from(manifest_dir).expect("CARGO_MANIFEST_DIR is not an absolute path")
} else {
AbsolutePathBuf::try_from(env!("CARGO_MANIFEST_DIR"))
.expect("CARGO_MANIFEST_DIR is not an absolute path")
};
let test_path = manifest_dir.join("Cargo.lock");
if test_path.exists() {
manifest_dir
} else {
manifest_dir
.parent()
.expect("Couldn't find the debug binaries directory")
.parent()
.expect("Couldn't find the debug binaries directory")
.into()
}
}
pub fn binaries() -> AbsolutePathBuf {
let build_target = std::env::var("CARGO_BUILD_TARGET").unwrap_or_default();
let profile = if let Ok(env_profile) = std::env::var("NUSHELL_CARGO_PROFILE") {
env_profile
} else if cfg!(debug_assertions) {
"debug".into()
} else {
"release".into()
};
std::env::var("CARGO_TARGET_DIR")
.or_else(|_| std::env::var("CARGO_BUILD_TARGET_DIR"))
.ok()
.and_then(|p| AbsolutePathBuf::try_from(p).ok())
.unwrap_or_else(|| root().join("target"))
.join(build_target)
.join(profile)
}
pub fn fixtures() -> AbsolutePathBuf {
let mut path = root();
path.push("tests");
path.push("fixtures");
path
}
pub fn assets() -> AbsolutePathBuf {
let mut path = root();
path.push("tests");
path.push("assets");
path
}
pub fn in_directory(path: impl AsRef<nu_path::Path>) -> AbsolutePathBuf {
root().join(path)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-test-support/src/playground.rs | crates/nu-test-support/src/playground.rs | mod director;
pub mod nu_process;
mod play;
#[cfg(test)]
mod tests;
pub use director::Director;
pub use nu_process::{Executable, NuProcess, Outcome};
pub use play::{Dirs, EnvironmentVariable, Playground};
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-test-support/src/macros.rs | crates/nu-test-support/src/macros.rs | /// Run a command in nu and get its output
///
/// The `nu!` macro accepts a number of options like the `cwd` in which the
/// command should be run. It is also possible to specify a different `locale`
/// to test locale dependent commands.
///
/// Pass options as the first arguments in the form of `key_1: value_1, key_1:
/// value_2, ...`. The options are defined in the `NuOpts` struct inside the
/// `nu!` macro.
///
/// The command can be formatted using `{}` just like `println!` or `format!`.
/// Pass the format arguments comma separated after the command itself.
///
/// # Examples
///
/// ```no_run
/// # // NOTE: The `nu!` macro needs the `nu` binary to exist. The test are
/// # // therefore only compiled but not run (that's what the `no_run` at
/// # // the beginning of this code block is for).
/// #
/// use nu_test_support::nu;
///
/// let outcome = nu!(
/// "date now | date to-record | get year"
/// );
///
/// let dir = "/";
/// let outcome = nu!(
/// "ls {} | get name",
/// dir,
/// );
///
/// let outcome = nu!(
/// cwd: "/",
/// "ls | get name",
/// );
///
/// let cell = "size";
/// let outcome = nu!(
/// locale: "de_DE.UTF-8",
/// "ls | into int {}",
/// cell,
/// );
///
/// let decimals = 2;
/// let outcome = nu!(
/// locale: "de_DE.UTF-8",
/// "10 | into string --decimals {}",
/// decimals,
/// );
/// ```
#[macro_export]
macro_rules! nu {
// In the `@options` phase, we restructure all the
// `$field_1: $value_1, $field_2: $value_2, ...`
// pairs to a structure like
// `@options[ $field_1 => $value_1 ; $field_2 => $value_2 ; ... ]`.
// We do this to later distinguish the options from the `$path` and `$part`s.
// (See
// https://users.rust-lang.org/t/i-dont-think-this-local-ambiguity-when-calling-macro-is-ambiguous/79401?u=x3ro
// )
//
// If there is any special treatment needed for the `$value`, we can just
// match for the specific `field` name.
(
@options [ $($options:tt)* ]
cwd: $value:expr,
$($rest:tt)*
) => {
nu!(@options [ $($options)* cwd => $crate::fs::in_directory($value) ; ] $($rest)*)
};
// For all other options, we call `.into()` on the `$value` and hope for the best. ;)
(
@options [ $($options:tt)* ]
$field:ident : $value:expr,
$($rest:tt)*
) => {
nu!(@options [ $($options)* $field => $value.into() ; ] $($rest)*)
};
// When the `$field: $value,` pairs are all parsed, the next tokens are the `$path` and any
// number of `$part`s, potentially followed by a trailing comma.
(
@options [ $($options:tt)* ]
$path:expr
$(, $part:expr)*
$(,)*
) => {{
// Here we parse the options into a `NuOpts` struct
let opts = nu!(@nu_opts $($options)*);
// and format the `$path` using the `$part`s
let path = $path;
// Then finally we go to the `@main` phase, where the actual work is done.
nu!(@main opts, path)
}};
// Create the NuOpts struct from the `field => value ;` pairs
(@nu_opts $( $field:ident => $value:expr ; )*) => {
$crate::macros::NuOpts{
$(
$field: Some($value),
)*
..Default::default()
}
};
// Do the actual work.
(@main $opts:expr, $path:expr) => {{
$crate::macros::nu_run_test($opts, $path, false)
}};
// This is the entrypoint for this macro.
($($token:tt)*) => {{
nu!(@options [ ] $($token)*)
}};
}
#[macro_export]
macro_rules! nu_with_std {
// In the `@options` phase, we restructure all the
// `$field_1: $value_1, $field_2: $value_2, ...`
// pairs to a structure like
// `@options[ $field_1 => $value_1 ; $field_2 => $value_2 ; ... ]`.
// We do this to later distinguish the options from the `$path` and `$part`s.
// (See
// https://users.rust-lang.org/t/i-dont-think-this-local-ambiguity-when-calling-macro-is-ambiguous/79401?u=x3ro
// )
//
// If there is any special treatment needed for the `$value`, we can just
// match for the specific `field` name.
(
@options [ $($options:tt)* ]
cwd: $value:expr,
$($rest:tt)*
) => {
nu_with_std!(@options [ $($options)* cwd => $crate::fs::in_directory($value) ; ] $($rest)*)
};
// For all other options, we call `.into()` on the `$value` and hope for the best. ;)
(
@options [ $($options:tt)* ]
$field:ident : $value:expr,
$($rest:tt)*
) => {
nu_with_std!(@options [ $($options)* $field => $value.into() ; ] $($rest)*)
};
// When the `$field: $value,` pairs are all parsed, the next tokens are the `$path` and any
// number of `$part`s, potentially followed by a trailing comma.
(
@options [ $($options:tt)* ]
$path:expr
$(, $part:expr)*
$(,)*
) => {{
// Here we parse the options into a `NuOpts` struct
let opts = nu_with_std!(@nu_opts $($options)*);
// and format the `$path` using the `$part`s
let path = nu_with_std!(@format_path $path, $($part),*);
// Then finally we go to the `@main` phase, where the actual work is done.
nu_with_std!(@main opts, path)
}};
// Create the NuOpts struct from the `field => value ;` pairs
(@nu_opts $( $field:ident => $value:expr ; )*) => {
$crate::macros::NuOpts{
$(
$field: Some($value),
)*
..Default::default()
}
};
// Helper to format `$path`.
(@format_path $path:expr $(,)?) => {
// When there are no `$part`s, do not format anything
$path
};
(@format_path $path:expr, $($part:expr),* $(,)?) => {{
format!($path, $( $part ),*)
}};
// Do the actual work.
(@main $opts:expr, $path:expr) => {{
$crate::macros::nu_run_test($opts, $path, true)
}};
// This is the entrypoint for this macro.
($($token:tt)*) => {{
nu_with_std!(@options [ ] $($token)*)
}};
}
#[macro_export]
macro_rules! nu_with_plugins {
(cwd: $cwd:expr, plugins: [$(($plugin_name:expr)),*$(,)?], $command:expr) => {{
nu_with_plugins!(
cwd: $cwd,
envs: Vec::<(&str, &str)>::new(),
plugins: [$(($plugin_name)),*],
$command
)
}};
(cwd: $cwd:expr, plugin: ($plugin_name:expr), $command:expr) => {{
nu_with_plugins!(
cwd: $cwd,
envs: Vec::<(&str, &str)>::new(),
plugin: ($plugin_name),
$command
)
}};
(
cwd: $cwd:expr,
envs: $envs:expr,
plugins: [$(($plugin_name:expr)),*$(,)?],
$command:expr
) => {{
$crate::macros::nu_with_plugin_run_test($cwd, $envs, &[$($plugin_name),*], $command)
}};
(cwd: $cwd:expr, envs: $envs:expr, plugin: ($plugin_name:expr), $command:expr) => {{
$crate::macros::nu_with_plugin_run_test($cwd, $envs, &[$plugin_name], $command)
}};
}
use crate::{NATIVE_PATH_ENV_VAR, Outcome};
use nu_path::{AbsolutePath, AbsolutePathBuf, Path, PathBuf};
use nu_utils::escape_quote_string;
use std::{
ffi::OsStr,
process::{Command, Stdio},
};
use tempfile::tempdir;
#[derive(Default)]
pub struct NuOpts {
pub cwd: Option<AbsolutePathBuf>,
pub locale: Option<String>,
pub envs: Option<Vec<(String, String)>>,
pub experimental: Option<Vec<String>>,
pub collapse_output: Option<bool>,
// Note: At the time this was added, passing in a file path was more convenient. However,
// passing in file contents seems like a better API - consider this when adding new uses of
// this field.
pub env_config: Option<PathBuf>,
}
pub fn nu_run_test(opts: NuOpts, commands: impl AsRef<str>, with_std: bool) -> Outcome {
let test_bins = crate::fs::binaries()
.canonicalize()
.expect("Could not canonicalize dummy binaries path");
let mut paths = crate::shell_os_paths();
paths.insert(0, test_bins.into());
let commands = commands.as_ref();
let paths_joined = match std::env::join_paths(paths) {
Ok(all) => all,
Err(_) => panic!("Couldn't join paths for PATH var."),
};
let target_cwd = opts.cwd.unwrap_or_else(crate::fs::root);
let locale = opts.locale.unwrap_or("en_US.UTF-8".to_string());
let executable_path = crate::fs::executable_path();
let mut command = setup_command(&executable_path, &target_cwd);
command
.env(nu_utils::locale::LOCALE_OVERRIDE_ENV_VAR, locale)
.env(NATIVE_PATH_ENV_VAR, paths_joined);
if let Some(envs) = opts.envs {
command.envs(envs);
}
match opts.env_config {
Some(path) => command.arg("--env-config").arg(path),
// TODO: This seems unnecessary: the code that runs for integration tests
// (run_commands) loads startup configs only if they are specified via flags explicitly or
// the shell is started as logging shell (which it is not in this case).
None => command.arg("--no-config-file"),
};
if let Some(experimental_opts) = opts.experimental {
let opts = format!("[{}]", experimental_opts.join(","));
command.arg(format!("--experimental-options={opts}"));
}
if !with_std {
command.arg("--no-std-lib");
}
// Use plain errors to help make error text matching more consistent
command.args(["--error-style", "plain", "--commands", commands]);
command.stdout(Stdio::piped()).stderr(Stdio::piped());
// Uncomment to debug the command being run:
// println!("=== command\n{command:#?}\n");
let process = match command.spawn() {
Ok(child) => child,
Err(why) => panic!("Can't run test {:?} {}", crate::fs::executable_path(), why),
};
let output = process
.wait_with_output()
.expect("couldn't read from stdout/stderr");
let out = String::from_utf8_lossy(&output.stdout);
let err = String::from_utf8_lossy(&output.stderr);
let out = if opts.collapse_output.unwrap_or(true) {
collapse_output(&out)
} else {
out.into_owned()
};
println!("=== stderr\n{err}");
Outcome::new(out, err.into_owned(), output.status)
}
pub fn nu_with_plugin_run_test<E, K, V>(
cwd: impl AsRef<Path>,
envs: E,
plugins: &[&str],
command: &str,
) -> Outcome
where
E: IntoIterator<Item = (K, V)>,
K: AsRef<OsStr>,
V: AsRef<OsStr>,
{
let test_bins = crate::fs::binaries();
let test_bins = nu_path::canonicalize_with(&test_bins, ".").unwrap_or_else(|e| {
panic!(
"Couldn't canonicalize dummy binaries path {}: {:?}",
test_bins.display(),
e
)
});
let temp = tempdir().expect("couldn't create a temporary directory");
let [temp_config_file, temp_env_config_file] = ["config.nu", "env.nu"].map(|name| {
let temp_file = temp.path().join(name);
std::fs::File::create(&temp_file).expect("couldn't create temporary config file");
temp_file
});
// We don't have to write the plugin registry file, it's ok for it to not exist
let temp_plugin_file = temp.path().join("plugin.msgpackz");
crate::commands::ensure_plugins_built();
let plugin_paths_quoted: Vec<String> = plugins
.iter()
.map(|plugin_name| {
let plugin = with_exe(plugin_name);
let plugin_path = nu_path::canonicalize_with(&plugin, &test_bins)
.unwrap_or_else(|_| panic!("failed to canonicalize plugin {} path", &plugin));
let plugin_path = plugin_path.to_string_lossy();
escape_quote_string(&plugin_path)
})
.collect();
let plugins_arg = format!("[{}]", plugin_paths_quoted.join(","));
let target_cwd = crate::fs::in_directory(&cwd);
// In plugin testing, we need to use installed nushell to drive
// plugin commands.
let mut executable_path = crate::fs::executable_path();
if !executable_path.exists() {
executable_path = crate::fs::installed_nu_path();
}
let process = match setup_command(&executable_path, &target_cwd)
.envs(envs)
.arg("--commands")
.arg(command)
// Use plain errors to help make error text matching more consistent
.args(["--error-style", "plain"])
.arg("--config")
.arg(temp_config_file)
.arg("--env-config")
.arg(temp_env_config_file)
.arg("--plugin-config")
.arg(temp_plugin_file)
.arg("--plugins")
.arg(plugins_arg)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
{
Ok(child) => child,
Err(why) => panic!("Can't run test {why}"),
};
let output = process
.wait_with_output()
.expect("couldn't read from stdout/stderr");
let out = collapse_output(&String::from_utf8_lossy(&output.stdout));
let err = String::from_utf8_lossy(&output.stderr);
println!("=== stderr\n{err}");
Outcome::new(out, err.into_owned(), output.status)
}
fn with_exe(name: &str) -> String {
#[cfg(windows)]
{
name.to_string() + ".exe"
}
#[cfg(not(windows))]
{
name.to_string()
}
}
fn collapse_output(out: &str) -> String {
let out = out.lines().collect::<Vec<_>>().join("\n");
let out = out.replace("\r\n", "");
out.replace('\n', "")
}
fn setup_command(executable_path: &AbsolutePath, target_cwd: &AbsolutePath) -> Command {
let mut command = Command::new(executable_path);
command
.env_clear()
.current_dir(target_cwd)
.env_remove("FILE_PWD")
.env("PWD", target_cwd); // setting PWD is enough to set cwd;
// Need these extra environments from before the environment is cleared.
let envs: std::collections::HashMap<String, String> = std::env::vars()
.filter(|(n, _)| {
n.starts_with("System") // System variables for disks, paths, etc.
|| n == "NUSHELL_CARGO_PROFILE" // Variable for crate::fs::binaries()
|| n == "PATHEXT" // Needed for Windows translate `nu` to `.../nu.exe`
|| n.starts_with("CARGO_")
|| n.starts_with("RUSTUP_")
})
.collect();
command.envs(envs);
command
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-test-support/src/commands.rs | crates/nu-test-support/src/commands.rs | use std::{
io::Read,
process::{Command, Stdio},
sync::{
Mutex,
atomic::{AtomicBool, Ordering::Relaxed},
},
};
static CARGO_BUILD_LOCK: Mutex<()> = Mutex::new(());
static PLUGINS_BUILT: AtomicBool = AtomicBool::new(false);
// This runs `cargo build --package nu_plugin_*` to ensure that all plugins
// have been built before plugin tests run. We use a lock to avoid multiple
// simultaneous `cargo build` invocations clobbering each other.
pub fn ensure_plugins_built() {
let _guard = CARGO_BUILD_LOCK.lock().expect("could not get mutex lock");
if PLUGINS_BUILT.load(Relaxed) {
return;
}
let cargo_path = env!("CARGO");
let mut arguments = vec![
"build",
"--workspace",
"--bins",
// Don't build nu, so that we only build the plugins
"--exclude",
"nu",
// Exclude nu_plugin_polars, because it's not needed at this stage, and is a large build
"--exclude",
"nu_plugin_polars",
"--quiet",
];
let profile = std::env::var("NUSHELL_CARGO_PROFILE");
if let Ok(profile) = &profile {
arguments.push("--profile");
arguments.push(profile);
}
let mut command = Command::new(cargo_path)
.args(arguments)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("Failed to spawn cargo build command");
let stderr = command.stderr.take();
let success = command
.wait()
.expect("failed to wait cargo build command")
.success();
if let Some(mut stderr) = stderr {
let mut buffer = String::new();
stderr
.read_to_string(&mut buffer)
.expect("failed to read cargo build stderr");
if !buffer.is_empty() {
println!("=== cargo build stderr\n{buffer}");
}
}
if !success {
panic!("cargo build failed");
}
PLUGINS_BUILT.store(true, Relaxed);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-test-support/src/playground/play.rs | crates/nu-test-support/src/playground/play.rs | use super::Director;
use crate::fs::{self, Stub};
use nu_glob::{Uninterruptible, glob};
#[cfg(not(target_arch = "wasm32"))]
use nu_path::Path;
use nu_path::{AbsolutePath, AbsolutePathBuf};
use std::str;
use tempfile::{TempDir, tempdir};
#[derive(Default, Clone, Debug)]
pub struct EnvironmentVariable {
pub name: String,
pub value: String,
}
impl EnvironmentVariable {
fn new(name: &str, value: &str) -> Self {
Self {
name: name.to_string(),
value: value.to_string(),
}
}
}
pub struct Playground<'a> {
_root: TempDir,
tests: String,
cwd: AbsolutePathBuf,
config: Option<AbsolutePathBuf>,
environment_vars: Vec<EnvironmentVariable>,
dirs: &'a Dirs,
}
#[derive(Clone)]
pub struct Dirs {
pub root: AbsolutePathBuf,
pub test: AbsolutePathBuf,
pub fixtures: AbsolutePathBuf,
}
impl Dirs {
pub fn formats(&self) -> AbsolutePathBuf {
self.fixtures.join("formats")
}
pub fn root(&self) -> &AbsolutePath {
&self.root
}
pub fn test(&self) -> &AbsolutePath {
&self.test
}
}
impl Playground<'_> {
pub fn root(&self) -> &AbsolutePath {
&self.dirs.root
}
pub fn cwd(&self) -> &AbsolutePath {
&self.cwd
}
pub fn back_to_playground(&mut self) -> &mut Self {
self.cwd = self.root().join(&self.tests);
self
}
pub fn play(&mut self) -> &mut Self {
self
}
pub fn setup(topic: &str, block: impl FnOnce(Dirs, &mut Playground)) {
let temp = tempdir().expect("Could not create a tempdir");
let root = AbsolutePathBuf::try_from(temp.path())
.expect("Tempdir is not an absolute path")
.canonicalize()
.expect("Could not canonicalize tempdir");
let test = root.join(topic);
if test.exists() {
std::fs::remove_dir_all(&test).expect("Could not remove directory");
}
std::fs::create_dir(&test).expect("Could not create directory");
let test = test
.canonicalize()
.expect("Could not canonicalize test path");
let fixtures = fs::fixtures()
.canonicalize()
.expect("Could not canonicalize fixtures path");
let dirs = Dirs {
root: root.into(),
test: test.as_path().into(),
fixtures: fixtures.into(),
};
let mut playground = Playground {
_root: temp,
tests: topic.to_string(),
cwd: test.into(),
config: None,
environment_vars: Vec::default(),
dirs: &dirs,
};
block(dirs.clone(), &mut playground);
}
pub fn with_config(&mut self, source_file: AbsolutePathBuf) -> &mut Self {
self.config = Some(source_file);
self
}
pub fn with_env(&mut self, name: &str, value: &str) -> &mut Self {
self.environment_vars
.push(EnvironmentVariable::new(name, value));
self
}
pub fn get_config(&self) -> Option<&str> {
self.config
.as_ref()
.map(|cfg| cfg.to_str().expect("could not convert path."))
}
pub fn build(&mut self) -> Director {
Director {
cwd: Some(self.dirs.test().into()),
config: self.config.clone().map(|cfg| cfg.into()),
environment_vars: self.environment_vars.clone(),
..Default::default()
}
}
pub fn cococo(&mut self, arg: &str) -> Director {
self.build().cococo(arg)
}
pub fn pipeline(&mut self, commands: &str) -> Director {
self.build().pipeline(commands)
}
pub fn mkdir(&mut self, directory: &str) -> &mut Self {
self.cwd.push(directory);
std::fs::create_dir_all(&self.cwd).expect("can not create directory");
self.back_to_playground();
self
}
#[cfg(not(target_arch = "wasm32"))]
pub fn symlink(&mut self, from: impl AsRef<Path>, to: impl AsRef<Path>) -> &mut Self {
let from = self.cwd.join(from);
let to = self.cwd.join(to);
let create_symlink = {
#[cfg(unix)]
{
std::os::unix::fs::symlink
}
#[cfg(windows)]
{
if from.is_file() {
std::os::windows::fs::symlink_file
} else if from.is_dir() {
std::os::windows::fs::symlink_dir
} else {
panic!("symlink from must be a file or dir")
}
}
};
create_symlink(from, to).expect("can not create symlink");
self.back_to_playground();
self
}
pub fn with_files(&mut self, files: &[Stub]) -> &mut Self {
let endl = fs::line_ending();
files
.iter()
.map(|f| {
let mut permission_set = false;
let mut write_able = true;
let (file_name, contents) = match *f {
Stub::EmptyFile(name) => (name, String::new()),
Stub::FileWithContent(name, content) => (name, content.to_string()),
Stub::FileWithContentToBeTrimmed(name, content) => (
name,
content
.lines()
.skip(1)
.map(|line| line.trim())
.collect::<Vec<&str>>()
.join(&endl),
),
Stub::FileWithPermission(name, is_write_able) => {
permission_set = true;
write_able = is_write_able;
(name, "check permission".to_string())
}
};
let path = self.cwd.join(file_name);
std::fs::write(&path, contents.as_bytes()).expect("can not create file");
if permission_set {
let err_perm = "can not set permission";
let mut perm = std::fs::metadata(path.clone())
.expect(err_perm)
.permissions();
perm.set_readonly(!write_able);
std::fs::set_permissions(path, perm).expect(err_perm);
}
})
.for_each(drop);
self.back_to_playground();
self
}
pub fn within(&mut self, directory: &str) -> &mut Self {
self.cwd.push(directory);
if !(self.cwd.exists() && self.cwd.is_dir()) {
std::fs::create_dir(&self.cwd).expect("can not create directory");
}
self
}
pub fn glob_vec(pattern: &str) -> Vec<std::path::PathBuf> {
let glob = glob(pattern, Uninterruptible);
glob.expect("invalid pattern")
.map(|path| {
if let Ok(path) = path {
path
} else {
unreachable!()
}
})
.collect()
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-test-support/src/playground/tests.rs | crates/nu-test-support/src/playground/tests.rs | use crate::playground::Playground;
#[test]
fn current_working_directory_in_sandbox_directory_created() {
Playground::setup("topic", |dirs, nu| {
let original_cwd = dirs.test();
nu.within("some_directory_within");
assert_eq!(nu.cwd(), original_cwd.join("some_directory_within"));
})
}
#[test]
fn current_working_directory_back_to_root_from_anywhere() {
Playground::setup("topic", |dirs, nu| {
let original_cwd = dirs.test();
nu.within("some_directory_within");
nu.back_to_playground();
assert_eq!(nu.cwd(), original_cwd);
})
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-test-support/src/playground/director.rs | crates/nu-test-support/src/playground/director.rs | use super::EnvironmentVariable;
use super::nu_process::*;
use std::ffi::OsString;
use std::fmt;
use std::fmt::Write;
#[derive(Default, Debug)]
pub struct Director {
pub cwd: Option<OsString>,
pub environment_vars: Vec<EnvironmentVariable>,
pub config: Option<OsString>,
pub pipeline: Option<Vec<String>>,
pub executable: Option<NuProcess>,
}
impl Director {
pub fn cococo(&self, arg: &str) -> Self {
let mut process = NuProcess {
environment_vars: self.environment_vars.clone(),
..Default::default()
};
process.args(&["--testbin", "cococo", arg]);
Director {
config: self.config.clone(),
executable: Some(process),
environment_vars: self.environment_vars.clone(),
..Default::default()
}
}
pub fn and_then(&mut self, commands: &str) -> &mut Self {
let commands = commands.to_string();
if let Some(ref mut pipeline) = self.pipeline {
pipeline.push(commands);
} else {
self.pipeline = Some(vec![commands]);
}
self
}
pub fn pipeline(&self, commands: &str) -> Self {
let mut director = Director {
pipeline: if commands.is_empty() {
None
} else {
Some(vec![commands.to_string()])
},
..Default::default()
};
let mut process = NuProcess {
environment_vars: self.environment_vars.clone(),
..Default::default()
};
if let Some(working_directory) = &self.cwd {
process.cwd(working_directory);
}
process.arg("--no-history");
if let Some(config_file) = self.config.as_ref() {
process.args(&[
"--config",
config_file.to_str().expect("failed to convert."),
]);
}
process.args(&["--log-level", "info"]);
director.executable = Some(process);
director
}
pub fn executable(&self) -> Option<&NuProcess> {
if let Some(binary) = &self.executable {
Some(binary)
} else {
None
}
}
}
impl Executable for Director {
fn execute(&mut self) -> Result<Outcome, NuError> {
use std::process::Stdio;
match self.executable() {
Some(binary) => {
let mut commands = String::new();
if let Some(pipelines) = &self.pipeline {
for pipeline in pipelines {
if !commands.is_empty() {
commands.push_str("| ");
}
let _ = writeln!(commands, "{pipeline}");
}
}
let process = binary
.construct()
.stdout(Stdio::piped())
// .stdin(Stdio::piped())
.stderr(Stdio::piped())
.arg(format!("-c '{commands}'"))
.spawn()
.expect("It should be possible to run tests");
process
.wait_with_output()
.map_err(|_| {
let reason = format!(
"could not execute process {} ({})",
binary, "No execution took place"
);
NuError {
desc: reason,
exit: None,
output: None,
}
})
.and_then(|process| {
let out =
Outcome::new(&read_std(&process.stdout), &read_std(&process.stderr));
match process.status.success() {
true => Ok(out),
false => Err(NuError {
desc: String::new(),
exit: Some(process.status),
output: Some(out),
}),
}
})
}
None => Err(NuError {
desc: String::from("err"),
exit: None,
output: None,
}),
}
}
}
impl fmt::Display for Director {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "director")
}
}
fn read_std(std: &[u8]) -> Vec<u8> {
let out = String::from_utf8_lossy(std);
let out = out.lines().collect::<Vec<_>>().join("\n");
let out = out.replace("\r\n", "");
out.replace('\n', "").into_bytes()
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.