repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/system/ps.rs | crates/nu-command/src/system/ps.rs | #[cfg(target_os = "macos")]
use chrono::{Local, TimeZone};
#[cfg(windows)]
use itertools::Itertools;
use nu_engine::command_prelude::*;
#[cfg(target_os = "linux")]
use procfs::WithCurrentSystemInfo;
use std::time::Duration;
#[derive(Clone)]
pub struct Ps;
impl Command for Ps {
fn name(&self) -> &str {
"ps"
}
fn signature(&self) -> Signature {
Signature::build("ps")
.input_output_types(vec![(Type::Nothing, Type::table())])
.switch(
"long",
"list all available columns for each entry",
Some('l'),
)
.filter()
.category(Category::System)
}
fn description(&self) -> &str {
"View information about system processes."
}
fn search_terms(&self) -> Vec<&str> {
vec!["procedures", "operations", "tasks", "ops"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
run_ps(engine_state, stack, call)
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "List the system processes",
example: "ps",
result: None,
},
Example {
description: "List the top 5 system processes with the highest memory usage",
example: "ps | sort-by mem | last 5",
result: None,
},
Example {
description: "List the top 3 system processes with the highest CPU usage",
example: "ps | sort-by cpu | last 3",
result: None,
},
Example {
description: "List the system processes with 'nu' in their names",
example: "ps | where name =~ 'nu'",
result: None,
},
Example {
description: "Get the parent process id of the current nu process",
example: "ps | where pid == $nu.pid | get ppid",
result: None,
},
]
}
}
fn run_ps(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
) -> Result<PipelineData, ShellError> {
let mut output = vec![];
let span = call.head;
let long = call.has_flag(engine_state, stack, "long")?;
for proc in nu_system::collect_proc(Duration::from_millis(100), false) {
let mut record = Record::new();
record.push("pid", Value::int(proc.pid() as i64, span));
record.push("ppid", Value::int(proc.ppid() as i64, span));
record.push("name", Value::string(proc.name(), span));
#[cfg(not(windows))]
{
// Hide status on Windows until we can find a good way to support it
record.push("status", Value::string(proc.status(), span));
}
record.push("cpu", Value::float(proc.cpu_usage(), span));
record.push("mem", Value::filesize(proc.mem_size() as i64, span));
record.push("virtual", Value::filesize(proc.virtual_size() as i64, span));
if long {
record.push("command", Value::string(proc.command(), span));
#[cfg(target_os = "linux")]
{
let proc_stat = proc
.curr_proc
.stat()
.map_err(|e| ShellError::GenericError {
error: "Error getting process stat".into(),
msg: e.to_string(),
span: Some(Span::unknown()),
help: None,
inner: vec![],
})?;
record.push(
"start_time",
match proc_stat.starttime().get() {
Ok(ts) => Value::date(ts.into(), span),
Err(_) => Value::nothing(span),
},
);
record.push("user_id", Value::int(proc.curr_proc.owner() as i64, span));
// These work and may be helpful, but it just seemed crowded
// record.push("group_id", Value::int(proc_stat.pgrp as i64, span));
// record.push("session_id", Value::int(proc_stat.session as i64, span));
// This may be helpful for ctrl+z type of checking, once we get there
// record.push("tpg_id", Value::int(proc_stat.tpgid as i64, span));
record.push("priority", Value::int(proc_stat.priority, span));
record.push("process_threads", Value::int(proc_stat.num_threads, span));
record.push("cwd", Value::string(proc.cwd(), span));
}
#[cfg(windows)]
{
//TODO: There's still more information we can cram in there if we want to
// see the ProcessInfo struct for more information
record.push(
"start_time",
Value::date(proc.start_time.fixed_offset(), span),
);
record.push(
"user",
Value::string(
proc.user.clone().name.unwrap_or("unknown".to_string()),
span,
),
);
record.push(
"user_sid",
Value::string(
proc.user
.clone()
.sid
.iter()
.map(|r| r.to_string())
.join("-"),
span,
),
);
record.push("priority", Value::int(proc.priority as i64, span));
record.push("cwd", Value::string(proc.cwd(), span));
record.push(
"environment",
Value::list(
proc.environ()
.iter()
.map(|x| Value::string(x.to_string(), span))
.collect(),
span,
),
);
}
#[cfg(target_os = "macos")]
{
let timestamp = Local
.timestamp_nanos(proc.start_time * 1_000_000_000)
.into();
record.push("start_time", Value::date(timestamp, span));
record.push("user_id", Value::int(proc.user_id, span));
record.push("priority", Value::int(proc.priority, span));
record.push("process_threads", Value::int(proc.task_thread_num, span));
record.push("cwd", Value::string(proc.cwd(), span));
}
}
output.push(Value::record(record, span));
}
Ok(output.into_pipeline_data(span, engine_state.signals().clone()))
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/system/sys/temp.rs | crates/nu-command/src/system/sys/temp.rs | use nu_engine::command_prelude::*;
use sysinfo::Components;
#[derive(Clone)]
pub struct SysTemp;
impl Command for SysTemp {
fn name(&self) -> &str {
"sys temp"
}
fn signature(&self) -> Signature {
Signature::build("sys temp")
.filter()
.category(Category::System)
.input_output_types(vec![(Type::Nothing, Type::table())])
}
fn description(&self) -> &str {
"View the temperatures of system components."
}
fn extra_description(&self) -> &str {
"Some system components do not support temperature readings, so this command may return an empty list if no components support temperature."
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
Ok(temp(call.head).into_pipeline_data())
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
description: "Show the system temperatures",
example: "sys temp",
result: None,
}]
}
}
fn temp(span: Span) -> Value {
let components = Components::new_with_refreshed_list()
.iter()
.map(|component| {
let mut record = record! {
"unit" => Value::string(component.label(), span),
"temp" => Value::float(component.temperature().unwrap_or(f32::NAN).into(), span),
"high" => Value::float(component.max().unwrap_or(f32::NAN).into(), span),
};
if let Some(critical) = component.critical() {
record.push("critical", Value::float(critical.into(), span));
}
Value::record(record, span)
})
.collect();
Value::list(components, span)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/system/sys/sys_.rs | crates/nu-command/src/system/sys/sys_.rs | use nu_engine::{command_prelude::*, get_full_help};
#[derive(Clone)]
pub struct Sys;
impl Command for Sys {
fn name(&self) -> &str {
"sys"
}
fn signature(&self) -> Signature {
Signature::build("sys")
.filter()
.category(Category::System)
.input_output_types(vec![(Type::Nothing, Type::record())])
}
fn description(&self) -> &str {
"View information about the system."
}
fn extra_description(&self) -> &str {
"You must use one of the following subcommands. Using this command as-is will only produce this help message."
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
Ok(Value::string(get_full_help(self, engine_state, stack), call.head).into_pipeline_data())
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
description: "Show info about the system",
example: "sys",
result: None,
}]
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/system/sys/disks.rs | crates/nu-command/src/system/sys/disks.rs | use super::trim_cstyle_null;
use nu_engine::command_prelude::*;
use sysinfo::Disks;
#[derive(Clone)]
pub struct SysDisks;
impl Command for SysDisks {
fn name(&self) -> &str {
"sys disks"
}
fn signature(&self) -> Signature {
Signature::build("sys disks")
.filter()
.category(Category::System)
.input_output_types(vec![(Type::Nothing, Type::table())])
}
fn description(&self) -> &str {
"View information about the system disks."
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
Ok(disks(call.head).into_pipeline_data())
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
description: "Show info about the system disks",
example: "sys disks",
result: None,
}]
}
}
fn disks(span: Span) -> Value {
let disks = Disks::new_with_refreshed_list()
.iter()
.map(|disk| {
let device = trim_cstyle_null(disk.name().to_string_lossy());
let typ = trim_cstyle_null(disk.file_system().to_string_lossy());
let record = record! {
"device" => Value::string(device, span),
"type" => Value::string(typ, span),
"mount" => Value::string(disk.mount_point().to_string_lossy(), span),
"total" => Value::filesize(disk.total_space() as i64, span),
"free" => Value::filesize(disk.available_space() as i64, span),
"removable" => Value::bool(disk.is_removable(), span),
"kind" => Value::string(disk.kind().to_string(), span),
};
Value::record(record, span)
})
.collect();
Value::list(disks, span)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/system/sys/users.rs | crates/nu-command/src/system/sys/users.rs | use super::trim_cstyle_null;
use nu_engine::command_prelude::*;
use sysinfo::Users;
#[derive(Clone)]
pub struct SysUsers;
impl Command for SysUsers {
fn name(&self) -> &str {
"sys users"
}
fn signature(&self) -> Signature {
Signature::build("sys users")
.category(Category::System)
.input_output_types(vec![(Type::Nothing, Type::table())])
}
fn description(&self) -> &str {
"View information about the users on the system."
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
Ok(users(call.head).into_pipeline_data())
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
description: "Show info about the system users",
example: "sys users",
result: None,
}]
}
}
fn users(span: Span) -> Value {
let users = Users::new_with_refreshed_list()
.iter()
.map(|user| {
let groups = user
.groups()
.iter()
.map(|group| Value::string(trim_cstyle_null(group.name()), span))
.collect();
let record = record! {
"name" => Value::string(trim_cstyle_null(user.name()), span),
"groups" => Value::list(groups, span),
};
Value::record(record, span)
})
.collect();
Value::list(users, span)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/system/sys/mod.rs | crates/nu-command/src/system/sys/mod.rs | mod cpu;
mod disks;
mod host;
mod mem;
mod net;
mod sys_;
mod temp;
mod users;
pub use cpu::SysCpu;
pub use disks::SysDisks;
pub use host::SysHost;
pub use mem::SysMem;
pub use net::SysNet;
pub use sys_::Sys;
pub use temp::SysTemp;
pub use users::SysUsers;
fn trim_cstyle_null(s: impl AsRef<str>) -> String {
s.as_ref().trim_matches('\0').into()
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/system/sys/mem.rs | crates/nu-command/src/system/sys/mem.rs | use nu_engine::command_prelude::*;
use sysinfo::System;
#[derive(Clone)]
pub struct SysMem;
impl Command for SysMem {
fn name(&self) -> &str {
"sys mem"
}
fn signature(&self) -> Signature {
Signature::build("sys mem")
.filter()
.category(Category::System)
.input_output_types(vec![(Type::Nothing, Type::record())])
}
fn description(&self) -> &str {
"View information about the system memory."
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
Ok(mem(call.head).into_pipeline_data())
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
description: "Show info about the system memory",
example: "sys mem",
result: None,
}]
}
}
fn mem(span: Span) -> Value {
let mut sys = System::new();
sys.refresh_memory();
let record = record! {
"total" => Value::filesize(sys.total_memory() as i64, span),
"free" => Value::filesize(sys.free_memory() as i64, span),
"used" => Value::filesize(sys.used_memory() as i64, span),
"available" => Value::filesize(sys.available_memory() as i64, span),
"swap total" => Value::filesize(sys.total_swap() as i64, span),
"swap free" => Value::filesize(sys.free_swap() as i64, span),
"swap used" => Value::filesize(sys.used_swap() as i64, span),
};
Value::record(record, span)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/system/sys/cpu.rs | crates/nu-command/src/system/sys/cpu.rs | use super::trim_cstyle_null;
use nu_engine::command_prelude::*;
use sysinfo::{CpuRefreshKind, MINIMUM_CPU_UPDATE_INTERVAL, System};
#[derive(Clone)]
pub struct SysCpu;
impl Command for SysCpu {
fn name(&self) -> &str {
"sys cpu"
}
fn signature(&self) -> Signature {
Signature::build("sys cpu")
.filter()
.switch(
"long",
"Get all available columns (slower, needs to sample CPU over time)",
Some('l'),
)
.category(Category::System)
.input_output_types(vec![(Type::Nothing, Type::table())])
}
fn description(&self) -> &str {
"View information about the system CPUs."
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let long = call.has_flag(engine_state, stack, "long")?;
Ok(cpu(long, call.head).into_pipeline_data())
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
description: "Show info about the system CPUs",
example: "sys cpu",
result: None,
}]
}
}
fn cpu(long: bool, span: Span) -> Value {
let mut sys = System::new();
if long {
sys.refresh_cpu_specifics(CpuRefreshKind::everything());
// We must refresh the CPU twice a while apart to get valid usage data.
// In theory we could just sleep MINIMUM_CPU_UPDATE_INTERVAL, but I've noticed that
// that gives poor results (error of ~5%). Decided to wait 2x that long, somewhat arbitrarily
std::thread::sleep(MINIMUM_CPU_UPDATE_INTERVAL * 2);
sys.refresh_cpu_specifics(CpuRefreshKind::nothing().with_cpu_usage());
} else {
sys.refresh_cpu_specifics(CpuRefreshKind::nothing().with_frequency());
}
let cpus = sys
.cpus()
.iter()
.map(|cpu| {
let load_avg = System::load_average();
let load_avg = format!(
"{:.2}, {:.2}, {:.2}",
load_avg.one, load_avg.five, load_avg.fifteen
);
let mut record = record! {
"name" => Value::string(trim_cstyle_null(cpu.name()), span),
"brand" => Value::string(trim_cstyle_null(cpu.brand()), span),
"vendor_id" => Value::string(trim_cstyle_null(cpu.vendor_id()), span),
"freq" => Value::int(cpu.frequency() as i64, span),
"load_average" => Value::string(load_avg, span),
};
if long {
// sysinfo CPU usage numbers are not very precise unless you wait a long time between refreshes.
// Round to 1DP (chosen somewhat arbitrarily) so people aren't misled by high-precision floats.
let rounded_usage = (f64::from(cpu.cpu_usage()) * 10.0).round() / 10.0;
record.push("cpu_usage", rounded_usage.into_value(span));
}
Value::record(record, span)
})
.collect();
Value::list(cpus, span)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/system/sys/host.rs | crates/nu-command/src/system/sys/host.rs | use super::trim_cstyle_null;
use chrono::{DateTime, FixedOffset, Local};
use nu_engine::command_prelude::*;
use sysinfo::System;
#[derive(Clone)]
pub struct SysHost;
impl Command for SysHost {
fn name(&self) -> &str {
"sys host"
}
fn signature(&self) -> Signature {
Signature::build("sys host")
.filter()
.category(Category::System)
.input_output_types(vec![(Type::Nothing, Type::record())])
}
fn description(&self) -> &str {
"View information about the system host."
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
Ok(host(call.head).into_pipeline_data())
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
description: "Show info about the system host",
example: "sys host",
result: None,
}]
}
}
fn host(span: Span) -> Value {
let mut record = Record::new();
if let Some(name) = System::name() {
record.push("name", Value::string(trim_cstyle_null(name), span));
}
if let Some(version) = System::os_version() {
record.push("os_version", Value::string(trim_cstyle_null(version), span));
}
if let Some(long_version) = System::long_os_version() {
record.push(
"long_os_version",
Value::string(trim_cstyle_null(long_version), span),
);
}
if let Some(version) = System::kernel_version() {
record.push(
"kernel_version",
Value::string(trim_cstyle_null(version), span),
);
}
if let Some(hostname) = System::host_name() {
record.push("hostname", Value::string(trim_cstyle_null(hostname), span));
}
let uptime = System::uptime()
.saturating_mul(1_000_000_000)
.try_into()
.unwrap_or(i64::MAX);
record.push("uptime", Value::duration(uptime, span));
let boot_time = boot_time()
.map(|time| Value::date(time, span))
.unwrap_or(Value::nothing(span));
record.push("boot_time", boot_time);
Value::record(record, span)
}
fn boot_time() -> Option<DateTime<FixedOffset>> {
// Broken systems can apparently return really high values.
// See: https://github.com/nushell/nushell/issues/10155
// First, try to convert u64 to i64, and then try to create a `DateTime`.
let secs = System::boot_time().try_into().ok()?;
let time = DateTime::from_timestamp(secs, 0)?;
Some(time.with_timezone(&Local).fixed_offset())
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/system/sys/net.rs | crates/nu-command/src/system/sys/net.rs | use super::trim_cstyle_null;
use nu_engine::command_prelude::*;
use sysinfo::Networks;
#[derive(Clone)]
pub struct SysNet;
impl Command for SysNet {
fn name(&self) -> &str {
"sys net"
}
fn signature(&self) -> Signature {
Signature::build("sys net")
.filter()
.category(Category::System)
.input_output_types(vec![(Type::Nothing, Type::table())])
}
fn description(&self) -> &str {
"View information about the system network interfaces."
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
Ok(net(call.head).into_pipeline_data())
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
description: "Show info about the system network",
example: "sys net",
result: None,
}]
}
}
fn net(span: Span) -> Value {
let networks = Networks::new_with_refreshed_list()
.iter()
.map(|(iface, data)| {
let ip_addresses = data
.ip_networks()
.iter()
.map(|ip| {
let protocol = match ip.addr {
std::net::IpAddr::V4(_) => "ipv4",
std::net::IpAddr::V6(_) => "ipv6",
};
Value::record(
record! {
"address" => Value::string(ip.addr.to_string(), span),
"protocol" => Value::string(protocol, span),
"loop" => Value::bool(ip.addr.is_loopback(), span),
"multicast" => Value::bool(ip.addr.is_multicast(), span),
},
span,
)
})
.collect();
let record = record! {
"name" => Value::string(trim_cstyle_null(iface), span),
"mac" => Value::string(data.mac_address().to_string(), span),
"ip" => Value::list(ip_addresses, span),
"sent" => Value::filesize(data.total_transmitted() as i64, span),
"recv" => Value::filesize(data.total_received() as i64, span),
};
Value::record(record, span)
})
.collect();
Value::list(networks, span)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/misc/source.rs | crates/nu-command/src/misc/source.rs | use nu_engine::{command_prelude::*, get_eval_block_with_early_return};
use nu_path::{canonicalize_with, is_windows_device_path};
use nu_protocol::{BlockId, engine::CommandType, shell_error::io::IoError};
/// Source a file for environment variables.
#[derive(Clone)]
pub struct Source;
impl Command for Source {
fn name(&self) -> &str {
"source"
}
fn signature(&self) -> Signature {
Signature::build("source")
.input_output_types(vec![(Type::Any, Type::Any)])
.required(
"filename",
SyntaxShape::OneOf(vec![SyntaxShape::Filepath, SyntaxShape::Nothing]),
"The filepath to the script file to source (`null` for no-op).",
)
.category(Category::Core)
}
fn description(&self) -> &str {
"Runs a script file in the current context."
}
fn extra_description(&self) -> &str {
r#"This command is a parser keyword. For details, check:
https://www.nushell.sh/book/thinking_in_nu.html"#
}
fn command_type(&self) -> CommandType {
CommandType::Keyword
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
if call.get_parser_info(stack, "noop").is_some() {
return Ok(PipelineData::empty());
}
// Note: two hidden positionals are used here that are injected by the parser:
// 1. The block_id that corresponded to the 0th position
// 2. The block_id_name that corresponded to the file name at the 0th position
let block_id: i64 = call.req_parser_info(engine_state, stack, "block_id")?;
let block_id_name: String = call.req_parser_info(engine_state, stack, "block_id_name")?;
let block_id = BlockId::new(block_id as usize);
let block = engine_state.get_block(block_id).clone();
let cwd = engine_state.cwd_as_string(Some(stack))?;
let pb = std::path::PathBuf::from(block_id_name);
let parent = pb.parent().unwrap_or(std::path::Path::new(""));
let file_path = if is_windows_device_path(pb.as_path()) {
pb.clone()
} else {
canonicalize_with(pb.as_path(), cwd).map_err(|err| {
IoError::new(err.not_found_as(NotFound::File), call.head, pb.clone())
})?
};
// Note: We intentionally left out PROCESS_PATH since it's supposed to
// to work like argv[0] in C, which is the name of the program being executed.
// Since we're not executing a program, we don't need to set it.
// Save the old env vars so we can restore them after the script has ran
let old_file_pwd = stack.get_env_var(engine_state, "FILE_PWD").cloned();
let old_current_file = stack.get_env_var(engine_state, "CURRENT_FILE").cloned();
// Add env vars so they are available to the script
stack.add_env_var(
"FILE_PWD".to_string(),
Value::string(parent.to_string_lossy(), Span::unknown()),
);
stack.add_env_var(
"CURRENT_FILE".to_string(),
Value::string(file_path.to_string_lossy(), Span::unknown()),
);
let eval_block_with_early_return = get_eval_block_with_early_return(engine_state);
let return_result =
eval_block_with_early_return(engine_state, stack, &block, input).map(|p| p.body);
// After the script has ran, restore the old values unless they didn't exist.
// If they didn't exist prior, remove the env vars
if let Some(old_file_pwd) = old_file_pwd {
stack.add_env_var("FILE_PWD".to_string(), old_file_pwd.clone());
} else {
stack.remove_env_var(engine_state, "FILE_PWD");
}
if let Some(old_current_file) = old_current_file {
stack.add_env_var("CURRENT_FILE".to_string(), old_current_file.clone());
} else {
stack.remove_env_var(engine_state, "CURRENT_FILE");
}
return_result
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Runs foo.nu in the current context",
example: r#"source foo.nu"#,
result: None,
},
Example {
description: "Runs foo.nu in current context and call the command defined, suppose foo.nu has content: `def say-hi [] { echo 'Hi!' }`",
example: r#"source ./foo.nu; say-hi"#,
result: None,
},
Example {
description: "Sourcing `null` is a no-op.",
example: r#"source null"#,
result: None,
},
Example {
description: "Source can be used with const variables.",
example: r#"const file = if $nu.is-interactive { "interactive.nu" } else { null }; source $file"#,
result: None,
},
]
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/misc/panic.rs | crates/nu-command/src/misc/panic.rs | use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct Panic;
impl Command for Panic {
fn name(&self) -> &str {
"panic"
}
fn description(&self) -> &str {
"Causes nushell to panic."
}
fn search_terms(&self) -> Vec<&str> {
vec!["crash", "throw"]
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build("panic")
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
.optional(
"msg",
SyntaxShape::String,
"The custom message for the panic.",
)
.category(Category::Debug)
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let maybe_msg: String = call
.opt(engine_state, stack, 0)?
.unwrap_or("Panic!".to_string());
panic!("{}", maybe_msg)
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
description: "Panic with a custom message",
example: "panic 'This is a custom panic message'",
result: None,
}]
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/misc/tutor.rs | crates/nu-command/src/misc/tutor.rs | use itertools::Itertools;
use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct Tutor;
impl Command for Tutor {
fn name(&self) -> &str {
"tutor"
}
fn signature(&self) -> Signature {
Signature::build("tutor")
.input_output_types(vec![(Type::Nothing, Type::String)])
.allow_variants_without_examples(true)
.optional(
"search",
SyntaxShape::String,
"Item to search for, or 'list' to list available tutorials.",
)
.named(
"find",
SyntaxShape::String,
"Search tutorial for a phrase",
Some('f'),
)
.category(Category::Misc)
}
fn description(&self) -> &str {
"Run the tutorial. To begin, run: tutor."
}
fn search_terms(&self) -> Vec<&str> {
vec!["help", "learn", "tutorial"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
tutor(engine_state, stack, call)
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Begin the tutorial",
example: "tutor begin",
result: None,
},
Example {
description: "Search a tutorial by phrase",
example: "tutor --find \"$in\"",
result: None,
},
]
}
}
fn tutor(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
) -> Result<PipelineData, ShellError> {
let span = call.head;
let search: Option<String> = call.opt(engine_state, stack, 0).unwrap_or(None);
let find: Option<String> = call.get_flag(engine_state, stack, "find")?;
let notes = "You can learn about a topic using `tutor` followed by the name of the topic.\nFor example: `tutor table` to open the table topic.\n\n";
let search_space = [
(vec!["begin"], begin_tutor()),
(
vec!["table", "tables", "row", "rows", "column", "columns"],
table_tutor(),
),
(vec!["cell", "cells"], cell_tutor()),
(
vec![
"expr",
"exprs",
"expressions",
"subexpression",
"subexpressions",
"sub-expression",
"sub-expressions",
],
expression_tutor(),
),
(vec!["echo"], echo_tutor()),
(vec!["each", "iteration", "iter"], each_tutor()),
(
vec!["var", "vars", "variable", "variables"],
variable_tutor(),
),
(vec!["block", "blocks"], block_tutor()),
(vec!["shorthand", "shorthands"], shorthand_tutor()),
];
if let Some(find) = find {
let mut results = vec![];
for search_group in search_space {
if search_group.1.contains(&find) {
results.push(search_group.0[0].to_string())
}
}
let message = format!(
"You can find '{find}' in the following topics:\n\n{}\n\n{notes}",
results.into_iter().map(|x| format!("- {x}")).join("\n")
);
return Ok(display(&message, engine_state, stack, span));
} else if let Some(search) = search {
if search == "list" {
let results = search_space.map(|s| s.0[0].to_string());
let message = format!(
"This tutorial contains the following topics:\n\n{}\n\n{notes}",
results.map(|x| format!("- {x}")).join("\n")
);
return Ok(display(&message, engine_state, stack, span));
}
for search_group in search_space {
if search_group.0.contains(&search.as_str()) {
return Ok(display(search_group.1, engine_state, stack, span));
}
}
}
Ok(display(default_tutor(), engine_state, stack, span))
}
fn default_tutor() -> &'static str {
r#"
Welcome to the Nushell tutorial!
With the `tutor` command, you'll be able to learn a lot about how Nushell
works along with many fun tips and tricks to speed up everyday tasks.
To get started, you can use `tutor begin`, and to see all the available
tutorials just run `tutor list`.
"#
}
fn begin_tutor() -> &'static str {
r#"
Nushell is a structured shell and programming language. One way to begin
using it is to try a few of the commands.
The first command to try is `ls`. The `ls` command will show you a list
of the files in the current directory. Notice that these files are shown
as a table. Each column of this table not only tells us what is being
shown, but also gives us a way to work with the data.
You can combine the `ls` command with other commands using the pipeline
symbol '|'. This allows data to flow from one command to the next.
For example, if we only wanted the name column, we could do:
```
ls | select name
```
Notice that we still get a table, but this time it only has one column:
the name column.
You can continue to learn more about tables by running:
```
tutor tables
```
If at any point, you'd like to restart this tutorial, you can run:
```
tutor begin
```
"#
}
fn table_tutor() -> &'static str {
r#"
The most common form of data in Nushell is the table. Tables contain rows and
columns of data. In each cell of the table, there is data that you can access
using Nushell commands.
To get the 3rd row in the table, you can use the `select` command:
```
ls | select 2
```
This will get the 3rd (note that `select` is zero-based) row in the table created
by the `ls` command. You can use `select` on any table created by other commands
as well.
You can also access the column of data in one of two ways. If you want
to keep the column as part of a new table, you can use `select`.
```
ls | select name
```
This runs `ls` and returns only the "name" column of the table.
If, instead, you'd like to get access to the values inside of the column, you
can use the `get` command.
```
ls | get name
```
This allows us to get to the list of strings that are the filenames rather
than having a full table. In some cases, this can make the names easier to
work with.
You can continue to learn more about working with cells of the table by
running:
```
tutor cells
```
"#
}
fn cell_tutor() -> &'static str {
r#"
Working with cells of data in the table is a key part of working with data in
Nushell. Because of this, there is a rich list of commands to work with cells
as well as handy shorthands for accessing cells.
Cells can hold simple values like strings and numbers, or more complex values
like lists and tables.
To reach a cell of data from a table, you can combine a row operation and a
column operation.
```
ls | select 4 | get name
```
You can combine these operations into one step using a shortcut.
```
(ls).4.name
```
Names/strings represent columns names and numbers represent row numbers.
The `(ls)` is a form of expression. You can continue to learn more about
expressions by running:
```
tutor expressions
```
You can also learn about these cell shorthands by running:
```
tutor shorthands
```
"#
}
fn expression_tutor() -> &'static str {
r#"
Expressions give you the power to mix calls to commands with math. The
simplest expression is a single value like a string or number.
```
3
```
Expressions can also include math operations like addition or division.
```
10 / 2
```
Normally, an expression is one type of operation: math or commands. You can
mix these types by using subexpressions. Subexpressions are just like
expressions, but they're wrapped in parentheses `()`.
```
10 * (3 + 4)
```
Here we use parentheses to create a higher math precedence in the math
expression.
```
echo (2 + 3)
```
You can continue to learn more about the `echo` command by running:
```
tutor echo
```
"#
}
fn echo_tutor() -> &'static str {
r#"
The `echo` command in Nushell is a powerful tool for not only seeing values,
but also for creating new ones.
```
echo "Hello"
```
You can echo output. This output, if it's not redirected using a "|" pipeline
will be displayed to the screen.
```
echo 1..10
```
You can also use echo to work with individual values of a range. In this
example, `echo` will create the values from 1 to 10 as a list.
```
echo 1 2 3 4 5
```
You can also create lists of values by passing `echo` multiple arguments.
This can be helpful if you want to later processes these values.
The `echo` command can pair well with the `each` command which can run
code on each row, or item, of input.
You can continue to learn more about the `each` command by running:
```
tutor each
```
"#
}
fn each_tutor() -> &'static str {
r#"
The `each` command gives us a way of working with the individual elements
(sometimes called 'rows') of a list one at a time. It reads these in from
the pipeline and runs a block on each one. A block is a group of pipelines.
```
echo 1 2 3 | each { |it| $it + 10}
```
This example iterates over each element sent by `echo`, giving us three new
values that are the original value + 10. Here, the `$it` is a variable that
is the name given to the block's parameter by default.
You can learn more about blocks by running:
```
tutor blocks
```
You can also learn more about variables by running:
```
tutor variables
```
"#
}
fn variable_tutor() -> &'static str {
r#"
Variables are an important way to store values to be used later. To create a
variable, you can use the `let` keyword. The `let` command will create a
variable and then assign it a value in one step.
```
let $x = 3
```
Once created, we can refer to this variable by name.
```
$x
```
Nushell also comes with built-in variables. The `$nu` variable is a reserved
variable that contains a lot of information about the currently running
instance of Nushell. The `$it` variable is the name given to block parameters
if you don't specify one. And `$in` is the variable that allows you to work
with all of the data coming in from the pipeline in one place.
"#
}
fn block_tutor() -> &'static str {
r#"
Blocks are a special form of expression that hold code to be run at a later
time. Often, you'll see blocks as one of the arguments given to commands
like `each` and `if`.
```
ls | each {|x| $x.name}
```
The above will create a list of the filenames in the directory.
```
if true { echo "it's true" } else { echo "it's not true" }
```
This `if` call will run the first block if the expression is true, or the
second block if the expression is false.
"#
}
fn shorthand_tutor() -> &'static str {
r#"
You can access data in a structure via a shorthand notation called a "cell path",
sometimes called a "column path". These paths allow you to go from a structure to
rows, columns, or cells inside of the structure.
Shorthand paths are made from rows numbers, column names, or both. You can use
them on any variable or subexpression.
```
$env.PWD
```
The above accesses the built-in `$env` variable, gets its table, and then uses
the shorthand path to retrieve only the cell data inside the "PWD" column.
```
(ls).name.4
```
This will retrieve the cell data in the "name" column on the 5th row (note:
row numbers are zero-based).
For tables, rows and columns don't need to come in any specific order. You can
produce the same value using:
```
(ls).4.name
```
"#
}
fn display(help: &str, engine_state: &EngineState, stack: &mut Stack, span: Span) -> PipelineData {
let help = help.split('`');
let mut build = String::new();
let mut code_mode = false;
for item in help {
if code_mode {
code_mode = false;
//TODO: support no-color mode
if let Some(highlighter) = engine_state.find_decl(b"nu-highlight", &[]) {
let decl = engine_state.get_decl(highlighter);
let result = decl.run(
engine_state,
stack,
&Call::new(span),
Value::string(item, Span::unknown()).into_pipeline_data(),
);
if let Ok(value) = result.and_then(|data| data.into_value(Span::unknown())) {
match value.coerce_into_string() {
Ok(s) => {
build.push_str(&s);
}
_ => {
build.push_str(item);
}
}
}
}
} else {
code_mode = true;
build.push_str(item);
}
}
Value::string(build, span).into_pipeline_data()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(Tutor)
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/misc/mod.rs | crates/nu-command/src/misc/mod.rs | mod panic;
mod source;
mod tutor;
mod unlet;
pub use panic::Panic;
pub use source::Source;
pub use tutor::Tutor;
pub use unlet::DeleteVar;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/misc/unlet.rs | crates/nu-command/src/misc/unlet.rs | use nu_engine::command_prelude::*;
use nu_protocol::engine::{ENV_VARIABLE_ID, IN_VARIABLE_ID, NU_VARIABLE_ID};
#[derive(Clone)]
pub struct DeleteVar;
impl Command for DeleteVar {
fn name(&self) -> &str {
"unlet"
}
fn description(&self) -> &str {
"Delete variables from nushell memory, making them unrecoverable."
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build("unlet")
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
.rest(
"rest",
SyntaxShape::Any,
"The variables to delete (pass as $variable_name).",
)
.category(Category::Experimental)
}
fn run(
&self,
_engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
// Collect all positional arguments passed to the command
let expressions: Vec<_> = (0..).map_while(|i| call.positional_nth(stack, i)).collect();
// Ensure at least one argument is provided
if expressions.is_empty() {
return Err(ShellError::GenericError {
error: "Wrong number of arguments".into(),
msg: "unlet takes at least one argument".into(),
span: Some(call.head),
help: None,
inner: vec![],
});
}
// Validate each argument and collect valid variable IDs
let mut var_ids = Vec::with_capacity(expressions.len());
for expr in expressions {
match &expr.expr {
nu_protocol::ast::Expr::Var(var_id) => {
// Prevent deletion of built-in variables that are essential for nushell operation
if var_id == &NU_VARIABLE_ID
|| var_id == &ENV_VARIABLE_ID
|| var_id == &IN_VARIABLE_ID
{
// Determine the variable name for the error message
let var_name = match *var_id {
NU_VARIABLE_ID => "nu",
ENV_VARIABLE_ID => "env",
IN_VARIABLE_ID => "in",
_ => "unknown", // This should never happen due to the check above
};
return Err(ShellError::GenericError {
error: "Cannot delete built-in variable".into(),
msg: format!(
"'${}' is a built-in variable and cannot be deleted",
var_name
),
span: Some(expr.span),
help: None,
inner: vec![],
});
}
var_ids.push(*var_id);
}
_ => {
// Argument is not a variable reference
return Err(ShellError::GenericError {
error: "Not a variable".into(),
msg: "Argument must be a variable reference like $x".into(),
span: Some(expr.span),
help: Some("Use $variable_name to refer to the variable".into()),
inner: vec![],
});
}
}
}
// Remove all valid variables from the stack
for var_id in var_ids {
stack.remove_var(var_id);
}
Ok(PipelineData::empty())
}
fn requires_ast_for_arguments(&self) -> bool {
true
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
example: "let x = 42; unlet $x",
description: "Delete a variable from memory",
result: None,
},
Example {
example: "let x = 1; let y = 2; unlet $x $y",
description: "Delete multiple variables from memory",
result: None,
},
Example {
example: "unlet $nu",
description: "Attempting to delete a built-in variable fails",
result: None,
},
Example {
example: "unlet 42",
description: "Attempting to delete a non-variable fails",
result: None,
},
]
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/env/with_env.rs | crates/nu-command/src/env/with_env.rs | use nu_engine::{command_prelude::*, eval_block};
use nu_protocol::{debugger::WithoutDebug, engine::Closure};
#[derive(Clone)]
pub struct WithEnv;
impl Command for WithEnv {
fn name(&self) -> &str {
"with-env"
}
fn signature(&self) -> Signature {
Signature::build("with-env")
.input_output_types(vec![(Type::Any, Type::Any)])
.required(
"variable",
SyntaxShape::Any,
"The environment variable to temporarily set.",
)
.required(
"block",
SyntaxShape::Closure(None),
"The block to run once the variable is set.",
)
.category(Category::Env)
}
fn description(&self) -> &str {
"Runs a block with an environment variable set."
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
with_env(engine_state, stack, call, input)
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
description: "Set by key-value record",
example: r#"with-env {X: "Y", W: "Z"} { [$env.X $env.W] }"#,
result: Some(Value::list(
vec![Value::test_string("Y"), Value::test_string("Z")],
Span::test_data(),
)),
}]
}
}
fn with_env(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let env: Record = call.req(engine_state, stack, 0)?;
let capture_block: Closure = call.req(engine_state, stack, 1)?;
let block = engine_state.get_block(capture_block.block_id);
let mut stack = stack.captures_to_stack_preserve_out_dest(capture_block.captures);
// TODO: factor list of prohibited env vars into common place
for prohibited in ["PWD", "FILE_PWD", "CURRENT_FILE"] {
if env.contains(prohibited) {
return Err(ShellError::AutomaticEnvVarSetManually {
envvar_name: prohibited.into(),
span: call.head,
});
}
}
for (k, v) in env {
stack.add_env_var(k, v);
}
eval_block::<WithoutDebug>(engine_state, &mut stack, block, input).map(|p| p.body)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(WithEnv {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/env/mod.rs | crates/nu-command/src/env/mod.rs | mod config;
mod export_env;
mod load_env;
mod source_env;
mod with_env;
pub use config::ConfigEnv;
pub use config::ConfigFlatten;
pub use config::ConfigMeta;
pub use config::ConfigNu;
pub use config::ConfigReset;
pub use config::ConfigUseColors;
pub use export_env::ExportEnv;
pub use load_env::LoadEnv;
pub use source_env::SourceEnv;
pub use with_env::WithEnv;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/env/export_env.rs | crates/nu-command/src/env/export_env.rs | use nu_engine::{command_prelude::*, get_eval_block, redirect_env};
use nu_protocol::engine::CommandType;
#[derive(Clone)]
pub struct ExportEnv;
impl Command for ExportEnv {
fn name(&self) -> &str {
"export-env"
}
fn signature(&self) -> Signature {
Signature::build("export-env")
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
.required(
"block",
SyntaxShape::Block,
"The block to run to set the environment.",
)
.category(Category::Env)
}
fn description(&self) -> &str {
"Run a block and preserve its environment in a current scope."
}
fn extra_description(&self) -> &str {
r#"This command is a parser keyword. For details, check:
https://www.nushell.sh/book/thinking_in_nu.html"#
}
fn command_type(&self) -> CommandType {
CommandType::Keyword
}
fn requires_ast_for_arguments(&self) -> bool {
true
}
fn run(
&self,
engine_state: &EngineState,
caller_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let block_id = call
.positional_nth(caller_stack, 0)
.expect("checked through parser")
.as_block()
.expect("internal error: missing block");
let block = engine_state.get_block(block_id);
let mut callee_stack = caller_stack
.gather_captures(engine_state, &block.captures)
.reset_pipes();
let eval_block = get_eval_block(engine_state);
// Run the block (discard the result)
let _ = eval_block(engine_state, &mut callee_stack, block, input)?;
// Merge the block's environment to the current stack
redirect_env(engine_state, caller_stack, &callee_stack);
Ok(PipelineData::empty())
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Set an environment variable",
example: r#"export-env { $env.SPAM = 'eggs' }"#,
result: Some(Value::nothing(Span::test_data())),
},
Example {
description: "Set an environment variable and examine its value",
example: r#"export-env { $env.SPAM = 'eggs' }; $env.SPAM"#,
result: Some(Value::test_string("eggs")),
},
]
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(ExportEnv {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/env/source_env.rs | crates/nu-command/src/env/source_env.rs | use nu_engine::{
command_prelude::*, find_in_dirs_env, get_dirs_var_from_call, get_eval_block_with_early_return,
redirect_env,
};
use nu_protocol::{
BlockId,
engine::CommandType,
shell_error::{self, io::IoError},
};
use std::path::PathBuf;
/// Source a file for environment variables.
#[derive(Clone)]
pub struct SourceEnv;
impl Command for SourceEnv {
fn name(&self) -> &str {
"source-env"
}
fn signature(&self) -> Signature {
Signature::build("source-env")
.input_output_types(vec![(Type::Any, Type::Any)])
.required(
"filename",
SyntaxShape::OneOf(vec![SyntaxShape::String, SyntaxShape::Nothing]), // type is string to avoid automatically canonicalizing the path
"The filepath to the script file to source the environment from (`null` for no-op).",
)
.category(Category::Core)
}
fn description(&self) -> &str {
"Source the environment from a source file into the current environment."
}
fn extra_description(&self) -> &str {
r#"This command is a parser keyword. For details, check:
https://www.nushell.sh/book/thinking_in_nu.html"#
}
fn command_type(&self) -> CommandType {
CommandType::Keyword
}
fn run(
&self,
engine_state: &EngineState,
caller_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
if call.get_parser_info(caller_stack, "noop").is_some() {
return Ok(PipelineData::empty());
}
let source_filename: Spanned<String> = call.req(engine_state, caller_stack, 0)?;
// Note: this hidden positional is the block_id that corresponded to the 0th position
// it is put here by the parser
let block_id: i64 = call.req_parser_info(engine_state, caller_stack, "block_id")?;
let block_id = BlockId::new(block_id as usize);
// Set the currently evaluated directory (file-relative PWD)
let file_path = if let Some(path) = find_in_dirs_env(
&source_filename.item,
engine_state,
caller_stack,
get_dirs_var_from_call(caller_stack, call),
)? {
PathBuf::from(&path)
} else {
return Err(ShellError::Io(IoError::new(
shell_error::io::ErrorKind::FileNotFound,
source_filename.span,
PathBuf::from(source_filename.item),
)));
};
if let Some(parent) = file_path.parent() {
let file_pwd = Value::string(parent.to_string_lossy(), call.head);
caller_stack.add_env_var("FILE_PWD".to_string(), file_pwd);
}
caller_stack.add_env_var(
"CURRENT_FILE".to_string(),
Value::string(file_path.to_string_lossy(), call.head),
);
// Evaluate the block
let block = engine_state.get_block(block_id).clone();
let mut callee_stack = caller_stack
.gather_captures(engine_state, &block.captures)
.reset_pipes();
let eval_block_with_early_return = get_eval_block_with_early_return(engine_state);
let result = eval_block_with_early_return(engine_state, &mut callee_stack, &block, input)
.map(|p| p.body);
// Merge the block's environment to the current stack
redirect_env(engine_state, caller_stack, &callee_stack);
// Remove the file-relative PWD
caller_stack.remove_env_var(engine_state, "FILE_PWD");
caller_stack.remove_env_var(engine_state, "CURRENT_FILE");
result
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Sources the environment from foo.nu in the current context",
example: r#"source-env foo.nu"#,
result: None,
},
Example {
description: "Sourcing `null` is a no-op.",
example: r#"source-env null"#,
result: None,
},
]
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/env/load_env.rs | crates/nu-command/src/env/load_env.rs | use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct LoadEnv;
impl Command for LoadEnv {
fn name(&self) -> &str {
"load-env"
}
fn description(&self) -> &str {
"Loads an environment update from a record."
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build("load-env")
.input_output_types(vec![
(Type::record(), Type::Nothing),
(Type::Nothing, Type::Nothing),
// FIXME Type::Any input added to disable pipeline input type checking, as run-time checks can raise undesirable type errors
// which aren't caught by the parser. see https://github.com/nushell/nushell/pull/14922 for more details
(Type::Any, Type::Nothing),
])
.allow_variants_without_examples(true)
.optional(
"update",
SyntaxShape::Record(vec![]),
"The record to use for updates.",
)
.category(Category::FileSystem)
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let arg: Option<Record> = call.opt(engine_state, stack, 0)?;
let span = call.head;
let record = match arg {
Some(record) => record,
None => match input {
PipelineData::Value(Value::Record { val, .. }, ..) => val.into_owned(),
_ => {
return Err(ShellError::UnsupportedInput {
msg: "'load-env' expects a single record".into(),
input: "value originated from here".into(),
msg_span: span,
input_span: input.span().unwrap_or(span),
});
}
},
};
for prohibited in ["FILE_PWD", "CURRENT_FILE", "PWD"] {
if record.contains(prohibited) {
return Err(ShellError::AutomaticEnvVarSetManually {
envvar_name: prohibited.to_string(),
span: call.head,
});
}
}
for (env_var, rhs) in record {
stack.add_env_var(env_var, rhs);
}
Ok(PipelineData::empty())
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Load variables from an input stream",
example: r#"{NAME: ABE, AGE: UNKNOWN} | load-env; $env.NAME"#,
result: Some(Value::test_string("ABE")),
},
Example {
description: "Load variables from an argument",
example: r#"load-env {NAME: ABE, AGE: UNKNOWN}; $env.NAME"#,
result: Some(Value::test_string("ABE")),
},
]
}
}
#[cfg(test)]
mod tests {
use super::LoadEnv;
#[test]
fn examples_work_as_expected() {
use crate::test_examples;
test_examples(LoadEnv {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/env/config/config_nu.rs | crates/nu-command/src/env/config/config_nu.rs | use nu_engine::command_prelude::*;
use nu_utils::ConfigFileKind;
#[derive(Clone)]
pub struct ConfigNu;
impl Command for ConfigNu {
fn name(&self) -> &str {
"config nu"
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.category(Category::Env)
.input_output_types(vec![(Type::Nothing, Type::Any)])
.switch(
"default",
"Print the internal default `config.nu` file instead.",
Some('d'),
)
.switch(
"doc",
"Print a commented `config.nu` with documentation instead.",
Some('s'),
)
}
fn description(&self) -> &str {
"Edit nu configurations."
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "open user's config.nu in the default editor",
example: "config nu",
result: None,
},
Example {
description: "pretty-print a commented `config.nu` that explains common settings",
example: "config nu --doc | nu-highlight",
result: None,
},
Example {
description: "pretty-print the internal `config.nu` file which is loaded before user's config",
example: "config nu --default | nu-highlight",
result: None,
},
]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
super::config_::handle_call(ConfigFileKind::Config, engine_state, stack, call)
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/env/config/config_env.rs | crates/nu-command/src/env/config/config_env.rs | use nu_engine::command_prelude::*;
use nu_utils::ConfigFileKind;
#[derive(Clone)]
pub struct ConfigEnv;
impl Command for ConfigEnv {
fn name(&self) -> &str {
"config env"
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.category(Category::Env)
.input_output_types(vec![(Type::Nothing, Type::Any)])
.switch(
"default",
"Print the internal default `env.nu` file instead.",
Some('d'),
)
.switch(
"doc",
"Print a commented `env.nu` with documentation instead.",
Some('s'),
)
// TODO: Signature narrower than what run actually supports theoretically
}
fn description(&self) -> &str {
"Edit nu environment configurations."
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "open user's env.nu in the default editor",
example: "config env",
result: None,
},
Example {
description: "pretty-print a commented `env.nu` that explains common settings",
example: "config env --doc | nu-highlight,",
result: None,
},
Example {
description: "pretty-print the internal `env.nu` file which is loaded before the user's environment",
example: "config env --default | nu-highlight,",
result: None,
},
]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
super::config_::handle_call(ConfigFileKind::Env, engine_state, stack, call)
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/env/config/config_flatten.rs | crates/nu-command/src/env/config/config_flatten.rs | use nu_engine::command_prelude::*;
use nu_utils::JsonFlattener; // Ensure this import is present // Ensure this import is present
#[derive(Clone)]
pub struct ConfigFlatten;
impl Command for ConfigFlatten {
fn name(&self) -> &str {
"config flatten"
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.category(Category::Debug)
.input_output_types(vec![(Type::Nothing, Type::record())])
}
fn description(&self) -> &str {
"Show the current configuration in a flattened form."
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
description: "Show the current configuration in a flattened form",
example: "config flatten",
result: None,
}]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
// Get the Config instance from the stack
let config = stack.get_config(engine_state);
// Serialize the Config instance to JSON
let serialized_config =
serde_json::to_value(&*config).map_err(|err| ShellError::GenericError {
error: format!("Failed to serialize config to json: {err}"),
msg: "".into(),
span: Some(call.head),
help: None,
inner: vec![],
})?;
// Create a JsonFlattener instance with appropriate arguments
let flattener = JsonFlattener {
separator: ".",
alt_array_flattening: false,
preserve_arrays: true,
};
// Flatten the JSON value
let flattened_config_str = flattener.flatten(&serialized_config).to_string();
let flattened_values =
convert_string_to_value(&flattened_config_str, engine_state, call.head)?;
Ok(flattened_values.into_pipeline_data())
}
}
// From here below is taken from `from json`. Would be nice to have a nu-utils-value crate that could be shared
fn convert_string_to_value(
string_input: &str,
engine_state: &EngineState,
span: Span,
) -> Result<Value, ShellError> {
match nu_json::from_str(string_input) {
Ok(value) => Ok(convert_nujson_to_value(None, value, engine_state, span)),
Err(x) => match x {
nu_json::Error::Syntax(_, row, col) => {
let label = x.to_string();
let label_span = Span::from_row_column(row, col, string_input);
Err(ShellError::GenericError {
error: "Error while parsing JSON text".into(),
msg: "error parsing JSON text".into(),
span: Some(span),
help: None,
inner: vec![ShellError::OutsideSpannedLabeledError {
src: string_input.into(),
error: "Error while parsing JSON text".into(),
msg: label,
span: label_span,
}],
})
}
x => Err(ShellError::CantConvert {
to_type: format!("structured json data ({x})"),
from_type: "string".into(),
span,
help: None,
}),
},
}
}
fn convert_nujson_to_value(
key: Option<String>,
value: nu_json::Value,
engine_state: &EngineState,
span: Span,
) -> Value {
match value {
nu_json::Value::Array(array) => Value::list(
array
.into_iter()
.map(|x| convert_nujson_to_value(key.clone(), x, engine_state, span))
.collect(),
span,
),
nu_json::Value::Bool(b) => Value::bool(b, span),
nu_json::Value::F64(f) => Value::float(f, span),
nu_json::Value::I64(i) => {
if let Some(closure_str) = expand_closure(key.clone(), i, engine_state) {
Value::string(closure_str, span)
} else {
Value::int(i, span)
}
}
nu_json::Value::Null => Value::nothing(span),
nu_json::Value::Object(k) => Value::record(
k.into_iter()
.map(|(k, v)| {
let mut key = k.clone();
// Keep .Closure.val and .block_id as part of the key during conversion to value
let value = convert_nujson_to_value(Some(key.clone()), v, engine_state, span);
// Replace .Closure.val and .block_id from the key after the conversion
if key.contains(".Closure.val") || key.contains(".block_id") {
key = key.replace(".Closure.val", "").replace(".block_id", "");
}
(key, value)
})
.collect(),
span,
),
nu_json::Value::U64(u) => {
if u > i64::MAX as u64 {
Value::error(
ShellError::CantConvert {
to_type: "i64 sized integer".into(),
from_type: "value larger than i64".into(),
span,
help: None,
},
span,
)
} else if let Some(closure_str) = expand_closure(key.clone(), u as i64, engine_state) {
Value::string(closure_str, span)
} else {
Value::int(u as i64, span)
}
}
nu_json::Value::String(s) => Value::string(s, span),
}
}
// If the block_id is a real block id, then it should expand into the closure contents, otherwise return None
fn expand_closure(
key: Option<String>,
block_id: i64,
engine_state: &EngineState,
) -> Option<String> {
match key {
Some(key) if key.contains(".Closure.val") || key.contains(".block_id") => engine_state
.try_get_block(nu_protocol::BlockId::new(block_id as usize))
.and_then(|block| block.span)
.map(|span| {
let contents = engine_state.get_span_contents(span);
String::from_utf8_lossy(contents).to_string()
}),
_ => None,
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/env/config/config_reset.rs | crates/nu-command/src/env/config/config_reset.rs | use chrono::Local;
use nu_engine::command_prelude::*;
use nu_utils::ConfigFileKind;
use std::{io::Write, path::PathBuf};
#[derive(Clone)]
pub struct ConfigReset;
impl Command for ConfigReset {
fn name(&self) -> &str {
"config reset"
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.switch("nu", "reset only nu config, config.nu", Some('n'))
.switch("env", "reset only env config, env.nu", Some('e'))
.switch("without-backup", "do not make a backup", Some('w'))
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
.allow_variants_without_examples(true)
.category(Category::Env)
}
fn description(&self) -> &str {
"Reset nushell environment configurations to default, and saves old config files in the config location as oldconfig.nu and oldenv.nu."
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
description: "reset nushell configuration files",
example: "config reset",
result: None,
}]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let only_nu = call.has_flag(engine_state, stack, "nu")?;
let only_env = call.has_flag(engine_state, stack, "env")?;
let no_backup = call.has_flag(engine_state, stack, "without-backup")?;
let span = call.head;
let Some(config_path) = nu_path::nu_config_dir() else {
return Err(ShellError::ConfigDirNotFound { span: call.head });
};
if !only_env {
let kind = ConfigFileKind::Config;
let mut nu_config = config_path.clone();
nu_config.push(kind.path());
let config_file = kind.scaffold();
if !no_backup {
let mut backup_path = config_path.clone();
backup_path.push(format!(
"oldconfig-{}.nu",
Local::now().format("%F-%H-%M-%S"),
));
if let Err(err) = std::fs::rename(nu_config.clone(), &backup_path) {
return Err(ShellError::Io(IoError::new_with_additional_context(
err.not_found_as(NotFound::Directory),
span,
PathBuf::from(backup_path),
"config.nu could not be backed up",
)));
}
}
if let Ok(mut file) = std::fs::File::create(&nu_config)
&& let Err(err) = writeln!(&mut file, "{config_file}")
{
return Err(ShellError::Io(IoError::new_with_additional_context(
err.not_found_as(NotFound::File),
span,
PathBuf::from(nu_config),
"config.nu could not be written to",
)));
}
}
if !only_nu {
let kind = ConfigFileKind::Env;
let mut env_config = config_path.clone();
env_config.push(kind.path());
let config_file = kind.scaffold();
if !no_backup {
let mut backup_path = config_path.clone();
backup_path.push(format!("oldenv-{}.nu", Local::now().format("%F-%H-%M-%S"),));
if let Err(err) = std::fs::rename(env_config.clone(), &backup_path) {
return Err(ShellError::Io(IoError::new_with_additional_context(
err.not_found_as(NotFound::Directory),
span,
PathBuf::from(backup_path),
"env.nu could not be backed up",
)));
}
}
if let Ok(mut file) = std::fs::File::create(&env_config)
&& let Err(err) = writeln!(&mut file, "{config_file}")
{
return Err(ShellError::Io(IoError::new_with_additional_context(
err.not_found_as(NotFound::File),
span,
PathBuf::from(env_config),
"env.nu could not be written to",
)));
}
}
Ok(PipelineData::empty())
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/env/config/config_.rs | crates/nu-command/src/env/config/config_.rs | use nu_cmd_base::util::get_editor;
use nu_engine::{command_prelude::*, env_to_strings, get_full_help};
use nu_protocol::{PipelineMetadata, shell_error::io::IoError};
use nu_system::ForegroundChild;
use nu_utils::ConfigFileKind;
#[cfg(feature = "os")]
use nu_protocol::process::PostWaitCallback;
#[derive(Clone)]
pub struct ConfigMeta;
impl Command for ConfigMeta {
fn name(&self) -> &str {
"config"
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.category(Category::Env)
.input_output_types(vec![(Type::Nothing, Type::String)])
}
fn description(&self) -> &str {
"Edit nushell configuration files."
}
fn extra_description(&self) -> &str {
"You must use one of the following subcommands. Using this command as-is will only produce this help message."
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
Ok(Value::string(get_full_help(self, engine_state, stack), call.head).into_pipeline_data())
}
fn search_terms(&self) -> Vec<&str> {
vec!["options", "setup"]
}
}
#[cfg(not(feature = "os"))]
pub(super) fn start_editor(
_: ConfigFileKind,
_: &EngineState,
_: &mut Stack,
call: &Call,
) -> Result<PipelineData, ShellError> {
Err(ShellError::DisabledOsSupport {
msg: "Running external commands is not available without OS support.".to_string(),
span: call.head,
})
}
#[cfg(feature = "os")]
pub(super) fn start_editor(
kind: ConfigFileKind,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
) -> Result<PipelineData, ShellError> {
// Find the editor executable.
let (editor_name, editor_args) = get_editor(engine_state, stack, call.head)?;
let paths = nu_engine::env::path_str(engine_state, stack, call.head)?;
let cwd = engine_state.cwd(Some(stack))?;
let editor_executable =
crate::which(&editor_name, &paths, cwd.as_ref()).ok_or(ShellError::ExternalCommand {
label: format!("`{editor_name}` not found"),
help: "Failed to find the editor executable".into(),
span: call.head,
})?;
let nu_const_path = kind.nu_const_path();
let Some(config_path) = engine_state.get_config_path(nu_const_path) else {
return Err(ShellError::GenericError {
error: format!("Could not find $nu.{nu_const_path}"),
msg: format!("Could not find $nu.{nu_const_path}"),
span: None,
help: None,
inner: vec![],
});
};
let config_path = config_path.to_string_lossy().to_string();
// Create the command.
let mut command = std::process::Command::new(editor_executable);
// Configure PWD.
command.current_dir(cwd);
// Configure environment variables.
let envs = env_to_strings(engine_state, stack)?;
command.env_clear();
command.envs(envs);
// Configure args.
command.args(editor_args);
command.arg(config_path);
// Spawn the child process. On Unix, also put the child process to
// foreground if we're in an interactive session.
#[cfg(windows)]
let child = ForegroundChild::spawn(command);
#[cfg(unix)]
let child = ForegroundChild::spawn(
command,
engine_state.is_interactive,
engine_state.is_background_job(),
&engine_state.pipeline_externals_state,
);
let child = child.map_err(|err| {
IoError::new_with_additional_context(
err,
call.head,
None,
"Could not spawn foreground child",
)
})?;
let post_wait_callback = PostWaitCallback::for_job_control(engine_state, None, None);
// Wrap the output into a `PipelineData::byte_stream`.
let child = nu_protocol::process::ChildProcess::new(
child,
None,
false,
call.head,
Some(post_wait_callback),
)?;
Ok(PipelineData::byte_stream(
ByteStream::child(child, call.head),
None,
))
}
pub(super) fn handle_call(
kind: ConfigFileKind,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
) -> Result<PipelineData, ShellError> {
let default_flag = call.has_flag(engine_state, stack, "default")?;
let doc_flag = call.has_flag(engine_state, stack, "doc")?;
Ok(match (default_flag, doc_flag) {
(false, false) => {
return super::config_::start_editor(kind, engine_state, stack, call);
}
(true, true) => {
return Err(ShellError::IncompatibleParameters {
left_message: "can't use `--default` at the same time".into(),
left_span: call.get_flag_span(stack, "default").expect("has flag"),
right_message: "because of `--doc`".into(),
right_span: call.get_flag_span(stack, "doc").expect("has flag"),
});
}
(true, false) => kind.default(),
(false, true) => kind.doc(),
}
.into_value(call.head)
.into_pipeline_data_with_metadata(
PipelineMetadata::default().with_content_type(Some("application/x-nuscript".into())),
))
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/env/config/config_use_colors.rs | crates/nu-command/src/env/config/config_use_colors.rs | use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct ConfigUseColors;
impl Command for ConfigUseColors {
fn name(&self) -> &str {
"config use-colors"
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.category(Category::Env)
.input_output_type(Type::Nothing, Type::Bool)
}
fn description(&self) -> &str {
"Get the configuration for color output."
}
fn extra_description(&self) -> &str {
r#"Use this command instead of checking `$env.config.use_ansi_coloring` to properly handle the "auto" setting, including environment variables that influence its behavior."#
}
fn search_terms(&self) -> Vec<&str> {
vec!["ansi"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let use_ansi_coloring = stack
.get_config(engine_state)
.use_ansi_coloring
.get(engine_state);
Ok(PipelineData::value(
Value::bool(use_ansi_coloring, call.head),
None,
))
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/env/config/mod.rs | crates/nu-command/src/env/config/mod.rs | mod config_;
mod config_env;
mod config_flatten;
mod config_nu;
mod config_reset;
mod config_use_colors;
pub use config_::ConfigMeta;
pub use config_env::ConfigEnv;
pub use config_flatten::ConfigFlatten;
pub use config_nu::ConfigNu;
pub use config_reset::ConfigReset;
pub use config_use_colors::ConfigUseColors;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/stor/open.rs | crates/nu-command/src/stor/open.rs | use crate::database::{MEMORY_DB, SQLiteDatabase};
use nu_engine::command_prelude::*;
use nu_protocol::Signals;
#[derive(Clone)]
pub struct StorOpen;
impl Command for StorOpen {
fn name(&self) -> &str {
"stor open"
}
fn signature(&self) -> Signature {
Signature::build("stor open")
.input_output_types(vec![(
Type::Nothing,
Type::Custom("sqlite-in-memory".into()),
)])
.allow_variants_without_examples(true)
.category(Category::Database)
}
fn description(&self) -> &str {
"Opens the in-memory sqlite database."
}
fn search_terms(&self) -> Vec<&str> {
vec!["sqlite", "storing", "access"]
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
description: "Open the in-memory sqlite database",
example: "stor open",
result: None,
}]
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
// eprintln!("Initializing nudb");
// eprintln!("Here's some things to try:");
// eprintln!("* stor open | schema | table -e");
// eprintln!("* stor open | query db 'insert into nudb (bool1,int1,float1,str1,datetime1) values (2,200,2.0,'str2','1969-04-17T06:00:00-05:00')'");
// eprintln!("* stor open | query db 'select * from nudb'");
// eprintln!("Now imagine all those examples happening as commands, without sql, in our normal nushell pipelines\n");
// TODO: Think about adding the following functionality
// * stor open --table-name my_table_name
// It returns the output of `select * from my_table_name`
// Just create an empty database with MEMORY_DB and nothing else
let db = Box::new(SQLiteDatabase::new(
std::path::Path::new(MEMORY_DB),
Signals::empty(),
));
// dbg!(db.clone());
Ok(db.into_value(call.head).into_pipeline_data())
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(StorOpen {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/stor/stor_.rs | crates/nu-command/src/stor/stor_.rs | use nu_engine::{command_prelude::*, get_full_help};
#[derive(Clone)]
pub struct Stor;
impl Command for Stor {
fn name(&self) -> &str {
"stor"
}
fn signature(&self) -> Signature {
Signature::build("stor")
.category(Category::Database)
.input_output_types(vec![(Type::Nothing, Type::String)])
}
fn description(&self) -> &str {
"Various commands for working with the in-memory sqlite database."
}
fn extra_description(&self) -> &str {
"You must use one of the following subcommands. Using this command as-is will only produce this help message."
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
Ok(Value::string(get_full_help(self, engine_state, stack), call.head).into_pipeline_data())
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/stor/insert.rs | crates/nu-command/src/stor/insert.rs | use crate::database::{MEMORY_DB, SQLiteDatabase, values_to_sql};
use nu_engine::command_prelude::*;
use nu_protocol::Signals;
use rusqlite::params_from_iter;
#[derive(Clone)]
pub struct StorInsert;
impl Command for StorInsert {
fn name(&self) -> &str {
"stor insert"
}
fn signature(&self) -> Signature {
Signature::build("stor insert")
.input_output_types(vec![
(Type::Nothing, Type::table()),
(Type::record(), Type::table()),
(Type::table(), Type::table()),
// FIXME Type::Any input added to disable pipeline input type checking, as run-time checks can raise undesirable type errors
// which aren't caught by the parser. see https://github.com/nushell/nushell/pull/14922 for more details
(Type::Any, Type::table()),
])
.required_named(
"table-name",
SyntaxShape::String,
"name of the table you want to insert into",
Some('t'),
)
.named(
"data-record",
SyntaxShape::Record(vec![]),
"a record of column names and column values to insert into the specified table",
Some('d'),
)
.allow_variants_without_examples(true)
.category(Category::Database)
}
fn description(&self) -> &str {
"Insert information into a specified table in the in-memory sqlite database."
}
fn search_terms(&self) -> Vec<&str> {
vec!["sqlite", "storing", "table", "saving"]
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Insert data in the in-memory sqlite database using a data-record of column-name and column-value pairs",
example: "stor insert --table-name nudb --data-record {bool1: true, int1: 5, float1: 1.1, str1: fdncred, datetime1: 2023-04-17}",
result: None,
},
Example {
description: "Insert data through pipeline input as a record of column-name and column-value pairs",
example: "{bool1: true, int1: 5, float1: 1.1, str1: fdncred, datetime1: 2023-04-17} | stor insert --table-name nudb",
result: None,
},
Example {
description: "Insert data through pipeline input as a table literal",
example: "[[bool1 int1 float1]; [true 5 1.1], [false 8 3.14]] | stor insert --table-name nudb",
result: None,
},
Example {
description: "Insert ls entries",
example: "ls | stor insert --table-name files",
result: None,
},
Example {
description: "Insert nu records as json data",
example: "ls -l | each {{file: $in.name, metadata: ($in | reject name)}} | stor insert --table-name files_with_md",
result: None,
},
]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let span = call.head;
let table_name: Option<String> = call.get_flag(engine_state, stack, "table-name")?;
let data_record: Option<Record> = call.get_flag(engine_state, stack, "data-record")?;
// let config = stack.get_config(engine_state);
let db = Box::new(SQLiteDatabase::new(
std::path::Path::new(MEMORY_DB),
Signals::empty(),
));
let records = handle(span, data_record, input)?;
for record in records {
process(engine_state, table_name.clone(), span, &db, record)?;
}
Ok(Value::custom(db, span).into_pipeline_data())
}
}
fn handle(
span: Span,
data_record: Option<Record>,
input: PipelineData,
) -> Result<Vec<Record>, ShellError> {
// Check for conflicting use of both pipeline input and flag
if let Some(record) = data_record {
if !matches!(input, PipelineData::Empty) {
return Err(ShellError::GenericError {
error: "Pipeline and Flag both being used".into(),
msg: "Use either pipeline input or '--data-record' parameter".into(),
span: Some(span),
help: None,
inner: vec![],
});
}
return Ok(vec![record]);
}
// Handle the input types
let values = match input {
PipelineData::Empty => {
return Err(ShellError::MissingParameter {
param_name: "requires a table or a record".into(),
span,
});
}
PipelineData::ListStream(stream, ..) => stream.into_iter().collect::<Vec<_>>(),
PipelineData::Value(Value::List { vals, .. }, ..) => vals,
PipelineData::Value(val, ..) => vec![val],
_ => {
return Err(ShellError::OnlySupportsThisInputType {
exp_input_type: "list or record".into(),
wrong_type: "".into(),
dst_span: span,
src_span: span,
});
}
};
values
.into_iter()
.map(|val| match val {
Value::Record { val, .. } => Ok(val.into_owned()),
other => Err(ShellError::OnlySupportsThisInputType {
exp_input_type: "record".into(),
wrong_type: other.get_type().to_string(),
dst_span: Span::unknown(),
src_span: other.span(),
}),
})
.collect()
}
fn process(
engine_state: &EngineState,
table_name: Option<String>,
span: Span,
db: &SQLiteDatabase,
record: Record,
) -> Result<(), ShellError> {
if table_name.is_none() {
return Err(ShellError::MissingParameter {
param_name: "requires at table name".into(),
span,
});
}
let new_table_name = table_name.unwrap_or("table".into());
let mut create_stmt = format!("INSERT INTO {new_table_name} (");
let mut column_placeholders: Vec<String> = Vec::new();
let cols = record.columns();
cols.for_each(|col| {
column_placeholders.push(col.to_string());
});
create_stmt.push_str(&column_placeholders.join(", "));
// Values are set as placeholders.
create_stmt.push_str(") VALUES (");
let mut value_placeholders: Vec<String> = Vec::new();
for (index, _) in record.columns().enumerate() {
value_placeholders.push(format!("?{}", index + 1));
}
create_stmt.push_str(&value_placeholders.join(", "));
create_stmt.push(')');
// dbg!(&create_stmt);
// Get the params from the passed values
let params = values_to_sql(engine_state, record.values().cloned(), span)?;
if let Ok(conn) = db.open_connection() {
conn.execute(&create_stmt, params_from_iter(params))
.map_err(|err| ShellError::GenericError {
error: "Failed to insert using the SQLite connection in memory from insert.rs."
.into(),
msg: err.to_string(),
span: Some(Span::test_data()),
help: None,
inner: vec![],
})?;
};
// dbg!(db.clone());
Ok(())
}
#[cfg(test)]
mod test {
use chrono::DateTime;
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(StorInsert {})
}
#[test]
fn test_process_with_simple_parameters() {
let db = Box::new(SQLiteDatabase::new(
std::path::Path::new(MEMORY_DB),
Signals::empty(),
));
let create_stmt = "CREATE TABLE test_process_with_simple_parameters (
int_column INTEGER,
real_column REAL,
str_column VARCHAR(255),
bool_column BOOLEAN,
date_column DATETIME DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW'))
)";
let conn = db
.open_connection()
.expect("Test was unable to open connection.");
conn.execute(create_stmt, [])
.expect("Failed to create table as part of test.");
let table_name = Some("test_process_with_simple_parameters".to_string());
let span = Span::unknown();
let mut columns = Record::new();
columns.insert("int_column".to_string(), Value::test_int(42));
columns.insert("real_column".to_string(), Value::test_float(3.1));
columns.insert(
"str_column".to_string(),
Value::test_string("SimpleString".to_string()),
);
columns.insert("bool_column".to_string(), Value::test_bool(true));
columns.insert(
"date_column".to_string(),
Value::test_date(
DateTime::parse_from_str("2021-12-30 00:00:00 +0000", "%Y-%m-%d %H:%M:%S %z")
.expect("Date string should parse."),
),
);
let result = process(&EngineState::new(), table_name, span, &db, columns);
assert!(result.is_ok());
}
#[test]
fn test_process_string_with_space() {
let db = Box::new(SQLiteDatabase::new(
std::path::Path::new(MEMORY_DB),
Signals::empty(),
));
let create_stmt = "CREATE TABLE test_process_string_with_space (
str_column VARCHAR(255)
)";
let conn = db
.open_connection()
.expect("Test was unable to open connection.");
conn.execute(create_stmt, [])
.expect("Failed to create table as part of test.");
let table_name = Some("test_process_string_with_space".to_string());
let span = Span::unknown();
let mut columns = Record::new();
columns.insert(
"str_column".to_string(),
Value::test_string("String With Spaces".to_string()),
);
let result = process(&EngineState::new(), table_name, span, &db, columns);
assert!(result.is_ok());
}
#[test]
fn test_no_errors_when_string_too_long() {
let db = Box::new(SQLiteDatabase::new(
std::path::Path::new(MEMORY_DB),
Signals::empty(),
));
let create_stmt = "CREATE TABLE test_errors_when_string_too_long (
str_column VARCHAR(8)
)";
let conn = db
.open_connection()
.expect("Test was unable to open connection.");
conn.execute(create_stmt, [])
.expect("Failed to create table as part of test.");
let table_name = Some("test_errors_when_string_too_long".to_string());
let span = Span::unknown();
let mut columns = Record::new();
columns.insert(
"str_column".to_string(),
Value::test_string("ThisIsALongString".to_string()),
);
let result = process(&EngineState::new(), table_name, span, &db, columns);
// SQLite uses dynamic typing, making any length acceptable for a varchar column
assert!(result.is_ok());
}
#[test]
fn test_no_errors_when_param_is_wrong_type() {
let db = Box::new(SQLiteDatabase::new(
std::path::Path::new(MEMORY_DB),
Signals::empty(),
));
let create_stmt = "CREATE TABLE test_errors_when_param_is_wrong_type (
int_column INT
)";
let conn = db
.open_connection()
.expect("Test was unable to open connection.");
conn.execute(create_stmt, [])
.expect("Failed to create table as part of test.");
let table_name = Some("test_errors_when_param_is_wrong_type".to_string());
let span = Span::unknown();
let mut columns = Record::new();
columns.insert(
"int_column".to_string(),
Value::test_string("ThisIsTheWrongType".to_string()),
);
let result = process(&EngineState::new(), table_name, span, &db, columns);
// SQLite uses dynamic typing, making any type acceptable for a column
assert!(result.is_ok());
}
#[test]
fn test_errors_when_column_doesnt_exist() {
let db = Box::new(SQLiteDatabase::new(
std::path::Path::new(MEMORY_DB),
Signals::empty(),
));
let create_stmt = "CREATE TABLE test_errors_when_column_doesnt_exist (
int_column INT
)";
let conn = db
.open_connection()
.expect("Test was unable to open connection.");
conn.execute(create_stmt, [])
.expect("Failed to create table as part of test.");
let table_name = Some("test_errors_when_column_doesnt_exist".to_string());
let span = Span::unknown();
let mut columns = Record::new();
columns.insert(
"not_a_column".to_string(),
Value::test_string("ThisIsALongString".to_string()),
);
let result = process(&EngineState::new(), table_name, span, &db, columns);
assert!(result.is_err());
}
#[test]
fn test_errors_when_table_doesnt_exist() {
let db = Box::new(SQLiteDatabase::new(
std::path::Path::new(MEMORY_DB),
Signals::empty(),
));
let table_name = Some("test_errors_when_table_doesnt_exist".to_string());
let span = Span::unknown();
let mut columns = Record::new();
columns.insert(
"str_column".to_string(),
Value::test_string("ThisIsALongString".to_string()),
);
let result = process(&EngineState::new(), table_name, span, &db, columns);
assert!(result.is_err());
}
#[test]
fn test_insert_json() {
let db = Box::new(SQLiteDatabase::new(
std::path::Path::new(MEMORY_DB),
Signals::empty(),
));
let create_stmt = "CREATE TABLE test_insert_json (
json_field JSON,
jsonb_field JSONB
)";
let conn = db
.open_connection()
.expect("Test was unable to open connection.");
conn.execute(create_stmt, [])
.expect("Failed to create table as part of test.");
let mut record = Record::new();
record.insert("x", Value::test_int(89));
record.insert("y", Value::test_int(12));
record.insert(
"z",
Value::test_list(vec![
Value::test_string("hello"),
Value::test_string("goodbye"),
]),
);
let mut row = Record::new();
row.insert("json_field", Value::test_record(record.clone()));
row.insert("jsonb_field", Value::test_record(record));
let result = process(
&EngineState::new(),
Some("test_insert_json".to_owned()),
Span::unknown(),
&db,
row,
);
assert!(result.is_ok());
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/stor/update.rs | crates/nu-command/src/stor/update.rs | use crate::database::{MEMORY_DB, SQLiteDatabase, values_to_sql};
use nu_engine::command_prelude::*;
use nu_protocol::Signals;
use rusqlite::params_from_iter;
#[derive(Clone)]
pub struct StorUpdate;
impl Command for StorUpdate {
fn name(&self) -> &str {
"stor update"
}
fn signature(&self) -> Signature {
Signature::build("stor update")
.input_output_types(vec![
(Type::Nothing, Type::table()),
(Type::record(), Type::table()),
// FIXME Type::Any input added to disable pipeline input type checking, as run-time checks can raise undesirable type errors
// which aren't caught by the parser. see https://github.com/nushell/nushell/pull/14922 for more details
(Type::Any, Type::table()),
])
.required_named(
"table-name",
SyntaxShape::String,
"name of the table you want to insert into",
Some('t'),
)
.named(
"update-record",
SyntaxShape::Record(vec![]),
"a record of column names and column values to update in the specified table",
Some('u'),
)
.named(
"where-clause",
SyntaxShape::String,
"a sql string to use as a where clause without the WHERE keyword",
Some('w'),
)
.allow_variants_without_examples(true)
.category(Category::Database)
}
fn description(&self) -> &str {
"Update information in a specified table in the in-memory sqlite database."
}
fn search_terms(&self) -> Vec<&str> {
vec!["sqlite", "storing", "table", "saving", "changing"]
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Update the in-memory sqlite database",
example: "stor update --table-name nudb --update-record {str1: nushell datetime1: 2020-04-17}",
result: None,
},
Example {
description: "Update the in-memory sqlite database with a where clause",
example: "stor update --table-name nudb --update-record {str1: nushell datetime1: 2020-04-17} --where-clause \"bool1 = 1\"",
result: None,
},
Example {
description: "Update the in-memory sqlite database through pipeline input",
example: "{str1: nushell datetime1: 2020-04-17} | stor update --table-name nudb",
result: None,
},
]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let span = call.head;
let table_name: Option<String> = call.get_flag(engine_state, stack, "table-name")?;
let update_record: Option<Record> = call.get_flag(engine_state, stack, "update-record")?;
let where_clause_opt: Option<Spanned<String>> =
call.get_flag(engine_state, stack, "where-clause")?;
// Open the in-mem database
let db = Box::new(SQLiteDatabase::new(
std::path::Path::new(MEMORY_DB),
Signals::empty(),
));
// Check if the record is being passed as input or using the update record parameter
let columns = handle(span, update_record, input)?;
process(
engine_state,
table_name,
span,
&db,
columns,
where_clause_opt,
)?;
Ok(Value::custom(db, span).into_pipeline_data())
}
}
fn handle(
span: Span,
update_record: Option<Record>,
input: PipelineData,
) -> Result<Record, ShellError> {
match input {
PipelineData::Empty => update_record.ok_or_else(|| ShellError::MissingParameter {
param_name: "requires a record".into(),
span,
}),
PipelineData::Value(value, ..) => {
// Since input is being used, check if the data record parameter is used too
if update_record.is_some() {
return Err(ShellError::GenericError {
error: "Pipeline and Flag both being used".into(),
msg: "Use either pipeline input or '--update-record' parameter".into(),
span: Some(span),
help: None,
inner: vec![],
});
}
match value {
Value::Record { val, .. } => Ok(val.into_owned()),
val => Err(ShellError::OnlySupportsThisInputType {
exp_input_type: "record".into(),
wrong_type: val.get_type().to_string(),
dst_span: Span::unknown(),
src_span: val.span(),
}),
}
}
_ => {
if update_record.is_some() {
return Err(ShellError::GenericError {
error: "Pipeline and Flag both being used".into(),
msg: "Use either pipeline input or '--update-record' parameter".into(),
span: Some(span),
help: None,
inner: vec![],
});
}
Err(ShellError::OnlySupportsThisInputType {
exp_input_type: "record".into(),
wrong_type: "".into(),
dst_span: span,
src_span: span,
})
}
}
}
fn process(
engine_state: &EngineState,
table_name: Option<String>,
span: Span,
db: &SQLiteDatabase,
record: Record,
where_clause_opt: Option<Spanned<String>>,
) -> Result<(), ShellError> {
if table_name.is_none() {
return Err(ShellError::MissingParameter {
param_name: "requires at table name".into(),
span,
});
}
let new_table_name = table_name.unwrap_or("table".into());
if let Ok(conn) = db.open_connection() {
let mut update_stmt = format!("UPDATE {new_table_name} ");
update_stmt.push_str("SET ");
let mut placeholders: Vec<String> = Vec::new();
for (index, (key, _)) in record.iter().enumerate() {
placeholders.push(format!("{} = ?{}", key, index + 1));
}
update_stmt.push_str(&placeholders.join(", "));
// Yup, this is a bit janky, but I'm not sure a better way to do this without having
// --and and --or flags as well as supporting ==, !=, <>, is null, is not null, etc.
// and other sql syntax. So, for now, just type a sql where clause as a string.
if let Some(where_clause) = where_clause_opt {
update_stmt.push_str(&format!(" WHERE {}", where_clause.item));
}
// dbg!(&update_stmt);
// Get the params from the passed values
let params = values_to_sql(engine_state, record.values().cloned(), span)?;
conn.execute(&update_stmt, params_from_iter(params))
.map_err(|err| ShellError::GenericError {
error: "Failed to open SQLite connection in memory from update".into(),
msg: err.to_string(),
span: Some(Span::test_data()),
help: None,
inner: vec![],
})?;
}
// dbg!(db.clone());
Ok(())
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(StorUpdate {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/stor/mod.rs | crates/nu-command/src/stor/mod.rs | mod create;
mod delete;
mod export;
mod import;
mod insert;
mod open;
mod reset;
mod stor_;
mod update;
pub use create::StorCreate;
pub use delete::StorDelete;
pub use export::StorExport;
pub use import::StorImport;
pub use insert::StorInsert;
pub use open::StorOpen;
pub use reset::StorReset;
pub use stor_::Stor;
pub use update::StorUpdate;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/stor/export.rs | crates/nu-command/src/stor/export.rs | use crate::database::{MEMORY_DB, SQLiteDatabase};
use nu_engine::command_prelude::*;
use nu_protocol::Signals;
#[derive(Clone)]
pub struct StorExport;
impl Command for StorExport {
fn name(&self) -> &str {
"stor export"
}
fn signature(&self) -> Signature {
Signature::build("stor export")
.input_output_types(vec![(Type::Nothing, Type::table())])
.required_named(
"file-name",
SyntaxShape::String,
"file name to export the sqlite in-memory database to",
Some('f'),
)
.allow_variants_without_examples(true)
.category(Category::Database)
}
fn description(&self) -> &str {
"Export the in-memory sqlite database to a sqlite database file."
}
fn search_terms(&self) -> Vec<&str> {
vec!["sqlite", "save", "database", "saving", "file"]
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
description: "Export the in-memory sqlite database",
example: "stor export --file-name nudb.sqlite",
result: None,
}]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let span = call.head;
let file_name_opt: Option<String> = call.get_flag(engine_state, stack, "file-name")?;
let file_name = match file_name_opt {
Some(file_name) => file_name,
None => {
return Err(ShellError::MissingParameter {
param_name: "please supply a file name with the --file-name parameter".into(),
span,
});
}
};
// Open the in-mem database
let db = Box::new(SQLiteDatabase::new(
std::path::Path::new(MEMORY_DB),
Signals::empty(),
));
if let Ok(conn) = db.open_connection() {
// This uses vacuum. I'm not really sure if this is the best way to do this.
// I also added backup in the sqlitedatabase impl. If we have problems, we could switch to that.
db.export_in_memory_database_to_file(&conn, file_name)
.map_err(|err| ShellError::GenericError {
error: "Failed to open SQLite connection in memory from export".into(),
msg: err.to_string(),
span: Some(Span::test_data()),
help: None,
inner: vec![],
})?;
}
// dbg!(db.clone());
Ok(Value::custom(db, span).into_pipeline_data())
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(StorExport {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/stor/import.rs | crates/nu-command/src/stor/import.rs | use crate::database::{MEMORY_DB, SQLiteDatabase};
use nu_engine::command_prelude::*;
use nu_protocol::Signals;
#[derive(Clone)]
pub struct StorImport;
impl Command for StorImport {
fn name(&self) -> &str {
"stor import"
}
fn signature(&self) -> Signature {
Signature::build("stor import")
.input_output_types(vec![(Type::Nothing, Type::table())])
.required_named(
"file-name",
SyntaxShape::String,
"file name to import the sqlite in-memory database from",
Some('f'),
)
.allow_variants_without_examples(true)
.category(Category::Database)
}
fn description(&self) -> &str {
"Import a sqlite database file into the in-memory sqlite database."
}
fn search_terms(&self) -> Vec<&str> {
vec!["sqlite", "open", "database", "restore", "file"]
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
description: "Import a sqlite database file into the in-memory sqlite database",
example: "stor import --file-name nudb.sqlite",
result: None,
}]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let span = call.head;
let file_name_opt: Option<String> = call.get_flag(engine_state, stack, "file-name")?;
let file_name = match file_name_opt {
Some(file_name) => file_name,
None => {
return Err(ShellError::MissingParameter {
param_name: "please supply a file name with the --file-name parameter".into(),
span,
});
}
};
// Open the in-mem database
let db = Box::new(SQLiteDatabase::new(
std::path::Path::new(MEMORY_DB),
Signals::empty(),
));
if let Ok(mut conn) = db.open_connection() {
db.restore_database_from_file(&mut conn, file_name)
.map_err(|err| ShellError::GenericError {
error: "Failed to open SQLite connection in memory from import".into(),
msg: err.to_string(),
span: Some(Span::test_data()),
help: None,
inner: vec![],
})?;
}
// dbg!(db.clone());
Ok(Value::custom(db, span).into_pipeline_data())
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(StorImport {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/stor/reset.rs | crates/nu-command/src/stor/reset.rs | use crate::database::{MEMORY_DB, SQLiteDatabase};
use nu_engine::command_prelude::*;
use nu_protocol::Signals;
#[derive(Clone)]
pub struct StorReset;
impl Command for StorReset {
fn name(&self) -> &str {
"stor reset"
}
fn signature(&self) -> Signature {
Signature::build("stor reset")
.input_output_types(vec![(Type::Nothing, Type::table())])
.allow_variants_without_examples(true)
.category(Category::Database)
}
fn description(&self) -> &str {
"Reset the in-memory database by dropping all tables."
}
fn search_terms(&self) -> Vec<&str> {
vec!["sqlite", "remove", "table", "saving", "drop"]
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
description: "Reset the in-memory sqlite database",
example: "stor reset",
result: None,
}]
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let span = call.head;
// Open the in-mem database
let db = Box::new(SQLiteDatabase::new(
std::path::Path::new(MEMORY_DB),
Signals::empty(),
));
if let Ok(conn) = db.open_connection() {
conn.execute("PRAGMA foreign_keys = OFF", [])
.map_err(|err| ShellError::GenericError {
error: "Failed to turn off foreign_key protections for reset".into(),
msg: err.to_string(),
span: Some(Span::test_data()),
help: None,
inner: vec![],
})?;
db.drop_all_tables(&conn)
.map_err(|err| ShellError::GenericError {
error: "Failed to drop all tables in memory from reset".into(),
msg: err.to_string(),
span: Some(Span::test_data()),
help: None,
inner: vec![],
})?;
conn.execute("PRAGMA foreign_keys = ON", [])
.map_err(|err| ShellError::GenericError {
error: "Failed to turn on foreign_key protections for reset".into(),
msg: err.to_string(),
span: Some(Span::test_data()),
help: None,
inner: vec![],
})?;
}
// dbg!(db.clone());
Ok(Value::custom(db, span).into_pipeline_data())
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(StorReset {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/stor/create.rs | crates/nu-command/src/stor/create.rs | use crate::database::{MEMORY_DB, SQLiteDatabase};
use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct StorCreate;
impl Command for StorCreate {
fn name(&self) -> &str {
"stor create"
}
fn signature(&self) -> Signature {
Signature::build("stor create")
.input_output_types(vec![(Type::Nothing, Type::table())])
.required_named(
"table-name",
SyntaxShape::String,
"name of the table you want to create",
Some('t'),
)
.required_named(
"columns",
SyntaxShape::Record(vec![]),
"a record of column names and datatypes",
Some('c'),
)
.allow_variants_without_examples(true)
.category(Category::Database)
}
fn description(&self) -> &str {
"Create a table in the in-memory sqlite database."
}
fn search_terms(&self) -> Vec<&str> {
vec!["sqlite", "storing", "table"]
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Create an in-memory sqlite database with specified table name, column names, and column data types",
example: "stor create --table-name nudb --columns {bool1: bool, int1: int, float1: float, str1: str, datetime1: datetime}",
result: None,
},
Example {
description: "Create an in-memory sqlite database with a json column",
example: "stor create --table-name files_with_md --columns {file: str, metadata: jsonb}",
result: None,
},
]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let span = call.head;
let table_name: Option<String> = call.get_flag(engine_state, stack, "table-name")?;
let columns: Option<Record> = call.get_flag(engine_state, stack, "columns")?;
let db = Box::new(SQLiteDatabase::new(
std::path::Path::new(MEMORY_DB),
engine_state.signals().clone(),
));
process(table_name, span, &db, columns)?;
// dbg!(db.clone());
Ok(Value::custom(db, span).into_pipeline_data())
}
}
fn process(
table_name: Option<String>,
span: Span,
db: &SQLiteDatabase,
columns: Option<Record>,
) -> Result<(), ShellError> {
if table_name.is_none() {
return Err(ShellError::MissingParameter {
param_name: "requires at table name".into(),
span,
});
}
let new_table_name = table_name.unwrap_or("table".into());
if let Ok(conn) = db.open_connection() {
match columns {
Some(record) => {
let mut create_stmt = format!("CREATE TABLE {new_table_name} ( ");
for (column_name, column_datatype) in record {
match column_datatype.coerce_str()?.to_lowercase().as_ref() {
"int" => {
create_stmt.push_str(&format!("{column_name} INTEGER, "));
}
"float" => {
create_stmt.push_str(&format!("{column_name} REAL, "));
}
"str" => {
create_stmt.push_str(&format!("{column_name} VARCHAR(255), "));
}
"bool" => {
create_stmt.push_str(&format!("{column_name} BOOLEAN, "));
}
"datetime" => {
create_stmt.push_str(&format!(
"{column_name} DATETIME DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')), "
));
}
"json" => {
create_stmt.push_str(&format!("{column_name} JSON, "));
}
"jsonb" => {
create_stmt.push_str(&format!("{column_name} JSONB, "));
}
_ => {
return Err(ShellError::UnsupportedInput {
msg: "Unsupported column data type. Please use: int, float, str, bool, datetime, json, jsonb".into(),
input: format!("{column_datatype:?}"),
msg_span: column_datatype.span(),
input_span: column_datatype.span(),
});
}
}
}
if create_stmt.ends_with(", ") {
create_stmt.pop();
create_stmt.pop();
}
create_stmt.push_str(" )");
// dbg!(&create_stmt);
conn.execute(&create_stmt, [])
.map_err(|err| ShellError::GenericError {
error: "Failed to open SQLite connection in memory from create".into(),
msg: err.to_string(),
span: Some(Span::test_data()),
help: None,
inner: vec![],
})?;
}
None => {
return Err(ShellError::MissingParameter {
param_name: "requires at least one column".into(),
span,
});
}
};
}
Ok(())
}
#[cfg(test)]
mod test {
use nu_protocol::Signals;
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(StorCreate {})
}
#[test]
fn test_process_with_valid_parameters() {
let table_name = Some("test_table".to_string());
let span = Span::unknown();
let db = Box::new(SQLiteDatabase::new(
std::path::Path::new(MEMORY_DB),
Signals::empty(),
));
let mut columns = Record::new();
columns.insert(
"int_column".to_string(),
Value::test_string("int".to_string()),
);
let result = process(table_name, span, &db, Some(columns));
assert!(result.is_ok());
}
#[test]
fn test_process_with_missing_table_name() {
let table_name = None;
let span = Span::unknown();
let db = Box::new(SQLiteDatabase::new(
std::path::Path::new(MEMORY_DB),
Signals::empty(),
));
let mut columns = Record::new();
columns.insert(
"int_column".to_string(),
Value::test_string("int".to_string()),
);
let result = process(table_name, span, &db, Some(columns));
assert!(result.is_err());
assert!(
result
.unwrap_err()
.to_string()
.contains("requires at table name")
);
}
#[test]
fn test_process_with_missing_columns() {
let table_name = Some("test_table".to_string());
let span = Span::unknown();
let db = Box::new(SQLiteDatabase::new(
std::path::Path::new(MEMORY_DB),
Signals::empty(),
));
let result = process(table_name, span, &db, None);
assert!(result.is_err());
assert!(
result
.unwrap_err()
.to_string()
.contains("requires at least one column")
);
}
#[test]
fn test_process_with_unsupported_column_data_type() {
let table_name = Some("test_table".to_string());
let span = Span::unknown();
let db = Box::new(SQLiteDatabase::new(
std::path::Path::new(MEMORY_DB),
Signals::empty(),
));
let mut columns = Record::new();
let column_datatype = "bogus_data_type".to_string();
columns.insert(
"column0".to_string(),
Value::test_string(column_datatype.clone()),
);
let result = process(table_name, span, &db, Some(columns));
assert!(result.is_err());
let expected_err = ShellError::UnsupportedInput {
msg: "unsupported column data type".into(),
input: format!("{:?}", column_datatype.clone()),
msg_span: Span::test_data(),
input_span: Span::test_data(),
};
assert_eq!(result.unwrap_err().to_string(), expected_err.to_string());
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/stor/delete.rs | crates/nu-command/src/stor/delete.rs | use crate::database::{MEMORY_DB, SQLiteDatabase};
use nu_engine::command_prelude::*;
use nu_protocol::Signals;
#[derive(Clone)]
pub struct StorDelete;
impl Command for StorDelete {
fn name(&self) -> &str {
"stor delete"
}
fn signature(&self) -> Signature {
Signature::build("stor delete")
.input_output_types(vec![(Type::Nothing, Type::table())])
.required_named(
"table-name",
SyntaxShape::String,
"name of the table you want to delete or delete from",
Some('t'),
)
.named(
"where-clause",
SyntaxShape::String,
"a sql string to use as a where clause without the WHERE keyword",
Some('w'),
)
.allow_variants_without_examples(true)
.category(Category::Database)
}
fn description(&self) -> &str {
"Delete a table or specified rows in the in-memory sqlite database."
}
fn search_terms(&self) -> Vec<&str> {
vec!["sqlite", "remove", "table", "saving", "drop"]
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Delete a table from the in-memory sqlite database",
example: "stor delete --table-name nudb",
result: None,
},
Example {
description: "Delete some rows from the in-memory sqlite database with a where clause",
example: "stor delete --table-name nudb --where-clause \"int1 == 5\"",
result: None,
},
]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let span = call.head;
// For dropping/deleting an entire table
let table_name_opt: Option<String> = call.get_flag(engine_state, stack, "table-name")?;
// For deleting rows from a table
let where_clause_opt: Option<String> =
call.get_flag(engine_state, stack, "where-clause")?;
if table_name_opt.is_none() && where_clause_opt.is_none() {
return Err(ShellError::MissingParameter {
param_name: "requires at least one of table-name or where-clause".into(),
span,
});
}
if table_name_opt.is_none() && where_clause_opt.is_some() {
return Err(ShellError::MissingParameter {
param_name: "using the where-clause requires the use of a table-name".into(),
span,
});
}
// Open the in-mem database
let db = Box::new(SQLiteDatabase::new(
std::path::Path::new(MEMORY_DB),
Signals::empty(),
));
if let Some(new_table_name) = table_name_opt
&& let Ok(conn) = db.open_connection()
{
let sql_stmt = match where_clause_opt {
None => {
// We're deleting an entire table
format!("DROP TABLE {new_table_name}")
}
Some(where_clause) => {
// We're just deleting some rows
let mut delete_stmt = format!("DELETE FROM {new_table_name} ");
// Yup, this is a bit janky, but I'm not sure a better way to do this without having
// --and and --or flags as well as supporting ==, !=, <>, is null, is not null, etc.
// and other sql syntax. So, for now, just type a sql where clause as a string.
delete_stmt.push_str(&format!("WHERE {where_clause}"));
delete_stmt
}
};
// dbg!(&sql_stmt);
conn.execute(&sql_stmt, [])
.map_err(|err| ShellError::GenericError {
error: "Failed to delete using the SQLite connection in memory from delete.rs."
.into(),
msg: err.to_string(),
span: Some(Span::test_data()),
help: None,
inner: vec![],
})?;
}
// dbg!(db.clone());
Ok(Value::custom(db, span).into_pipeline_data())
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(StorDelete {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/charting/hashable_value.rs | crates/nu-command/src/charting/hashable_value.rs | use chrono::{DateTime, FixedOffset};
use nu_protocol::{Filesize, ShellError, Span, Value};
use std::hash::{Hash, Hasher};
/// A subset of [`Value`], which is hashable.
/// And it means that we can put the value into something like
/// [`HashMap`](std::collections::HashMap) or [`HashSet`](std::collections::HashSet) for further
/// usage like value statistics.
///
/// For now the main way to crate a [`HashableValue`] is using
/// [`from_value`](HashableValue::from_value)
///
/// Please note that although each variant contains `span` field, but during hashing, this field will not be concerned.
/// Which means that the following will be true:
/// ```text
/// assert_eq!(HashableValue::Bool {val: true, span: Span{start: 0, end: 1}}, HashableValue::Bool {val: true, span: Span{start: 90, end: 1000}})
/// ```
#[derive(Eq, Debug, Ord, PartialOrd)]
pub enum HashableValue {
Bool {
val: bool,
span: Span,
},
Int {
val: i64,
span: Span,
},
Float {
val: [u8; 8], // because f64 is not hashable, we save it as [u8;8] array to make it hashable.
span: Span,
},
Filesize {
val: Filesize,
span: Span,
},
Duration {
val: i64,
span: Span,
},
Date {
val: DateTime<FixedOffset>,
span: Span,
},
String {
val: String,
span: Span,
},
Binary {
val: Vec<u8>,
span: Span,
},
}
impl Default for HashableValue {
fn default() -> Self {
HashableValue::Bool {
val: false,
span: Span::unknown(),
}
}
}
impl HashableValue {
/// Try to convert from `value` to self
///
/// A `span` is required because when there is an error in value, it may not contain `span` field.
///
/// If the given value is not hashable(mainly because of it is structured data), an error will returned.
pub fn from_value(value: Value, span: Span) -> Result<Self, ShellError> {
let val_span = value.span();
match value {
Value::Bool { val, .. } => Ok(HashableValue::Bool {
val,
span: val_span,
}),
Value::Int { val, .. } => Ok(HashableValue::Int {
val,
span: val_span,
}),
Value::Filesize { val, .. } => Ok(HashableValue::Filesize {
val,
span: val_span,
}),
Value::Duration { val, .. } => Ok(HashableValue::Duration {
val,
span: val_span,
}),
Value::Date { val, .. } => Ok(HashableValue::Date {
val,
span: val_span,
}),
Value::Float { val, .. } => Ok(HashableValue::Float {
val: val.to_ne_bytes(),
span: val_span,
}),
Value::String { val, .. } => Ok(HashableValue::String {
val,
span: val_span,
}),
Value::Binary { val, .. } => Ok(HashableValue::Binary {
val,
span: val_span,
}),
// Explicitly propagate errors instead of dropping them.
Value::Error { error, .. } => Err(*error),
_ => Err(ShellError::UnsupportedInput {
msg: "input value is not hashable".into(),
input: format!("input type: {:?}", value.get_type()),
msg_span: span,
input_span: value.span(),
}),
}
}
/// Convert from self to nu's core data type `Value`.
pub fn into_value(self) -> Value {
match self {
HashableValue::Bool { val, span } => Value::bool(val, span),
HashableValue::Int { val, span } => Value::int(val, span),
HashableValue::Filesize { val, span } => Value::filesize(val, span),
HashableValue::Duration { val, span } => Value::duration(val, span),
HashableValue::Date { val, span } => Value::date(val, span),
HashableValue::Float { val, span } => Value::float(f64::from_ne_bytes(val), span),
HashableValue::String { val, span } => Value::string(val, span),
HashableValue::Binary { val, span } => Value::binary(val, span),
}
}
}
impl Hash for HashableValue {
fn hash<H: Hasher>(&self, state: &mut H) {
match self {
HashableValue::Bool { val, .. } => val.hash(state),
HashableValue::Int { val, .. } => val.hash(state),
HashableValue::Filesize { val, .. } => val.hash(state),
HashableValue::Duration { val, .. } => val.hash(state),
HashableValue::Date { val, .. } => val.hash(state),
HashableValue::Float { val, .. } => val.hash(state),
HashableValue::String { val, .. } => val.hash(state),
HashableValue::Binary { val, .. } => val.hash(state),
}
}
}
impl PartialEq for HashableValue {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(HashableValue::Bool { val: lhs, .. }, HashableValue::Bool { val: rhs, .. }) => {
lhs == rhs
}
(HashableValue::Int { val: lhs, .. }, HashableValue::Int { val: rhs, .. }) => {
lhs == rhs
}
(
HashableValue::Filesize { val: lhs, .. },
HashableValue::Filesize { val: rhs, .. },
) => lhs == rhs,
(
HashableValue::Duration { val: lhs, .. },
HashableValue::Duration { val: rhs, .. },
) => lhs == rhs,
(HashableValue::Date { val: lhs, .. }, HashableValue::Date { val: rhs, .. }) => {
lhs == rhs
}
(HashableValue::Float { val: lhs, .. }, HashableValue::Float { val: rhs, .. }) => {
lhs == rhs
}
(HashableValue::String { val: lhs, .. }, HashableValue::String { val: rhs, .. }) => {
lhs == rhs
}
(HashableValue::Binary { val: lhs, .. }, HashableValue::Binary { val: rhs, .. }) => {
lhs == rhs
}
_ => false,
}
}
}
#[cfg(test)]
mod test {
use super::*;
use nu_protocol::{
BlockId,
ast::{CellPath, PathMember},
engine::Closure,
};
use std::collections::HashSet;
#[test]
fn from_value() {
let span = Span::test_data();
let values = vec![
(
Value::bool(true, span),
HashableValue::Bool { val: true, span },
),
(Value::int(1, span), HashableValue::Int { val: 1, span }),
(
Value::filesize(1, span),
HashableValue::Filesize {
val: 1.into(),
span,
},
),
(
Value::duration(1, span),
HashableValue::Duration { val: 1, span },
),
(
Value::date(
DateTime::<FixedOffset>::parse_from_rfc2822("Wed, 18 Feb 2015 23:16:09 GMT")
.unwrap(),
span,
),
HashableValue::Date {
val: DateTime::<FixedOffset>::parse_from_rfc2822(
"Wed, 18 Feb 2015 23:16:09 GMT",
)
.unwrap(),
span,
},
),
(
Value::string("1".to_string(), span),
HashableValue::String {
val: "1".to_string(),
span,
},
),
(
Value::binary(vec![1], span),
HashableValue::Binary { val: vec![1], span },
),
];
for (val, expect_hashable_val) in values.into_iter() {
assert_eq!(
HashableValue::from_value(val, Span::unknown()).unwrap(),
expect_hashable_val
);
}
}
#[test]
fn from_unhashable_value() {
let span = Span::test_data();
let values = [
Value::list(vec![Value::bool(true, span)], span),
Value::closure(
Closure {
block_id: BlockId::new(0),
captures: Vec::new(),
},
span,
),
Value::nothing(span),
Value::error(
ShellError::DidYouMean {
suggestion: "what?".to_string(),
span,
},
span,
),
Value::cell_path(
CellPath {
members: vec![PathMember::Int {
val: 0,
span,
optional: false,
}],
},
span,
),
];
for v in values {
assert!(HashableValue::from_value(v, Span::unknown()).is_err())
}
}
#[test]
fn from_to_tobe_same() {
let span = Span::test_data();
let values = vec![
Value::bool(true, span),
Value::int(1, span),
Value::filesize(1, span),
Value::duration(1, span),
Value::string("1".to_string(), span),
Value::binary(vec![1], span),
];
for val in values.into_iter() {
let expected_val = val.clone();
assert_eq!(
HashableValue::from_value(val, Span::unknown())
.unwrap()
.into_value(),
expected_val
);
}
}
#[test]
fn hashable_value_eq_without_concern_span() {
assert_eq!(
HashableValue::Bool {
val: true,
span: Span::new(0, 1)
},
HashableValue::Bool {
val: true,
span: Span::new(90, 1000)
}
)
}
#[test]
fn put_to_hashset() {
let span = Span::test_data();
let mut set = HashSet::new();
set.insert(HashableValue::Bool { val: true, span });
assert!(set.contains(&HashableValue::Bool { val: true, span }));
// hashable value doesn't care about span.
let diff_span = Span::new(1, 2);
set.insert(HashableValue::Bool {
val: true,
span: diff_span,
});
assert!(set.contains(&HashableValue::Bool { val: true, span }));
assert!(set.contains(&HashableValue::Bool {
val: true,
span: diff_span
}));
assert_eq!(set.len(), 1);
set.insert(HashableValue::Int { val: 2, span });
assert_eq!(set.len(), 2);
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/charting/mod.rs | crates/nu-command/src/charting/mod.rs | mod hashable_value;
mod histogram;
pub use histogram::Histogram;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/charting/histogram.rs | crates/nu-command/src/charting/histogram.rs | use super::hashable_value::HashableValue;
use itertools::Itertools;
use nu_engine::command_prelude::*;
use std::collections::HashMap;
#[derive(Clone)]
pub struct Histogram;
enum PercentageCalcMethod {
Normalize,
Relative,
}
impl Command for Histogram {
fn name(&self) -> &str {
"histogram"
}
fn signature(&self) -> Signature {
Signature::build("histogram")
.input_output_types(vec![(Type::List(Box::new(Type::Any)), Type::table())])
.optional(
"column-name",
SyntaxShape::String,
"Column name to calc frequency, no need to provide if input is a list.",
)
.optional(
"frequency-column-name",
SyntaxShape::String,
"Histogram's frequency column, default to be frequency column output.",
)
.param(
Flag::new("percentage-type")
.short('t')
.arg(SyntaxShape::String)
.desc(
"percentage calculate method, can be 'normalize' or 'relative', in \
'normalize', defaults to be 'normalize'",
)
.completion(Completion::new_list(&["normalize", "relative"])),
)
.category(Category::Chart)
}
fn description(&self) -> &str {
"Creates a new table with a histogram based on the column name passed in."
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Compute a histogram of file types",
example: "ls | histogram type",
result: None,
},
Example {
description: "Compute a histogram for the types of files, with frequency column \
named freq",
example: "ls | histogram type freq",
result: None,
},
Example {
description: "Compute a histogram for a list of numbers",
example: "[1 2 1] | histogram",
result: Some(Value::test_list(vec![
Value::test_record(record! {
"value" => Value::test_int(1),
"count" => Value::test_int(2),
"quantile" => Value::test_float(0.6666666666666666),
"percentage" => Value::test_string("66.67%"),
"frequency" => Value::test_string("******************************************************************"),
}),
Value::test_record(record! {
"value" => Value::test_int(2),
"count" => Value::test_int(1),
"quantile" => Value::test_float(0.3333333333333333),
"percentage" => Value::test_string("33.33%"),
"frequency" => Value::test_string("*********************************"),
}),
])),
},
Example {
description: "Compute a histogram for a list of numbers, and percentage is based \
on the maximum value",
example: "[1 2 3 1 1 1 2 2 1 1] | histogram --percentage-type relative",
result: None,
},
]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
// input check.
let column_name: Option<Spanned<String>> = call.opt(engine_state, stack, 0)?;
let frequency_name_arg = call.opt::<Spanned<String>>(engine_state, stack, 1)?;
let frequency_column_name = match frequency_name_arg {
Some(inner) => {
let forbidden_column_names = ["value", "count", "quantile", "percentage"];
if forbidden_column_names.contains(&inner.item.as_str()) {
return Err(ShellError::TypeMismatch {
err_message: format!(
"frequency-column-name can't be {}",
forbidden_column_names
.iter()
.map(|val| format!("'{val}'"))
.collect::<Vec<_>>()
.join(", ")
),
span: inner.span,
});
}
inner.item
}
None => "frequency".to_string(),
};
let calc_method: Option<Spanned<String>> =
call.get_flag(engine_state, stack, "percentage-type")?;
let calc_method = match calc_method {
None => PercentageCalcMethod::Normalize,
Some(inner) => match inner.item.as_str() {
"normalize" => PercentageCalcMethod::Normalize,
"relative" => PercentageCalcMethod::Relative,
_ => {
return Err(ShellError::TypeMismatch {
err_message: "calc method can only be 'normalize' or 'relative'"
.to_string(),
span: inner.span,
});
}
},
};
let span = call.head;
let data_as_value = input.into_value(span)?;
let value_span = data_as_value.span();
// `input` is not a list, here we can return an error.
run_histogram(
data_as_value.into_list()?,
column_name,
frequency_column_name,
calc_method,
span,
// Note that as_list() filters out Value::Error here.
value_span,
)
}
}
fn run_histogram(
values: Vec<Value>,
column_name: Option<Spanned<String>>,
freq_column: String,
calc_method: PercentageCalcMethod,
head_span: Span,
list_span: Span,
) -> Result<PipelineData, ShellError> {
let mut inputs = vec![];
// convert from inputs to hashable values.
match column_name {
None => {
// some invalid input scenario needs to handle:
// Expect input is a list of hashable value, if one value is not hashable, throw out error.
for v in values {
match v {
// Propagate existing errors.
Value::Error { error, .. } => return Err(*error),
_ => {
let t = v.get_type();
let span = v.span();
inputs.push(HashableValue::from_value(v, head_span).map_err(|_| {
ShellError::UnsupportedInput {
msg: "Since column-name was not provided, only lists of hashable \
values are supported."
.to_string(),
input: format!("input type: {t:?}"),
msg_span: head_span,
input_span: span,
}
})?)
}
}
}
}
Some(ref col) => {
// some invalid input scenario needs to handle:
// * item in `input` is not a record, just skip it.
// * a record doesn't contain specific column, just skip it.
// * all records don't contain specific column, throw out error, indicate at least one row should contains specific column.
// * a record contain a value which can't be hashed, skip it.
let col_name = &col.item;
for v in values {
match v {
// parse record, and fill valid value to actual input.
Value::Record { val, .. } => {
if let Some(v) = val.get(col_name)
&& let Ok(v) = HashableValue::from_value(v.clone(), head_span)
{
inputs.push(v);
}
}
// Propagate existing errors.
Value::Error { error, .. } => return Err(*error),
_ => continue,
}
}
if inputs.is_empty() {
return Err(ShellError::CantFindColumn {
col_name: col_name.clone(),
span: Some(head_span),
src_span: list_span,
});
}
}
}
let value_column_name = column_name
.map(|x| x.item)
.unwrap_or_else(|| "value".to_string());
Ok(histogram_impl(
inputs,
&value_column_name,
calc_method,
&freq_column,
head_span,
))
}
fn histogram_impl(
inputs: Vec<HashableValue>,
value_column_name: &str,
calc_method: PercentageCalcMethod,
freq_column: &str,
span: Span,
) -> PipelineData {
// here we can make sure that inputs is not empty, and every elements
// is a simple val and ok to make count.
let mut counter = HashMap::new();
let mut max_cnt = 0;
let total_cnt = inputs.len();
for i in inputs {
let new_cnt = *counter.get(&i).unwrap_or(&0) + 1;
counter.insert(i, new_cnt);
if new_cnt > max_cnt {
max_cnt = new_cnt;
}
}
let mut result = vec![];
const MAX_FREQ_COUNT: f64 = 100.0;
for (val, count) in counter.into_iter().sorted() {
let quantile = match calc_method {
PercentageCalcMethod::Normalize => count as f64 / total_cnt as f64,
PercentageCalcMethod::Relative => count as f64 / max_cnt as f64,
};
let percentage = format!("{:.2}%", quantile * 100_f64);
let freq = "*".repeat((MAX_FREQ_COUNT * quantile).floor() as usize);
result.push((
count, // attach count first for easily sorting.
Value::record(
record! {
value_column_name => val.into_value(),
"count" => Value::int(count, span),
"quantile" => Value::float(quantile, span),
"percentage" => Value::string(percentage, span),
freq_column => Value::string(freq, span),
},
span,
),
));
}
result.sort_by(|a, b| b.0.cmp(&a.0));
Value::list(result.into_iter().map(|x| x.1).collect(), span).into_pipeline_data()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(Histogram)
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/hash/sha256.rs | crates/nu-command/src/hash/sha256.rs | use super::generic_digest::{GenericDigest, HashDigest};
use ::sha2::Sha256;
use nu_protocol::{Example, Span, Value};
pub type HashSha256 = GenericDigest<Sha256>;
impl HashDigest for Sha256 {
fn name() -> &'static str {
"sha256"
}
fn examples() -> Vec<Example<'static>> {
vec![
Example {
description: "Return the sha256 hash of a string, hex-encoded",
example: "'abcdefghijklmnopqrstuvwxyz' | hash sha256",
result: Some(Value::string(
"71c480df93d6ae2f1efad1447c66c9525e316218cf51fc8d9ed832f2daf18b73".to_owned(),
Span::test_data(),
)),
},
Example {
description: "Return the sha256 hash of a string, as binary",
example: "'abcdefghijklmnopqrstuvwxyz' | hash sha256 --binary",
result: Some(Value::binary(
vec![
0x71, 0xc4, 0x80, 0xdf, 0x93, 0xd6, 0xae, 0x2f, 0x1e, 0xfa, 0xd1, 0x44,
0x7c, 0x66, 0xc9, 0x52, 0x5e, 0x31, 0x62, 0x18, 0xcf, 0x51, 0xfc, 0x8d,
0x9e, 0xd8, 0x32, 0xf2, 0xda, 0xf1, 0x8b, 0x73,
],
Span::test_data(),
)),
},
Example {
description: "Return the sha256 hash of a file's contents",
example: "open ./nu_0_24_1_windows.zip | hash sha256",
result: None,
},
]
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::hash::generic_digest::{self, Arguments};
#[test]
fn test_examples() {
crate::test_examples(HashSha256::default())
}
#[test]
fn hash_string() {
let binary = Value::string("abcdefghijklmnopqrstuvwxyz".to_owned(), Span::test_data());
let expected = Value::string(
"71c480df93d6ae2f1efad1447c66c9525e316218cf51fc8d9ed832f2daf18b73".to_owned(),
Span::test_data(),
);
let actual = generic_digest::action::<Sha256>(
&binary,
&Arguments {
cell_paths: None,
binary: false,
},
Span::test_data(),
);
assert_eq!(actual, expected);
}
#[test]
fn hash_bytes() {
let binary = Value::binary(vec![0xC0, 0xFF, 0xEE], Span::test_data());
let expected = Value::string(
"c47a10dc272b1221f0380a2ae0f7d7fa830b3e378f2f5309bbf13f61ad211913".to_owned(),
Span::test_data(),
);
let actual = generic_digest::action::<Sha256>(
&binary,
&Arguments {
cell_paths: None,
binary: false,
},
Span::test_data(),
);
assert_eq!(actual, expected);
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/hash/hash_.rs | crates/nu-command/src/hash/hash_.rs | use nu_engine::{command_prelude::*, get_full_help};
#[derive(Clone)]
pub struct Hash;
impl Command for Hash {
fn name(&self) -> &str {
"hash"
}
fn signature(&self) -> Signature {
Signature::build("hash")
.category(Category::Hash)
.input_output_types(vec![(Type::Nothing, Type::String)])
}
fn description(&self) -> &str {
"Apply hash function."
}
fn extra_description(&self) -> &str {
"You must use one of the following subcommands. Using this command as-is will only produce this help message."
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
Ok(Value::string(get_full_help(self, engine_state, stack), call.head).into_pipeline_data())
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/hash/mod.rs | crates/nu-command/src/hash/mod.rs | mod generic_digest;
mod hash_;
mod md5;
mod sha256;
pub use self::hash_::Hash;
pub use self::md5::HashMd5;
pub use self::sha256::HashSha256;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/hash/md5.rs | crates/nu-command/src/hash/md5.rs | use super::generic_digest::{GenericDigest, HashDigest};
use ::md5::Md5;
use nu_protocol::{Example, Span, Value};
pub type HashMd5 = GenericDigest<Md5>;
impl HashDigest for Md5 {
fn name() -> &'static str {
"md5"
}
fn examples() -> Vec<Example<'static>> {
vec![
Example {
description: "Return the md5 hash of a string, hex-encoded",
example: "'abcdefghijklmnopqrstuvwxyz' | hash md5",
result: Some(Value::string(
"c3fcd3d76192e4007dfb496cca67e13b".to_owned(),
Span::test_data(),
)),
},
Example {
description: "Return the md5 hash of a string, as binary",
example: "'abcdefghijklmnopqrstuvwxyz' | hash md5 --binary",
result: Some(Value::binary(
vec![
0xc3, 0xfc, 0xd3, 0xd7, 0x61, 0x92, 0xe4, 0x00, 0x7d, 0xfb, 0x49, 0x6c,
0xca, 0x67, 0xe1, 0x3b,
],
Span::test_data(),
)),
},
Example {
description: "Return the md5 hash of a file's contents",
example: "open ./nu_0_24_1_windows.zip | hash md5",
result: None,
},
]
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::hash::generic_digest::{self, Arguments};
#[test]
fn test_examples() {
crate::test_examples(HashMd5::default())
}
#[test]
fn hash_string() {
let binary = Value::string("abcdefghijklmnopqrstuvwxyz".to_owned(), Span::test_data());
let expected = Value::string(
"c3fcd3d76192e4007dfb496cca67e13b".to_owned(),
Span::test_data(),
);
let actual = generic_digest::action::<Md5>(
&binary,
&Arguments {
cell_paths: None,
binary: false,
},
Span::test_data(),
);
assert_eq!(actual, expected);
}
#[test]
fn hash_bytes() {
let binary = Value::binary(vec![0xC0, 0xFF, 0xEE], Span::test_data());
let expected = Value::string(
"5f80e231382769b0102b1164cf722d83".to_owned(),
Span::test_data(),
);
let actual = generic_digest::action::<Md5>(
&binary,
&Arguments {
cell_paths: None,
binary: false,
},
Span::test_data(),
);
assert_eq!(actual, expected);
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/hash/generic_digest.rs | crates/nu-command/src/hash/generic_digest.rs | use nu_cmd_base::input_handler::{CmdArgument, operate};
use nu_engine::command_prelude::*;
use std::{io::Write, marker::PhantomData};
pub trait HashDigest: digest::Digest + Clone {
fn name() -> &'static str;
fn examples() -> Vec<Example<'static>>;
}
#[derive(Clone)]
pub struct GenericDigest<D: HashDigest> {
name: String,
description: String,
phantom: PhantomData<D>,
}
impl<D: HashDigest> Default for GenericDigest<D> {
fn default() -> Self {
Self {
name: format!("hash {}", D::name()),
description: format!("Hash a value using the {} hash algorithm.", D::name()),
phantom: PhantomData,
}
}
}
pub(super) struct Arguments {
pub(super) cell_paths: Option<Vec<CellPath>>,
pub(super) binary: bool,
}
impl CmdArgument for Arguments {
fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> {
self.cell_paths.take()
}
}
impl<D> Command for GenericDigest<D>
where
D: HashDigest + Write + Send + Sync + 'static,
digest::Output<D>: core::fmt::LowerHex,
{
fn name(&self) -> &str {
&self.name
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.category(Category::Hash)
.input_output_types(vec![
(Type::String, Type::Any),
(Type::Binary, Type::Any),
(Type::table(), Type::table()),
(Type::record(), Type::record()),
])
.allow_variants_without_examples(true)
.switch(
"binary",
"Output binary instead of hexadecimal representation",
Some('b'),
)
.rest(
"rest",
SyntaxShape::CellPath,
format!("Optionally {} hash data by cell path.", D::name()),
)
}
fn description(&self) -> &str {
&self.description
}
fn examples(&self) -> Vec<Example<'static>> {
D::examples()
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let binary = call.has_flag(engine_state, stack, "binary")?;
let cell_paths: Vec<CellPath> = call.rest(engine_state, stack, 0)?;
let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths);
let mut hasher = D::new();
if let PipelineData::ByteStream(stream, ..) = input {
stream.write_to(&mut hasher)?;
let digest = hasher.finalize();
if binary {
Ok(Value::binary(digest.to_vec(), head).into_pipeline_data())
} else {
Ok(Value::string(format!("{digest:x}"), head).into_pipeline_data())
}
} else {
let args = Arguments { binary, cell_paths };
operate(action::<D>, args, input, head, engine_state.signals())
}
}
}
pub(super) fn action<D>(input: &Value, args: &Arguments, _span: Span) -> Value
where
D: HashDigest,
digest::Output<D>: core::fmt::LowerHex,
{
let span = input.span();
let (bytes, span) = match input {
Value::String { val, .. } => (val.as_bytes(), span),
Value::Binary { val, .. } => (val.as_slice(), span),
// Propagate existing errors
Value::Error { .. } => return input.clone(),
other => {
let span = input.span();
return Value::error(
ShellError::OnlySupportsThisInputType {
exp_input_type: "string or binary".into(),
wrong_type: other.get_type().to_string(),
dst_span: span,
src_span: other.span(),
},
span,
);
}
};
let digest = D::digest(bytes);
if args.binary {
Value::binary(digest.to_vec(), span)
} else {
Value::string(format!("{digest:x}"), span)
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/help/help_pipe_and_redirect.rs | crates/nu-command/src/help/help_pipe_and_redirect.rs | use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct HelpPipeAndRedirect;
impl Command for HelpPipeAndRedirect {
fn name(&self) -> &str {
"help pipe-and-redirect"
}
fn description(&self) -> &str {
"Show help on nushell pipes and redirects."
}
fn extra_description(&self) -> &str {
r#"This command contains basic usage of pipe and redirect symbol, for more detail, check:
https://www.nushell.sh/lang-guide/chapters/pipelines.html"#
}
fn signature(&self) -> Signature {
Signature::build("help pipe-and-redirect")
.category(Category::Core)
.input_output_types(vec![(Type::Nothing, Type::table())])
.allow_variants_without_examples(true)
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let examples = vec![
HelpExamples::new(
"|",
"pipe",
"pipeline stdout of a command to another command",
"^cmd1 | ^cmd2",
),
HelpExamples::new(
"e>|",
"stderr pipe",
"pipeline stderr of a command to another command",
"^cmd1 e>| ^cmd2",
),
HelpExamples::new(
"o+e>|",
"stdout and stderr pipe",
"pipeline stdout and stderr of a command to another command",
"^cmd1 o+e>| ^cmd2",
),
HelpExamples::new(
"o>",
"redirection",
"redirect stdout of a command, overwriting a file",
"^cmd1 o> file.txt",
),
HelpExamples::new(
"e>",
"stderr redirection",
"redirect stderr of a command, overwriting a file",
"^cmd1 e> file.txt",
),
HelpExamples::new(
"o+e>",
"stdout and stderr redirection",
"redirect stdout and stderr of a command, overwriting a file",
"^cmd1 o+e> file.txt",
),
HelpExamples::new(
"o>>",
"redirection append",
"redirect stdout of a command, appending to a file",
"^cmd1 o>> file.txt",
),
HelpExamples::new(
"e>>",
"stderr redirection append",
"redirect stderr of a command, appending to a file",
"^cmd1 e>> file.txt",
),
HelpExamples::new(
"o+e>>",
"stdout and stderr redirection append",
"redirect stdout and stderr of a command, appending to a file",
"^cmd1 o+e>> file.txt",
),
HelpExamples::new(
"o>|",
"",
"UNSUPPORTED, Redirecting stdout to a pipe is the same as normal piping",
"",
),
];
let examples: Vec<Value> = examples
.into_iter()
.map(|x| x.into_val_record(head))
.collect();
Ok(Value::list(examples, head).into_pipeline_data())
}
}
struct HelpExamples {
symbol: String,
name: String,
description: String,
example: String,
}
impl HelpExamples {
fn new(symbol: &str, name: &str, description: &str, example: &str) -> Self {
Self {
symbol: symbol.to_string(),
name: name.to_string(),
description: description.to_string(),
example: example.to_string(),
}
}
fn into_val_record(self, span: Span) -> Value {
Value::record(
record! {
"symbol" => Value::string(self.symbol, span),
"name" => Value::string(self.name, span),
"description" => Value::string(self.description, span),
"example" => Value::string(self.example, span),
},
span,
)
}
}
#[cfg(test)]
mod test {
#[test]
fn test_examples() {
use super::HelpPipeAndRedirect;
use crate::test_examples;
test_examples(HelpPipeAndRedirect {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/help/help_commands.rs | crates/nu-command/src/help/help_commands.rs | use crate::filters::find_internal;
use nu_engine::{command_prelude::*, get_full_help};
#[derive(Clone)]
pub struct HelpCommands;
impl Command for HelpCommands {
fn name(&self) -> &str {
"help commands"
}
fn description(&self) -> &str {
"Show help on nushell commands."
}
fn signature(&self) -> Signature {
Signature::build("help commands")
.category(Category::Core)
.rest(
"rest",
SyntaxShape::String,
"The name of command to get help on.",
)
.named(
"find",
SyntaxShape::String,
"string to find in command names, descriptions, and search terms",
Some('f'),
)
.input_output_types(vec![(Type::Nothing, Type::table())])
.allow_variants_without_examples(true)
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
help_commands(engine_state, stack, call)
}
}
pub fn help_commands(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let find: Option<Spanned<String>> = call.get_flag(engine_state, stack, "find")?;
let rest: Vec<Spanned<String>> = call.rest(engine_state, stack, 0)?;
if let Some(f) = find {
let all_cmds_vec = build_help_commands(engine_state, head);
return find_internal(
all_cmds_vec,
engine_state,
stack,
&f.item,
&["name", "description", "search_terms"],
true,
);
}
if rest.is_empty() {
Ok(build_help_commands(engine_state, head))
} else {
let mut name = String::new();
for r in &rest {
if !name.is_empty() {
name.push(' ');
}
name.push_str(&r.item);
}
if let Some(decl) = engine_state.find_decl(name.as_bytes(), &[]) {
let cmd = engine_state.get_decl(decl);
let help_text = get_full_help(cmd, engine_state, stack);
Ok(Value::string(help_text, call.head).into_pipeline_data())
} else {
Err(ShellError::CommandNotFound {
span: Span::merge_many(rest.iter().map(|s| s.span)),
})
}
}
}
fn build_help_commands(engine_state: &EngineState, span: Span) -> PipelineData {
let commands = engine_state.get_decls_sorted(false);
let mut found_cmds_vec = Vec::new();
for (_, decl_id) in commands {
let decl = engine_state.get_decl(decl_id);
let sig = decl.signature().update_from_command(decl);
let key = sig.name;
let description = sig.description;
let search_terms = sig.search_terms;
let command_type = decl.command_type().to_string();
// Build table of parameters
let param_table = {
let mut vals = vec![];
for required_param in &sig.required_positional {
vals.push(Value::record(
record! {
"name" => Value::string(&required_param.name, span),
"type" => Value::string(required_param.shape.to_string(), span),
"required" => Value::bool(true, span),
"description" => Value::string(&required_param.desc, span),
},
span,
));
}
for optional_param in &sig.optional_positional {
vals.push(Value::record(
record! {
"name" => Value::string(&optional_param.name, span),
"type" => Value::string(optional_param.shape.to_string(), span),
"required" => Value::bool(false, span),
"description" => Value::string(&optional_param.desc, span),
},
span,
));
}
if let Some(rest_positional) = &sig.rest_positional {
vals.push(Value::record(
record! {
"name" => Value::string(format!("...{}", rest_positional.name), span),
"type" => Value::string(rest_positional.shape.to_string(), span),
"required" => Value::bool(false, span),
"description" => Value::string(&rest_positional.desc, span),
},
span,
));
}
for named_param in &sig.named {
let name = if let Some(short) = named_param.short {
if named_param.long.is_empty() {
format!("-{short}")
} else {
format!("--{}(-{})", named_param.long, short)
}
} else {
format!("--{}", named_param.long)
};
let typ = if let Some(arg) = &named_param.arg {
arg.to_string()
} else {
"switch".to_string()
};
vals.push(Value::record(
record! {
"name" => Value::string(name, span),
"type" => Value::string(typ, span),
"required" => Value::bool(named_param.required, span),
"description" => Value::string(&named_param.desc, span),
},
span,
));
}
Value::list(vals, span)
};
// Build the signature input/output table
let input_output_table = {
let mut vals = vec![];
for (input_type, output_type) in sig.input_output_types {
vals.push(Value::record(
record! {
"input" => Value::string(input_type.to_string(), span),
"output" => Value::string(output_type.to_string(), span),
},
span,
));
}
Value::list(vals, span)
};
let record = record! {
"name" => Value::string(key, span),
"category" => Value::string(sig.category.to_string(), span),
"command_type" => Value::string(command_type, span),
"description" => Value::string(description, span),
"params" => param_table,
"input_output" => input_output_table,
"search_terms" => Value::string(search_terms.join(", "), span),
"is_const" => Value::bool(decl.is_const(), span),
};
found_cmds_vec.push(Value::record(record, span));
}
Value::list(found_cmds_vec, span).into_pipeline_data()
}
#[cfg(test)]
mod test {
#[test]
fn test_examples() {
use super::HelpCommands;
use crate::test_examples;
test_examples(HelpCommands {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/help/help_escapes.rs | crates/nu-command/src/help/help_escapes.rs | use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct HelpEscapes;
impl Command for HelpEscapes {
fn name(&self) -> &str {
"help escapes"
}
fn description(&self) -> &str {
"Show help on nushell string escapes."
}
fn signature(&self) -> Signature {
Signature::build("help escapes")
.category(Category::Core)
.input_output_types(vec![(Type::Nothing, Type::table())])
.allow_variants_without_examples(true)
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let escape_info = generate_escape_info();
let mut recs = vec![];
for escape in escape_info {
recs.push(Value::record(
record! {
"sequence" => Value::string(escape.sequence, head),
"output" => Value::string(escape.output, head),
},
head,
));
}
Ok(Value::list(recs, call.head).into_pipeline_data())
}
}
struct EscapeInfo {
sequence: String,
output: String,
}
fn generate_escape_info() -> Vec<EscapeInfo> {
vec![
EscapeInfo {
sequence: "\\\"".into(),
output: "\"".into(),
},
EscapeInfo {
sequence: "\\\'".into(),
output: "\'".into(),
},
EscapeInfo {
sequence: "\\\\".into(),
output: "\\".into(),
},
EscapeInfo {
sequence: "\\/".into(),
output: "/".into(),
},
EscapeInfo {
sequence: "\\(".into(),
output: "(".into(),
},
EscapeInfo {
sequence: "\\)".into(),
output: ")".into(),
},
EscapeInfo {
sequence: "\\{".into(),
output: "{".into(),
},
EscapeInfo {
sequence: "\\}".into(),
output: "}".into(),
},
EscapeInfo {
sequence: "\\$".into(),
output: "$".into(),
},
EscapeInfo {
sequence: "\\^".into(),
output: "^".into(),
},
EscapeInfo {
sequence: "\\#".into(),
output: "#".into(),
},
EscapeInfo {
sequence: "\\|".into(),
output: "|".into(),
},
EscapeInfo {
sequence: "\\~".into(),
output: "~".into(),
},
EscapeInfo {
sequence: "\\a".into(),
output: "alert bell".into(),
},
EscapeInfo {
sequence: "\\b".into(),
output: "backspace".into(),
},
EscapeInfo {
sequence: "\\e".into(),
output: "escape".into(),
},
EscapeInfo {
sequence: "\\f".into(),
output: "form feed".into(),
},
EscapeInfo {
sequence: "\\n".into(),
output: "newline (line feed)".into(),
},
EscapeInfo {
sequence: "\\r".into(),
output: "carriage return".into(),
},
EscapeInfo {
sequence: "\\t".into(),
output: "tab".into(),
},
EscapeInfo {
sequence: "\\u{X...}".into(),
output: "a single unicode character, where X... is 1-6 digits (0-9, A-F)".into(),
},
]
}
#[cfg(test)]
mod test {
#[test]
fn test_examples() {
use super::HelpEscapes;
use crate::test_examples;
test_examples(HelpEscapes {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/help/help_externs.rs | crates/nu-command/src/help/help_externs.rs | use crate::filters::find_internal;
use nu_engine::{command_prelude::*, get_full_help, scope::ScopeData};
#[derive(Clone)]
pub struct HelpExterns;
impl Command for HelpExterns {
fn name(&self) -> &str {
"help externs"
}
fn description(&self) -> &str {
"Show help on nushell externs."
}
fn signature(&self) -> Signature {
Signature::build("help externs")
.category(Category::Core)
.rest(
"rest",
SyntaxShape::String,
"The name of extern to get help on.",
)
.named(
"find",
SyntaxShape::String,
"string to find in extern names and descriptions",
Some('f'),
)
.input_output_types(vec![(Type::Nothing, Type::table())])
.allow_variants_without_examples(true)
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "show all externs",
example: "help externs",
result: None,
},
Example {
description: "show help for single extern",
example: "help externs smth",
result: None,
},
Example {
description: "search for string in extern names and descriptions",
example: "help externs --find smth",
result: None,
},
]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
help_externs(engine_state, stack, call)
}
}
pub fn help_externs(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let find: Option<Spanned<String>> = call.get_flag(engine_state, stack, "find")?;
let rest: Vec<Spanned<String>> = call.rest(engine_state, stack, 0)?;
if let Some(f) = find {
let all_cmds_vec = build_help_externs(engine_state, stack, head);
return find_internal(
all_cmds_vec,
engine_state,
stack,
&f.item,
&["name", "description"],
true,
);
}
if rest.is_empty() {
Ok(build_help_externs(engine_state, stack, head))
} else {
let mut name = String::new();
for r in &rest {
if !name.is_empty() {
name.push(' ');
}
name.push_str(&r.item);
}
if let Some(decl) = engine_state.find_decl(name.as_bytes(), &[]) {
let cmd = engine_state.get_decl(decl);
let help_text = get_full_help(cmd, engine_state, stack);
Ok(Value::string(help_text, call.head).into_pipeline_data())
} else {
Err(ShellError::CommandNotFound {
span: Span::merge_many(rest.iter().map(|s| s.span)),
})
}
}
}
fn build_help_externs(engine_state: &EngineState, stack: &Stack, span: Span) -> PipelineData {
let mut scope = ScopeData::new(engine_state, stack);
scope.populate_decls();
Value::list(scope.collect_externs(span), span).into_pipeline_data()
}
#[cfg(test)]
mod test {
#[test]
fn test_examples() {
use super::HelpExterns;
use crate::test_examples;
test_examples(HelpExterns {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/help/help_aliases.rs | crates/nu-command/src/help/help_aliases.rs | use crate::filters::find_internal;
use nu_engine::{command_prelude::*, get_full_help, scope::ScopeData};
#[derive(Clone)]
pub struct HelpAliases;
impl Command for HelpAliases {
fn name(&self) -> &str {
"help aliases"
}
fn description(&self) -> &str {
"Show help on nushell aliases."
}
fn signature(&self) -> Signature {
Signature::build("help aliases")
.category(Category::Core)
.rest(
"rest",
SyntaxShape::String,
"The name of alias to get help on.",
)
.named(
"find",
SyntaxShape::String,
"string to find in alias names and descriptions",
Some('f'),
)
.input_output_types(vec![(Type::Nothing, Type::table())])
.allow_variants_without_examples(true)
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "show all aliases",
example: "help aliases",
result: None,
},
Example {
description: "show help for single alias",
example: "help aliases my-alias",
result: None,
},
Example {
description: "search for string in alias names and descriptions",
example: "help aliases --find my-alias",
result: None,
},
]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
help_aliases(engine_state, stack, call)
}
}
pub fn help_aliases(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let find: Option<Spanned<String>> = call.get_flag(engine_state, stack, "find")?;
let rest: Vec<Spanned<String>> = call.rest(engine_state, stack, 0)?;
if let Some(f) = find {
let all_cmds_vec = build_help_aliases(engine_state, stack, head);
return find_internal(
all_cmds_vec,
engine_state,
stack,
&f.item,
&["name", "description"],
true,
);
}
if rest.is_empty() {
Ok(build_help_aliases(engine_state, stack, head))
} else {
let mut name = String::new();
for r in &rest {
if !name.is_empty() {
name.push(' ');
}
name.push_str(&r.item);
}
let Some(alias) = engine_state.find_decl(name.as_bytes(), &[]) else {
return Err(ShellError::AliasNotFound {
span: Span::merge_many(rest.iter().map(|s| s.span)),
});
};
let alias = engine_state.get_decl(alias);
if alias.as_alias().is_none() {
return Err(ShellError::AliasNotFound {
span: Span::merge_many(rest.iter().map(|s| s.span)),
});
};
let help = get_full_help(alias, engine_state, stack);
Ok(Value::string(help, call.head).into_pipeline_data())
}
}
fn build_help_aliases(engine_state: &EngineState, stack: &Stack, span: Span) -> PipelineData {
let mut scope_data = ScopeData::new(engine_state, stack);
scope_data.populate_decls();
Value::list(scope_data.collect_aliases(span), span).into_pipeline_data()
}
#[cfg(test)]
mod test {
#[test]
fn test_examples() {
use super::HelpAliases;
use crate::test_examples;
test_examples(HelpAliases {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/help/mod.rs | crates/nu-command/src/help/mod.rs | mod help_;
mod help_aliases;
mod help_commands;
mod help_escapes;
mod help_externs;
mod help_modules;
mod help_operators;
mod help_pipe_and_redirect;
pub use help_::Help;
pub use help_aliases::HelpAliases;
pub use help_commands::HelpCommands;
pub use help_escapes::HelpEscapes;
pub use help_externs::HelpExterns;
pub use help_modules::HelpModules;
pub use help_operators::HelpOperators;
pub use help_pipe_and_redirect::HelpPipeAndRedirect;
pub(crate) use help_aliases::help_aliases;
pub(crate) use help_commands::help_commands;
pub(crate) use help_modules::help_modules;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/help/help_modules.rs | crates/nu-command/src/help/help_modules.rs | use crate::filters::find_internal;
use nu_engine::{command_prelude::*, scope::ScopeData};
use nu_protocol::DeclId;
#[derive(Clone)]
pub struct HelpModules;
impl Command for HelpModules {
fn name(&self) -> &str {
"help modules"
}
fn description(&self) -> &str {
"Show help on nushell modules."
}
fn extra_description(&self) -> &str {
r#"When requesting help for a single module, its commands and aliases will be highlighted if they
are also available in the current scope. Commands/aliases that were imported under a different name
(such as with a prefix after `use some-module`) will be highlighted in parentheses."#
}
fn signature(&self) -> Signature {
Signature::build("help modules")
.category(Category::Core)
.rest(
"rest",
SyntaxShape::String,
"The name of module to get help on.",
)
.named(
"find",
SyntaxShape::String,
"string to find in module names and descriptions",
Some('f'),
)
.input_output_types(vec![(Type::Nothing, Type::table())])
.allow_variants_without_examples(true)
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "show all modules",
example: "help modules",
result: None,
},
Example {
description: "show help for single module",
example: "help modules my-module",
result: None,
},
Example {
description: "search for string in module names and descriptions",
example: "help modules --find my-module",
result: None,
},
]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
help_modules(engine_state, stack, call)
}
}
pub fn help_modules(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let find: Option<Spanned<String>> = call.get_flag(engine_state, stack, "find")?;
let rest: Vec<Spanned<String>> = call.rest(engine_state, stack, 0)?;
if let Some(f) = find {
let all_cmds_vec = build_help_modules(engine_state, stack, head);
return find_internal(
all_cmds_vec,
engine_state,
stack,
&f.item,
&["name", "description"],
true,
);
}
if rest.is_empty() {
Ok(build_help_modules(engine_state, stack, head))
} else {
let mut name = String::new();
for r in &rest {
if !name.is_empty() {
name.push(' ');
}
name.push_str(&r.item);
}
let Some(module_id) = engine_state.find_module(name.as_bytes(), &[]) else {
return Err(ShellError::ModuleNotFoundAtRuntime {
mod_name: name,
span: Span::merge_many(rest.iter().map(|s| s.span)),
});
};
let module = engine_state.get_module(module_id);
let module_desc = engine_state.build_module_desc(module_id);
// TODO: merge this into documentation.rs at some point
const G: &str = "\x1b[32m"; // green
const C: &str = "\x1b[36m"; // cyan
const CB: &str = "\x1b[1;36m"; // cyan bold
const RESET: &str = "\x1b[0m"; // reset
let mut long_desc = String::new();
if let Some((desc, extra_desc)) = module_desc {
long_desc.push_str(&desc);
long_desc.push_str("\n\n");
if !extra_desc.is_empty() {
long_desc.push_str(&extra_desc);
long_desc.push_str("\n\n");
}
}
long_desc.push_str(&format!("{G}Module{RESET}: {C}{name}{RESET}"));
long_desc.push_str("\n\n");
if !module.decls.is_empty() || module.main.is_some() {
let commands: Vec<(Vec<u8>, DeclId)> = engine_state
.get_decls_sorted(false)
.into_iter()
.filter(|(_, id)| !engine_state.get_decl(*id).is_alias())
.collect();
let mut module_commands: Vec<(Vec<u8>, DeclId)> = module
.decls()
.into_iter()
.filter(|(_, id)| !engine_state.get_decl(*id).is_alias())
.collect();
module_commands.sort_by(|a, b| a.0.cmp(&b.0));
let commands_str = module_commands
.iter()
.map(|(name_bytes, id)| {
let name = String::from_utf8_lossy(name_bytes);
if let Some((used_name_bytes, _)) =
commands.iter().find(|(_, decl_id)| id == decl_id)
{
if engine_state.find_decl(name.as_bytes(), &[]).is_some() {
format!("{CB}{name}{RESET}")
} else {
let command_name = String::from_utf8_lossy(used_name_bytes);
format!("{name} ({CB}{command_name}{RESET})")
}
} else {
format!("{name}")
}
})
.collect::<Vec<String>>()
.join(", ");
long_desc.push_str(&format!("{G}Exported commands{RESET}:\n {commands_str}"));
long_desc.push_str("\n\n");
}
if !module.decls.is_empty() {
let aliases: Vec<(Vec<u8>, DeclId)> = engine_state
.get_decls_sorted(false)
.into_iter()
.filter(|(_, id)| engine_state.get_decl(*id).is_alias())
.collect();
let mut module_aliases: Vec<(Vec<u8>, DeclId)> = module
.decls()
.into_iter()
.filter(|(_, id)| engine_state.get_decl(*id).is_alias())
.collect();
module_aliases.sort_by(|a, b| a.0.cmp(&b.0));
let aliases_str = module_aliases
.iter()
.map(|(name_bytes, id)| {
let name = String::from_utf8_lossy(name_bytes);
if let Some((used_name_bytes, _)) =
aliases.iter().find(|(_, alias_id)| id == alias_id)
{
if engine_state.find_decl(name.as_bytes(), &[]).is_some() {
format!("{CB}{name}{RESET}")
} else {
let alias_name = String::from_utf8_lossy(used_name_bytes);
format!("{name} ({CB}{alias_name}{RESET})")
}
} else {
format!("{name}")
}
})
.collect::<Vec<String>>()
.join(", ");
long_desc.push_str(&format!("{G}Exported aliases{RESET}:\n {aliases_str}"));
long_desc.push_str("\n\n");
}
if module.env_block.is_some() {
long_desc.push_str(&format!("This module {C}exports{RESET} environment."));
} else {
long_desc.push_str(&format!(
"This module {C}does not export{RESET} environment."
));
}
let config = stack.get_config(engine_state);
if !config.use_ansi_coloring.get(engine_state) {
long_desc = nu_utils::strip_ansi_string_likely(long_desc);
}
Ok(Value::string(long_desc, call.head).into_pipeline_data())
}
}
fn build_help_modules(engine_state: &EngineState, stack: &Stack, span: Span) -> PipelineData {
let mut scope_data = ScopeData::new(engine_state, stack);
scope_data.populate_modules();
Value::list(scope_data.collect_modules(span), span).into_pipeline_data()
}
#[cfg(test)]
mod test {
#[test]
fn test_examples() {
use super::HelpModules;
use crate::test_examples;
test_examples(HelpModules {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/help/help_operators.rs | crates/nu-command/src/help/help_operators.rs | use nu_engine::command_prelude::*;
use nu_protocol::ast::{Assignment, Bits, Boolean, Comparison, Math, Operator};
use strum::IntoEnumIterator;
#[derive(Clone)]
pub struct HelpOperators;
impl Command for HelpOperators {
fn name(&self) -> &str {
"help operators"
}
fn description(&self) -> &str {
"Show help on nushell operators."
}
fn signature(&self) -> Signature {
Signature::build("help operators")
.category(Category::Core)
.input_output_types(vec![(Type::Nothing, Type::table())])
.allow_variants_without_examples(true)
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let mut operators = Assignment::iter()
.map(Operator::Assignment)
.chain(Comparison::iter().map(Operator::Comparison))
.chain(Math::iter().map(Operator::Math))
.chain(Bits::iter().map(Operator::Bits))
.chain(Boolean::iter().map(Operator::Boolean))
.map(|op| {
if op == Operator::Comparison(Comparison::RegexMatch) {
Value::record(
record! {
"type" => Value::string(op_type(&op), head),
"operator" => Value::string("=~, like", head),
"name" => Value::string(name(&op), head),
"description" => Value::string(description(&op), head),
"precedence" => Value::int(op.precedence().into(), head),
},
head,
)
} else if op == Operator::Comparison(Comparison::NotRegexMatch) {
Value::record(
record! {
"type" => Value::string(op_type(&op), head),
"operator" => Value::string("!~, not-like", head),
"name" => Value::string(name(&op), head),
"description" => Value::string(description(&op), head),
"precedence" => Value::int(op.precedence().into(), head),
},
head,
)
} else {
Value::record(
record! {
"type" => Value::string(op_type(&op), head),
"operator" => Value::string(op.to_string(), head),
"name" => Value::string(name(&op), head),
"description" => Value::string(description(&op), head),
"precedence" => Value::int(op.precedence().into(), head),
},
head,
)
}
})
.collect::<Vec<_>>();
operators.push(Value::record(
record! {
"type" => Value::string("Boolean", head),
"operator" => Value::string("not", head),
"name" => Value::string("Not", head),
"description" => Value::string("Negates a value or expression.", head),
"precedence" => Value::int(55, head),
},
head,
));
Ok(Value::list(operators, head).into_pipeline_data())
}
}
fn op_type(operator: &Operator) -> &'static str {
match operator {
Operator::Comparison(_) => "Comparison",
Operator::Math(_) => "Math",
Operator::Boolean(_) => "Boolean",
Operator::Bits(_) => "Bitwise",
Operator::Assignment(_) => "Assignment",
}
}
fn name(operator: &Operator) -> String {
match operator {
Operator::Comparison(op) => format!("{op:?}"),
Operator::Math(op) => format!("{op:?}"),
Operator::Boolean(op) => format!("{op:?}"),
Operator::Bits(op) => format!("{op:?}"),
Operator::Assignment(op) => format!("{op:?}"),
}
}
fn description(operator: &Operator) -> &'static str {
match operator {
Operator::Comparison(Comparison::Equal) => "Checks if two values are equal.",
Operator::Comparison(Comparison::NotEqual) => "Checks if two values are not equal.",
Operator::Comparison(Comparison::LessThan) => "Checks if a value is less than another.",
Operator::Comparison(Comparison::GreaterThan) => {
"Checks if a value is greater than another."
}
Operator::Comparison(Comparison::LessThanOrEqual) => {
"Checks if a value is less than or equal to another."
}
Operator::Comparison(Comparison::GreaterThanOrEqual) => {
"Checks if a value is greater than or equal to another."
}
Operator::Comparison(Comparison::RegexMatch) => {
"Checks if a value matches a regular expression."
}
Operator::Comparison(Comparison::NotRegexMatch) => {
"Checks if a value does not match a regular expression."
}
Operator::Comparison(Comparison::In) => {
"Checks if a value is in a list, is part of a string, or is a key in a record."
}
Operator::Comparison(Comparison::NotIn) => {
"Checks if a value is not in a list, is not part of a string, or is not a key in a record."
}
Operator::Comparison(Comparison::Has) => {
"Checks if a list contains a value, a string contains another, or if a record has a key."
}
Operator::Comparison(Comparison::NotHas) => {
"Checks if a list does not contain a value, a string does not contain another, or if a record does not have a key."
}
Operator::Comparison(Comparison::StartsWith) => "Checks if a string starts with another.",
Operator::Comparison(Comparison::NotStartsWith) => {
"Checks if a string does not start with another."
}
Operator::Comparison(Comparison::EndsWith) => "Checks if a string ends with another.",
Operator::Comparison(Comparison::NotEndsWith) => {
"Checks if a string does not end with another."
}
Operator::Math(Math::Add) => "Adds two values.",
Operator::Math(Math::Subtract) => "Subtracts two values.",
Operator::Math(Math::Multiply) => "Multiplies two values.",
Operator::Math(Math::Divide) => "Divides two values.",
Operator::Math(Math::FloorDivide) => "Divides two values and floors the result.",
Operator::Math(Math::Modulo) => "Divides two values and returns the remainder.",
Operator::Math(Math::Pow) => "Raises one value to the power of another.",
Operator::Math(Math::Concatenate) => {
"Concatenates two lists, two strings, or two binary values."
}
Operator::Boolean(Boolean::Or) => "Checks if either value is true.",
Operator::Boolean(Boolean::Xor) => "Checks if one value is true and the other is false.",
Operator::Boolean(Boolean::And) => "Checks if both values are true.",
Operator::Bits(Bits::BitOr) => "Performs a bitwise OR on two values.",
Operator::Bits(Bits::BitXor) => "Performs a bitwise XOR on two values.",
Operator::Bits(Bits::BitAnd) => "Performs a bitwise AND on two values.",
Operator::Bits(Bits::ShiftLeft) => "Bitwise shifts a value left by another.",
Operator::Bits(Bits::ShiftRight) => "Bitwise shifts a value right by another.",
Operator::Assignment(Assignment::Assign) => "Assigns a value to a variable.",
Operator::Assignment(Assignment::AddAssign) => "Adds a value to a variable.",
Operator::Assignment(Assignment::SubtractAssign) => "Subtracts a value from a variable.",
Operator::Assignment(Assignment::MultiplyAssign) => "Multiplies a variable by a value.",
Operator::Assignment(Assignment::DivideAssign) => "Divides a variable by a value.",
Operator::Assignment(Assignment::ConcatenateAssign) => {
"Concatenates a list, a string, or a binary value to a variable of the same type."
}
}
}
#[cfg(test)]
mod test {
#[test]
fn test_examples() {
use super::HelpOperators;
use crate::test_examples;
test_examples(HelpOperators {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/help/help_.rs | crates/nu-command/src/help/help_.rs | use crate::help::{help_aliases, help_commands, help_modules};
use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct Help;
impl Command for Help {
fn name(&self) -> &str {
"help"
}
fn signature(&self) -> Signature {
Signature::build("help")
.input_output_types(vec![(Type::Nothing, Type::Any)])
.rest(
"rest",
SyntaxShape::String,
"The name of command, alias or module to get help on.",
)
.named(
"find",
SyntaxShape::String,
"string to find in command names, descriptions, and search terms",
Some('f'),
)
.category(Category::Core)
}
fn description(&self) -> &str {
"Display help information about different parts of Nushell."
}
fn extra_description(&self) -> &str {
r#"`help word` searches for "word" in commands, aliases and modules, in that order.
If you want your own help implementation, create a custom command named `help` and it will also be used for `--help` invocations.
There already is an alternative `help` command in the standard library you can try with `use std/help`."#
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let find: Option<Spanned<String>> = call.get_flag(engine_state, stack, "find")?;
let rest: Vec<Spanned<String>> = call.rest(engine_state, stack, 0)?;
if rest.is_empty() && find.is_none() {
let msg = r#"Welcome to Nushell.
Here are some tips to help you get started.
* help -h or help help - show available `help` subcommands and examples
* help commands - list all available commands
* help <name> - display help about a particular command, alias, or module
* help --find <text to search> - search through all help commands table
Nushell works on the idea of a "pipeline". Pipelines are commands connected with the '|' character.
Each stage in the pipeline works together to load, parse, and display information to you.
[Examples]
List the files in the current directory, sorted by size:
ls | sort-by size
Get the current system host name:
sys host | get hostname
Get the processes on your system actively using CPU:
ps | where cpu > 0
You can also learn more at https://www.nushell.sh/book/"#;
Ok(Value::string(msg, head).into_pipeline_data())
} else if find.is_some() {
help_commands(engine_state, stack, call)
} else {
let result = help_aliases(engine_state, stack, call);
let result = if let Err(ShellError::AliasNotFound { .. }) = result {
help_commands(engine_state, stack, call)
} else {
result
};
let result = if let Err(ShellError::CommandNotFound { .. }) = result {
help_modules(engine_state, stack, call)
} else {
result
};
if let Err(ShellError::ModuleNotFoundAtRuntime {
mod_name: _,
span: _,
}) = result
{
Err(ShellError::NotFound {
span: Span::merge_many(rest.iter().map(|s| s.span)),
})
} else {
result
}
}
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "show help for single command, alias, or module",
example: "help match",
result: None,
},
Example {
description: "show help for single sub-command, alias, or module",
example: "help str join",
result: None,
},
Example {
description: "search for string in command names, descriptions, and search terms",
example: "help --find char",
result: None,
},
]
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/date/humanize.rs | crates/nu-command/src/date/humanize.rs | use crate::date::utils::parse_date_from_string;
use chrono::{DateTime, FixedOffset, Local};
use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct DateHumanize;
impl Command for DateHumanize {
fn name(&self) -> &str {
"date humanize"
}
fn signature(&self) -> Signature {
Signature::build("date humanize")
.input_output_types(vec![
(Type::Date, Type::String),
(Type::String, Type::String),
])
.allow_variants_without_examples(true)
.category(Category::Date)
}
fn description(&self) -> &str {
"Print a 'humanized' format for the date, relative to now."
}
fn search_terms(&self) -> Vec<&str> {
vec![
"relative",
"now",
"today",
"tomorrow",
"yesterday",
"weekday",
"weekday_name",
"timezone",
]
}
fn run(
&self,
engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
// This doesn't match explicit nulls
if let PipelineData::Empty = input {
return Err(ShellError::PipelineEmpty { dst_span: head });
}
input.map(move |value| helper(value, head), engine_state.signals())
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
description: "Print a 'humanized' format for the date, relative to now.",
example: r#""2021-10-22 20:00:12 +01:00" | date humanize"#,
result: None,
}]
}
}
fn helper(value: Value, head: Span) -> Value {
let span = value.span();
match value {
Value::Nothing { .. } => {
let dt = Local::now();
Value::string(humanize_date(dt.with_timezone(dt.offset())), head)
}
Value::String { val, .. } => {
let dt = parse_date_from_string(&val, span);
match dt {
Ok(x) => Value::string(humanize_date(x), head),
Err(e) => e,
}
}
Value::Date { val, .. } => Value::string(humanize_date(val), head),
_ => Value::error(
ShellError::OnlySupportsThisInputType {
exp_input_type: "date, string (that represents datetime), or nothing".into(),
wrong_type: value.get_type().to_string(),
dst_span: head,
src_span: span,
},
head,
),
}
}
fn humanize_date(dt: DateTime<FixedOffset>) -> String {
nu_protocol::human_time_from_now(&dt).to_string()
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(DateHumanize {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/date/parser.rs | crates/nu-command/src/date/parser.rs | // Modified from chrono::format::scan
use chrono::{DateTime, FixedOffset, Local, Offset, TimeZone};
use chrono_tz::Tz;
use titlecase::titlecase;
#[derive(Debug, Clone, PartialEq, Eq, Copy)]
pub enum ParseErrorKind {
/// Given field is out of permitted range.
OutOfRange,
/// The input string has some invalid character sequence for given formatting items.
Invalid,
/// The input string has been prematurely ended.
TooShort,
}
pub fn datetime_in_timezone(
dt: &DateTime<FixedOffset>,
s: &str,
) -> Result<DateTime<FixedOffset>, ParseErrorKind> {
match timezone_offset_internal(s, true, true) {
Ok(offset) => match FixedOffset::east_opt(offset) {
Some(offset) => Ok(dt.with_timezone(&offset)),
None => Err(ParseErrorKind::OutOfRange),
},
Err(ParseErrorKind::Invalid) => {
if s.eq_ignore_ascii_case("local") {
Ok(dt.with_timezone(Local::now().offset()))
} else {
let tz: Tz = parse_timezone_internal(s)?;
let offset = tz.offset_from_utc_datetime(&dt.naive_utc()).fix();
Ok(dt.with_timezone(&offset))
}
}
Err(e) => Err(e),
}
}
fn parse_timezone_internal(s: &str) -> Result<Tz, ParseErrorKind> {
if let Ok(tz) = s.parse() {
Ok(tz)
} else if let Ok(tz) = titlecase(s).parse() {
Ok(tz)
} else if let Ok(tz) = s.to_uppercase().parse() {
Ok(tz)
} else {
Err(ParseErrorKind::Invalid)
}
}
fn timezone_offset_internal(
mut s: &str,
consume_colon: bool,
allow_missing_minutes: bool,
) -> Result<i32, ParseErrorKind> {
fn digits(s: &str) -> Result<(u8, u8), ParseErrorKind> {
let b = s.as_bytes();
if b.len() < 2 {
Err(ParseErrorKind::TooShort)
} else {
Ok((b[0], b[1]))
}
}
let negative = match s.as_bytes().first() {
Some(&b'+') => false,
Some(&b'-') => true,
Some(_) => return Err(ParseErrorKind::Invalid),
None => return Err(ParseErrorKind::TooShort),
};
s = &s[1..];
// hours (00--99)
let hours = match digits(s)? {
(h1 @ b'0'..=b'9', h2 @ b'0'..=b'9') => i32::from((h1 - b'0') * 10 + (h2 - b'0')),
_ => return Err(ParseErrorKind::Invalid),
};
s = &s[2..];
// colons (and possibly other separators)
if consume_colon {
s = s.trim_start_matches(|c: char| c == ':' || c.is_whitespace());
}
// minutes (00--59)
// if the next two items are digits then we have to add minutes
let minutes = if let Ok(ds) = digits(s) {
match ds {
(m1 @ b'0'..=b'5', m2 @ b'0'..=b'9') => i32::from((m1 - b'0') * 10 + (m2 - b'0')),
(b'6'..=b'9', b'0'..=b'9') => return Err(ParseErrorKind::OutOfRange),
_ => return Err(ParseErrorKind::Invalid),
}
} else if allow_missing_minutes {
0
} else {
return Err(ParseErrorKind::TooShort);
};
match s.len() {
len if len >= 2 => &s[2..],
0 => s,
_ => return Err(ParseErrorKind::TooShort),
};
let seconds = hours * 3600 + minutes * 60;
Ok(if negative { -seconds } else { seconds })
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/date/from_human.rs | crates/nu-command/src/date/from_human.rs | use chrono::{Local, TimeZone};
use human_date_parser::{ParseResult, from_human_time};
use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct DateFromHuman;
impl Command for DateFromHuman {
fn name(&self) -> &str {
"date from-human"
}
fn signature(&self) -> Signature {
Signature::build("date from-human")
.input_output_types(vec![
(Type::String, Type::Date),
(Type::Nothing, Type::table()),
])
.allow_variants_without_examples(true)
.switch(
"list",
"Show human-readable datetime parsing examples",
Some('l'),
)
.category(Category::Date)
}
fn description(&self) -> &str {
"Convert a human readable datetime string to a datetime."
}
fn search_terms(&self) -> Vec<&str> {
vec![
"relative",
"now",
"today",
"tomorrow",
"yesterday",
"weekday",
"weekday_name",
"timezone",
]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
if call.has_flag(engine_state, stack, "list")? {
return Ok(list_human_readable_examples(call.head).into_pipeline_data());
}
let head = call.head;
// This doesn't match explicit nulls
if let PipelineData::Empty = input {
return Err(ShellError::PipelineEmpty { dst_span: head });
}
input.map(move |value| helper(value, head), engine_state.signals())
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Parsing human readable datetime",
example: "'Today at 18:30' | date from-human",
result: None,
},
Example {
description: "Parsing human readable datetime",
example: "'Last Friday at 19:45' | date from-human",
result: None,
},
Example {
description: "Parsing human readable datetime",
example: "'In 5 minutes and 30 seconds' | date from-human",
result: None,
},
Example {
description: "PShow human-readable datetime parsing examples",
example: "date from-human --list",
result: None,
},
]
}
}
fn helper(value: Value, head: Span) -> Value {
let span = value.span();
let input_val = match value {
Value::String { val, .. } => val,
other => {
return Value::error(
ShellError::OnlySupportsThisInputType {
exp_input_type: "string".to_string(),
wrong_type: other.get_type().to_string(),
dst_span: head,
src_span: span,
},
span,
);
}
};
let now = Local::now();
if let Ok(date) = from_human_time(&input_val, now.naive_local()) {
match date {
ParseResult::Date(date) => {
let time = now.time();
let combined = date.and_time(time);
let local_offset = *now.offset();
let dt_fixed = TimeZone::from_local_datetime(&local_offset, &combined)
.single()
.unwrap_or_default();
return Value::date(dt_fixed, span);
}
ParseResult::DateTime(date) => {
let local_offset = *now.offset();
let dt_fixed = match local_offset.from_local_datetime(&date) {
chrono::LocalResult::Single(dt) => dt,
chrono::LocalResult::Ambiguous(_, _) => {
return Value::error(
ShellError::DatetimeParseError {
msg: "Ambiguous datetime".to_string(),
span,
},
span,
);
}
chrono::LocalResult::None => {
return Value::error(
ShellError::DatetimeParseError {
msg: "Invalid datetime".to_string(),
span,
},
span,
);
}
};
return Value::date(dt_fixed, span);
}
ParseResult::Time(time) => {
let date = now.date_naive();
let combined = date.and_time(time);
let local_offset = *now.offset();
let dt_fixed = TimeZone::from_local_datetime(&local_offset, &combined)
.single()
.unwrap_or_default();
return Value::date(dt_fixed, span);
}
}
}
match from_human_time(&input_val, now.naive_local()) {
Ok(date) => match date {
ParseResult::Date(date) => {
let time = now.time();
let combined = date.and_time(time);
let local_offset = *now.offset();
let dt_fixed = TimeZone::from_local_datetime(&local_offset, &combined)
.single()
.unwrap_or_default();
Value::date(dt_fixed, span)
}
ParseResult::DateTime(date) => {
let local_offset = *now.offset();
let dt_fixed = match local_offset.from_local_datetime(&date) {
chrono::LocalResult::Single(dt) => dt,
chrono::LocalResult::Ambiguous(_, _) => {
return Value::error(
ShellError::DatetimeParseError {
msg: "Ambiguous datetime".to_string(),
span,
},
span,
);
}
chrono::LocalResult::None => {
return Value::error(
ShellError::DatetimeParseError {
msg: "Invalid datetime".to_string(),
span,
},
span,
);
}
};
Value::date(dt_fixed, span)
}
ParseResult::Time(time) => {
let date = now.date_naive();
let combined = date.and_time(time);
let local_offset = *now.offset();
let dt_fixed = TimeZone::from_local_datetime(&local_offset, &combined)
.single()
.unwrap_or_default();
Value::date(dt_fixed, span)
}
},
Err(_) => Value::error(
ShellError::IncorrectValue {
msg: "Cannot parse as humanized date".to_string(),
val_span: head,
call_span: span,
},
span,
),
}
}
fn list_human_readable_examples(span: Span) -> Value {
let examples: Vec<String> = vec![
"Today 18:30".into(),
"2022-11-07 13:25:30".into(),
"15:20 Friday".into(),
"This Friday 17:00".into(),
"13:25, Next Tuesday".into(),
"Last Friday at 19:45".into(),
"In 3 days".into(),
"In 2 hours".into(),
"10 hours and 5 minutes ago".into(),
"1 years ago".into(),
"A year ago".into(),
"A month ago".into(),
"A week ago".into(),
"A day ago".into(),
"An hour ago".into(),
"A minute ago".into(),
"A second ago".into(),
"Now".into(),
];
let records = examples
.iter()
.map(|s| {
Value::record(
record! {
"parseable human datetime examples" => Value::test_string(s.to_string()),
"result" => helper(Value::test_string(s.to_string()), span),
},
span,
)
})
.collect::<Vec<Value>>();
Value::list(records, span)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(DateFromHuman {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/date/date_.rs | crates/nu-command/src/date/date_.rs | use nu_engine::{command_prelude::*, get_full_help};
#[derive(Clone)]
pub struct Date;
impl Command for Date {
fn name(&self) -> &str {
"date"
}
fn signature(&self) -> Signature {
Signature::build("date")
.category(Category::Date)
.input_output_types(vec![(Type::Nothing, Type::String)])
}
fn description(&self) -> &str {
"Date-related commands."
}
fn extra_description(&self) -> &str {
"You must use one of the following subcommands. Using this command as-is will only produce this help message."
}
fn search_terms(&self) -> Vec<&str> {
vec![
"time",
"now",
"today",
"tomorrow",
"yesterday",
"weekday",
"weekday_name",
"timezone",
]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
Ok(Value::string(get_full_help(self, engine_state, stack), call.head).into_pipeline_data())
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/date/utils.rs | crates/nu-command/src/date/utils.rs | use chrono::{DateTime, FixedOffset, Local, LocalResult, TimeZone};
use nu_protocol::{ShellError, Span, Value, record};
pub(crate) fn parse_date_from_string(
input: &str,
span: Span,
) -> Result<DateTime<FixedOffset>, Value> {
match dtparse::parse(input) {
Ok((native_dt, fixed_offset)) => {
let offset = match fixed_offset {
Some(offset) => offset,
None => *Local
.from_local_datetime(&native_dt)
.single()
.unwrap_or_default()
.offset(),
};
match offset.from_local_datetime(&native_dt) {
LocalResult::Single(d) => Ok(d),
LocalResult::Ambiguous(d, _) => Ok(d),
LocalResult::None => Err(Value::error(
ShellError::DatetimeParseError {
msg: input.into(),
span,
},
span,
)),
}
}
Err(_) => Err(Value::error(
ShellError::DatetimeParseError {
msg: input.into(),
span,
},
span,
)),
}
}
/// Generates a table containing available datetime format specifiers
///
/// # Arguments
/// * `head` - use the call's head
/// * `show_parse_only_formats` - whether parse-only format specifiers (that can't be outputted) should be shown. Should only be used for `into datetime`, not `format date`
pub(crate) fn generate_strftime_list(head: Span, show_parse_only_formats: bool) -> Value {
let now = Local::now();
struct FormatSpecification<'a> {
spec: &'a str,
description: &'a str,
}
let specifications = [
FormatSpecification {
spec: "%Y",
description: "The full proleptic Gregorian year, zero-padded to 4 digits.",
},
FormatSpecification {
spec: "%C",
description: "The proleptic Gregorian year divided by 100, zero-padded to 2 digits.",
},
FormatSpecification {
spec: "%y",
description: "The proleptic Gregorian year modulo 100, zero-padded to 2 digits.",
},
FormatSpecification {
spec: "%m",
description: "Month number (01--12), zero-padded to 2 digits.",
},
FormatSpecification {
spec: "%b",
description: "Abbreviated month name. Always 3 letters.",
},
FormatSpecification {
spec: "%B",
description: "Full month name. Also accepts corresponding abbreviation in parsing.",
},
FormatSpecification {
spec: "%h",
description: "Same as %b.",
},
FormatSpecification {
spec: "%d",
description: "Day number (01--31), zero-padded to 2 digits.",
},
FormatSpecification {
spec: "%e",
description: "Same as %d but space-padded. Same as %_d.",
},
FormatSpecification {
spec: "%a",
description: "Abbreviated weekday name. Always 3 letters.",
},
FormatSpecification {
spec: "%A",
description: "Full weekday name. Also accepts corresponding abbreviation in parsing.",
},
FormatSpecification {
spec: "%w",
description: "Sunday = 0, Monday = 1, ..., Saturday = 6.",
},
FormatSpecification {
spec: "%u",
description: "Monday = 1, Tuesday = 2, ..., Sunday = 7. (ISO 8601)",
},
FormatSpecification {
spec: "%U",
description: "Week number starting with Sunday (00--53), zero-padded to 2 digits.",
},
FormatSpecification {
spec: "%W",
description: "Same as %U, but week 1 starts with the first Monday in that year instead.",
},
FormatSpecification {
spec: "%G",
description: "Same as %Y but uses the year number in ISO 8601 week date.",
},
FormatSpecification {
spec: "%g",
description: "Same as %y but uses the year number in ISO 8601 week date.",
},
FormatSpecification {
spec: "%V",
description: "Same as %U but uses the week number in ISO 8601 week date (01--53).",
},
FormatSpecification {
spec: "%j",
description: "Day of the year (001--366), zero-padded to 3 digits.",
},
FormatSpecification {
spec: "%D",
description: "Month-day-year format. Same as %m/%d/%y.",
},
FormatSpecification {
spec: "%x",
description: "Locale's date representation (e.g., 12/31/99).",
},
FormatSpecification {
spec: "%F",
description: "Year-month-day format (ISO 8601). Same as %Y-%m-%d.",
},
FormatSpecification {
spec: "%v",
description: "Day-month-year format. Same as %e-%b-%Y.",
},
FormatSpecification {
spec: "%H",
description: "Hour number (00--23), zero-padded to 2 digits.",
},
FormatSpecification {
spec: "%k",
description: "Same as %H but space-padded. Same as %_H.",
},
FormatSpecification {
spec: "%I",
description: "Hour number in 12-hour clocks (01--12), zero-padded to 2 digits.",
},
FormatSpecification {
spec: "%l",
description: "Same as %I but space-padded. Same as %_I.",
},
FormatSpecification {
spec: "%P",
description: "am or pm in 12-hour clocks.",
},
FormatSpecification {
spec: "%p",
description: "AM or PM in 12-hour clocks.",
},
FormatSpecification {
spec: "%M",
description: "Minute number (00--59), zero-padded to 2 digits.",
},
FormatSpecification {
spec: "%S",
description: "Second number (00--60), zero-padded to 2 digits.",
},
FormatSpecification {
spec: "%f",
description: "The fractional seconds (in nanoseconds) since last whole second.",
},
FormatSpecification {
spec: "%.f",
description: "Similar to .%f but left-aligned. These all consume the leading dot.",
},
FormatSpecification {
spec: "%.3f",
description: "Similar to .%f but left-aligned but fixed to a length of 3.",
},
FormatSpecification {
spec: "%.6f",
description: "Similar to .%f but left-aligned but fixed to a length of 6.",
},
FormatSpecification {
spec: "%.9f",
description: "Similar to .%f but left-aligned but fixed to a length of 9.",
},
FormatSpecification {
spec: "%3f",
description: "Similar to %.3f but without the leading dot.",
},
FormatSpecification {
spec: "%6f",
description: "Similar to %.6f but without the leading dot.",
},
FormatSpecification {
spec: "%9f",
description: "Similar to %.9f but without the leading dot.",
},
FormatSpecification {
spec: "%R",
description: "Hour-minute format. Same as %H:%M.",
},
FormatSpecification {
spec: "%T",
description: "Hour-minute-second format. Same as %H:%M:%S.",
},
FormatSpecification {
spec: "%X",
description: "Locale's time representation (e.g., 23:13:48).",
},
FormatSpecification {
spec: "%r",
description: "Hour-minute-second format in 12-hour clocks. Same as %I:%M:%S %p.",
},
FormatSpecification {
spec: "%Z",
description: "Local time zone name. Skips all non-whitespace characters during parsing.",
},
FormatSpecification {
spec: "%z",
description: "Offset from the local time to UTC (with UTC being +0000).",
},
FormatSpecification {
spec: "%:z",
description: "Same as %z but with a colon.",
},
FormatSpecification {
spec: "%c",
description: "Locale's date and time (e.g., Thu Mar 3 23:05:25 2005).",
},
FormatSpecification {
spec: "%+",
description: "ISO 8601 / RFC 3339 date & time format.",
},
FormatSpecification {
spec: "%s",
description: "UNIX timestamp, the number of seconds since 1970-01-01",
},
FormatSpecification {
spec: "%J",
description: "Joined date format. Same as %Y%m%d.",
},
FormatSpecification {
spec: "%Q",
description: "Sequential time format. Same as %H%M%S.",
},
FormatSpecification {
spec: "%t",
description: "Literal tab (\\t).",
},
FormatSpecification {
spec: "%n",
description: "Literal newline (\\n).",
},
FormatSpecification {
spec: "%%",
description: "Literal percent sign.",
},
];
let mut records = specifications
.iter()
.map(|s| {
// Handle custom format specifiers that aren't supported by chrono
let example = match s.spec {
"%J" => now.format("%Y%m%d").to_string(),
"%Q" => now.format("%H%M%S").to_string(),
_ => now.format(s.spec).to_string(),
};
Value::record(
record! {
"Specification" => Value::string(s.spec, head),
"Example" => Value::string(example, head),
"Description" => Value::string(s.description, head),
},
head,
)
})
.collect::<Vec<Value>>();
if show_parse_only_formats {
// now.format("%#z") will panic since it is parse-only
// so here we emulate how it will look:
let example = now
.format("%:z") // e.g. +09:30
.to_string()
.get(0..3) // +09:30 -> +09
.unwrap_or("")
.to_string();
let description = "Parsing only: Same as %z but allows minutes to be missing or present.";
records.push(Value::record(
record! {
"Specification" => Value::string("%#z", head),
"Example" => Value::string(example, head),
"Description" => Value::string(description, head),
},
head,
));
}
Value::list(records, head)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/date/mod.rs | crates/nu-command/src/date/mod.rs | mod date_;
mod from_human;
mod humanize;
mod list_timezone;
mod now;
mod parser;
mod to_timezone;
mod utils;
pub use date_::Date;
pub use from_human::DateFromHuman;
pub use humanize::DateHumanize;
pub use list_timezone::DateListTimezones;
pub use now::DateNow;
pub use to_timezone::DateToTimezone;
pub(crate) use utils::{generate_strftime_list, parse_date_from_string};
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/date/list_timezone.rs | crates/nu-command/src/date/list_timezone.rs | use chrono_tz::TZ_VARIANTS;
use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct DateListTimezones;
impl Command for DateListTimezones {
fn name(&self) -> &str {
"date list-timezone"
}
fn signature(&self) -> Signature {
Signature::build("date list-timezone")
.input_output_types(vec![(Type::Nothing, Type::table())])
.category(Category::Date)
}
fn description(&self) -> &str {
"List supported time zones."
}
fn search_terms(&self) -> Vec<&str> {
vec!["UTC", "GMT", "tz"]
}
fn run(
&self,
engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
Ok(TZ_VARIANTS
.iter()
.map(move |x| {
Value::record(
record! { "timezone" => Value::string(x.name(), head) },
head,
)
})
.into_pipeline_data(head, engine_state.signals().clone()))
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
example: "date list-timezone | where timezone =~ Shanghai",
description: "Show time zone(s) that contains 'Shanghai'",
result: Some(Value::test_list(vec![Value::test_record(record! {
"timezone" => Value::test_string("Asia/Shanghai"),
})])),
}]
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/date/now.rs | crates/nu-command/src/date/now.rs | use chrono::Local;
use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct DateNow;
impl Command for DateNow {
fn name(&self) -> &str {
"date now"
}
fn signature(&self) -> Signature {
Signature::build("date now")
.input_output_types(vec![(Type::Nothing, Type::Date)])
.category(Category::Date)
}
fn description(&self) -> &str {
"Get the current date."
}
fn search_terms(&self) -> Vec<&str> {
vec!["present", "current-time"]
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let dt = Local::now();
Ok(Value::date(dt.with_timezone(dt.offset()), head).into_pipeline_data())
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Get the current date and format it in a given format string.",
example: r#"date now | format date "%Y-%m-%d %H:%M:%S""#,
result: None,
},
Example {
description: "Get the current date and format it according to the RFC 3339 standard.",
example: r#"date now | format date "%+""#,
result: None,
},
Example {
description: "Get the time duration since 2019-04-30.",
example: r#"(date now) - 2019-05-01"#,
result: None,
},
Example {
description: "Get the time duration since a more specific time.",
example: r#"(date now) - 2019-05-01T04:12:05.20+08:00"#,
result: None,
},
Example {
description: "Get current time and format it in the debug format (RFC 2822 with timezone)",
example: r#"date now | debug"#,
result: None,
},
]
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/date/to_timezone.rs | crates/nu-command/src/date/to_timezone.rs | use std::sync::LazyLock;
use super::parser::datetime_in_timezone;
use crate::date::utils::parse_date_from_string;
use chrono::{DateTime, FixedOffset, Local, LocalResult, TimeZone};
use nu_engine::command_prelude::*;
static TIMEZONES: LazyLock<Vec<&'static str>> =
LazyLock::new(|| chrono_tz::TZ_VARIANTS.iter().map(|tz| tz.name()).collect());
#[derive(Clone)]
pub struct DateToTimezone;
impl Command for DateToTimezone {
fn name(&self) -> &str {
"date to-timezone"
}
fn signature(&self) -> Signature {
Signature::build("date to-timezone")
.input_output_types(vec![(Type::Date, Type::Date), (Type::String, Type::Date)])
.allow_variants_without_examples(true) // https://github.com/nushell/nushell/issues/7032
.param(
PositionalArg::new("time zone", SyntaxShape::String)
.desc("Time zone description.")
.completion(Completion::new_list(TIMEZONES.as_slice()))
.required(),
)
.category(Category::Date)
}
fn description(&self) -> &str {
"Convert a date to a given time zone."
}
fn extra_description(&self) -> &str {
"Use 'date list-timezone' to list all supported time zones."
}
fn search_terms(&self) -> Vec<&str> {
vec![
"tz",
"transform",
"convert",
"UTC",
"GMT",
"list",
"list-timezone",
]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let timezone: Spanned<String> = call.req(engine_state, stack, 0)?;
// This doesn't match explicit nulls
if let PipelineData::Empty = input {
return Err(ShellError::PipelineEmpty { dst_span: head });
}
input.map(
move |value| helper(value, head, &timezone),
engine_state.signals(),
)
}
fn examples(&self) -> Vec<Example<'_>> {
let example_result_1 = || match FixedOffset::east_opt(5 * 3600)
.expect("to timezone: help example is invalid")
.with_ymd_and_hms(2020, 10, 10, 13, 00, 00)
{
LocalResult::Single(dt) => Some(Value::date(dt, Span::test_data())),
_ => panic!("to timezone: help example is invalid"),
};
vec![
Example {
description: "Get the current date in UTC+05:00.",
example: "date now | date to-timezone '+0500'",
result: None,
},
Example {
description: "Get the current date in the local time zone.",
example: "date now | date to-timezone local",
result: None,
},
Example {
description: "Get the current date in Hawaii.",
example: "date now | date to-timezone US/Hawaii",
result: None,
},
Example {
description: "Get a date in a different time zone, from a string.",
example: r#""2020-10-10 10:00:00 +02:00" | date to-timezone "+0500""#,
result: example_result_1(),
},
Example {
description: "Get a date in a different time zone, from a datetime.",
example: r#""2020-10-10 10:00:00 +02:00" | into datetime | date to-timezone "+0500""#,
result: example_result_1(),
},
]
}
}
fn helper(value: Value, head: Span, timezone: &Spanned<String>) -> Value {
let val_span = value.span();
match value {
Value::Date { val, .. } => _to_timezone(val, timezone, head),
Value::String { val, .. } => {
let time = parse_date_from_string(&val, val_span);
match time {
Ok(dt) => _to_timezone(dt, timezone, head),
Err(e) => e,
}
}
Value::Nothing { .. } => {
let dt = Local::now();
_to_timezone(dt.with_timezone(dt.offset()), timezone, head)
}
_ => Value::error(
ShellError::OnlySupportsThisInputType {
exp_input_type: "date, string (that represents datetime), or nothing".into(),
wrong_type: value.get_type().to_string(),
dst_span: head,
src_span: val_span,
},
head,
),
}
}
fn _to_timezone(dt: DateTime<FixedOffset>, timezone: &Spanned<String>, span: Span) -> Value {
match datetime_in_timezone(&dt, timezone.item.as_str()) {
Ok(dt) => Value::date(dt, span),
Err(_) => Value::error(
ShellError::TypeMismatch {
err_message: String::from("invalid time zone"),
span: timezone.span,
},
timezone.span,
),
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(DateToTimezone {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/math/abs.rs | crates/nu-command/src/math/abs.rs | use crate::math::utils::ensure_bounded;
use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct MathAbs;
impl Command for MathAbs {
fn name(&self) -> &str {
"math abs"
}
fn signature(&self) -> Signature {
Signature::build("math abs")
.input_output_types(vec![
(Type::Number, Type::Number),
(Type::Duration, Type::Duration),
(
Type::List(Box::new(Type::Number)),
Type::List(Box::new(Type::Number)),
),
(
Type::List(Box::new(Type::Duration)),
Type::List(Box::new(Type::Duration)),
),
(Type::Range, Type::List(Box::new(Type::Number))),
])
.allow_variants_without_examples(true)
.category(Category::Math)
}
fn description(&self) -> &str {
"Returns the absolute value of a number."
}
fn search_terms(&self) -> Vec<&str> {
vec!["absolute", "modulus", "positive", "distance"]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
if let PipelineData::Value(ref v @ Value::Range { ref val, .. }, ..) = input {
let span = v.span();
ensure_bounded(val, span, head)?;
}
input.map(move |value| abs_helper(value, head), engine_state.signals())
}
fn run_const(
&self,
working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
if let PipelineData::Value(ref v @ Value::Range { ref val, .. }, ..) = input {
let span = v.span();
ensure_bounded(val, span, head)?;
}
input.map(
move |value| abs_helper(value, head),
working_set.permanent().signals(),
)
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
description: "Compute absolute value of each number in a list of numbers",
example: "[-50 -100.0 25] | math abs",
result: Some(Value::list(
vec![
Value::test_int(50),
Value::test_float(100.0),
Value::test_int(25),
],
Span::test_data(),
)),
}]
}
}
fn abs_helper(val: Value, head: Span) -> Value {
let span = val.span();
match val {
Value::Int { val, .. } => Value::int(val.abs(), span),
Value::Float { val, .. } => Value::float(val.abs(), span),
Value::Duration { val, .. } => Value::duration(val.abs(), span),
Value::Error { .. } => val,
other => Value::error(
ShellError::OnlySupportsThisInputType {
exp_input_type: "numeric".into(),
wrong_type: other.get_type().to_string(),
dst_span: head,
src_span: other.span(),
},
head,
),
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(MathAbs {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/math/median.rs | crates/nu-command/src/math/median.rs | use crate::math::{avg::average, utils::run_with_function};
use nu_engine::command_prelude::*;
use std::cmp::Ordering;
#[derive(Clone)]
pub struct MathMedian;
impl Command for MathMedian {
fn name(&self) -> &str {
"math median"
}
fn signature(&self) -> Signature {
Signature::build("math median")
.input_output_types(vec![
(Type::List(Box::new(Type::Number)), Type::Number),
(Type::List(Box::new(Type::Duration)), Type::Duration),
(Type::List(Box::new(Type::Filesize)), Type::Filesize),
(Type::Range, Type::Number),
(Type::table(), Type::record()),
(Type::record(), Type::record()),
])
.allow_variants_without_examples(true)
.category(Category::Math)
}
fn description(&self) -> &str {
"Computes the median of a list of numbers."
}
fn search_terms(&self) -> Vec<&str> {
vec!["middle", "statistics"]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
run_with_function(call, input, median)
}
fn run_const(
&self,
_working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
run_with_function(call, input, median)
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Compute the median of a list of numbers",
example: "[3 8 9 12 12 15] | math median",
result: Some(Value::test_float(10.5)),
},
Example {
description: "Compute the medians of the columns of a table",
example: "[{a: 1 b: 3} {a: 2 b: -1} {a: -3 b: 5}] | math median",
result: Some(Value::test_record(record! {
"a" => Value::test_int(1),
"b" => Value::test_int(3),
})),
},
Example {
description: "Find the median of a list of file sizes",
example: "[5KB 10MB 200B] | math median",
result: Some(Value::test_filesize(5 * 1_000)),
},
]
}
}
enum Pick {
MedianAverage,
Median,
}
pub fn median(values: &[Value], span: Span, head: Span) -> Result<Value, ShellError> {
let take = if values.len().is_multiple_of(2) {
Pick::MedianAverage
} else {
Pick::Median
};
let mut sorted = values
.iter()
.filter(|x| !x.as_float().is_ok_and(f64::is_nan))
.collect::<Vec<_>>();
sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal));
match take {
Pick::Median => {
let idx = (values.len() as f64 / 2.0).floor() as usize;
Ok(sorted
.get(idx)
.ok_or_else(|| ShellError::UnsupportedInput {
msg: "Empty input".to_string(),
input: "value originates from here".into(),
msg_span: head,
input_span: span,
})?
.to_owned()
.to_owned())
}
Pick::MedianAverage => {
let idx_end = values.len() / 2;
let idx_start = idx_end - 1;
let left = sorted
.get(idx_start)
.ok_or_else(|| ShellError::UnsupportedInput {
msg: "Empty input".to_string(),
input: "value originates from here".into(),
msg_span: head,
input_span: span,
})?
.to_owned()
.to_owned();
let right = sorted
.get(idx_end)
.ok_or_else(|| ShellError::UnsupportedInput {
msg: "Empty input".to_string(),
input: "value originates from here".into(),
msg_span: head,
input_span: span,
})?
.to_owned()
.to_owned();
average(&[left, right], span, head)
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(MathMedian {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/math/log.rs | crates/nu-command/src/math/log.rs | use crate::math::utils::ensure_bounded;
use nu_engine::command_prelude::*;
use nu_protocol::Signals;
#[derive(Clone)]
pub struct MathLog;
impl Command for MathLog {
fn name(&self) -> &str {
"math log"
}
fn signature(&self) -> Signature {
Signature::build("math log")
.required(
"base",
SyntaxShape::Number,
"Base for which the logarithm should be computed.",
)
.input_output_types(vec![
(Type::Number, Type::Float),
(
Type::List(Box::new(Type::Number)),
Type::List(Box::new(Type::Float)),
),
(Type::Range, Type::List(Box::new(Type::Number))),
])
.allow_variants_without_examples(true)
.category(Category::Math)
}
fn description(&self) -> &str {
"Returns the logarithm for an arbitrary base."
}
fn search_terms(&self) -> Vec<&str> {
vec!["base", "exponent", "inverse", "euler"]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let base: Spanned<f64> = call.req(engine_state, stack, 0)?;
if let PipelineData::Value(ref v @ Value::Range { ref val, .. }, ..) = input {
let span = v.span();
ensure_bounded(val, span, head)?;
}
log(base, call.head, input, engine_state.signals())
}
fn run_const(
&self,
working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let base: Spanned<f64> = call.req_const(working_set, 0)?;
if let PipelineData::Value(ref v @ Value::Range { ref val, .. }, ..) = input {
let span = v.span();
ensure_bounded(val, span, head)?;
}
log(base, call.head, input, working_set.permanent().signals())
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Get the logarithm of 100 to the base 10",
example: "100 | math log 10",
result: Some(Value::test_float(2.0f64)),
},
Example {
example: "[16 8 4] | math log 2",
description: "Get the log2 of a list of values",
result: Some(Value::list(
vec![
Value::test_float(4.0),
Value::test_float(3.0),
Value::test_float(2.0),
],
Span::test_data(),
)),
},
]
}
}
fn log(
base: Spanned<f64>,
head: Span,
input: PipelineData,
signals: &Signals,
) -> Result<PipelineData, ShellError> {
if base.item <= 0.0f64 {
return Err(ShellError::UnsupportedInput {
msg: "Base has to be greater 0".into(),
input: "value originates from here".into(),
msg_span: head,
input_span: base.span,
});
}
// This doesn't match explicit nulls
if let PipelineData::Empty = input {
return Err(ShellError::PipelineEmpty { dst_span: head });
}
let base = base.item;
input.map(move |value| operate(value, head, base), signals)
}
fn operate(value: Value, head: Span, base: f64) -> Value {
let span = value.span();
match value {
numeric @ (Value::Int { .. } | Value::Float { .. }) => {
let (val, span) = match numeric {
Value::Int { val, .. } => (val as f64, span),
Value::Float { val, .. } => (val, span),
_ => unreachable!(),
};
if val <= 0.0 {
return Value::error(
ShellError::UnsupportedInput {
msg: "'math log' undefined for values outside the open interval (0, Inf)."
.into(),
input: "value originates from here".into(),
msg_span: head,
input_span: span,
},
span,
);
}
// Specialize for better precision/performance
let val = if base == 10.0 {
val.log10()
} else if base == 2.0 {
val.log2()
} else {
val.log(base)
};
Value::float(val, span)
}
Value::Error { .. } => value,
other => Value::error(
ShellError::OnlySupportsThisInputType {
exp_input_type: "numeric".into(),
wrong_type: other.get_type().to_string(),
dst_span: head,
src_span: other.span(),
},
head,
),
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(MathLog {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/math/sum.rs | crates/nu-command/src/math/sum.rs | use crate::math::{
reducers::{Reduce, reducer_for},
utils::run_with_function,
};
use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct MathSum;
impl Command for MathSum {
fn name(&self) -> &str {
"math sum"
}
fn signature(&self) -> Signature {
Signature::build("math sum")
.input_output_types(vec![
(Type::List(Box::new(Type::Number)), Type::Number),
(Type::List(Box::new(Type::Duration)), Type::Duration),
(Type::List(Box::new(Type::Filesize)), Type::Filesize),
(Type::Range, Type::Number),
(Type::table(), Type::record()),
(Type::record(), Type::record()),
])
.allow_variants_without_examples(true)
.category(Category::Math)
}
fn description(&self) -> &str {
"Returns the sum of a list of numbers or of each column in a table."
}
fn search_terms(&self) -> Vec<&str> {
vec!["plus", "add", "total", "+"]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
run_with_function(call, input, summation)
}
fn run_const(
&self,
_working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
run_with_function(call, input, summation)
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Sum a list of numbers",
example: "[1 2 3] | math sum",
result: Some(Value::test_int(6)),
},
Example {
description: "Get the disk usage for the current directory",
example: "ls | get size | math sum",
result: None,
},
Example {
description: "Compute the sum of each column in a table",
example: "[[a b]; [1 2] [3 4]] | math sum",
result: Some(Value::test_record(record! {
"a" => Value::test_int(4),
"b" => Value::test_int(6),
})),
},
]
}
}
pub fn summation(values: &[Value], span: Span, head: Span) -> Result<Value, ShellError> {
let sum_func = reducer_for(Reduce::Summation);
sum_func(Value::nothing(head), values.to_vec(), span, head)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(MathSum {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/math/product.rs | crates/nu-command/src/math/product.rs | use crate::math::{
reducers::{Reduce, reducer_for},
utils::run_with_function,
};
use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct MathProduct;
impl Command for MathProduct {
fn name(&self) -> &str {
"math product"
}
fn signature(&self) -> Signature {
Signature::build("math product")
.input_output_types(vec![
(Type::List(Box::new(Type::Number)), Type::Number),
(Type::Range, Type::Number),
(Type::table(), Type::record()),
(Type::record(), Type::record()),
])
.allow_variants_without_examples(true)
.category(Category::Math)
}
fn description(&self) -> &str {
"Returns the product of a list of numbers or the products of each column of a table."
}
fn search_terms(&self) -> Vec<&str> {
vec!["times", "multiply", "x", "*"]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
run_with_function(call, input, product)
}
fn run_const(
&self,
_working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
run_with_function(call, input, product)
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Compute the product of a list of numbers",
example: "[2 3 3 4] | math product",
result: Some(Value::test_int(72)),
},
Example {
description: "Compute the product of each column in a table",
example: "[[a b]; [1 2] [3 4]] | math product",
result: Some(Value::test_record(record! {
"a" => Value::test_int(3),
"b" => Value::test_int(8),
})),
},
]
}
}
/// Calculate product of given values
pub fn product(values: &[Value], span: Span, head: Span) -> Result<Value, ShellError> {
let product_func = reducer_for(Reduce::Product);
product_func(Value::nothing(head), values.to_vec(), span, head)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(MathProduct {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/math/max.rs | crates/nu-command/src/math/max.rs | use crate::math::{
reducers::{Reduce, reducer_for},
utils::run_with_function,
};
use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct MathMax;
impl Command for MathMax {
fn name(&self) -> &str {
"math max"
}
fn signature(&self) -> Signature {
Signature::build("math max")
.input_output_types(vec![
(Type::List(Box::new(Type::Number)), Type::Number),
(Type::List(Box::new(Type::Duration)), Type::Duration),
(Type::List(Box::new(Type::Filesize)), Type::Filesize),
(Type::List(Box::new(Type::Any)), Type::Any),
(Type::Range, Type::Number),
(Type::table(), Type::record()),
(Type::record(), Type::record()),
])
.allow_variants_without_examples(true)
.category(Category::Math)
}
fn description(&self) -> &str {
"Returns the maximum of a list of values, or of columns in a table."
}
fn search_terms(&self) -> Vec<&str> {
vec!["maximum", "largest"]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
run_with_function(call, input, maximum)
}
fn run_const(
&self,
_working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
run_with_function(call, input, maximum)
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Find the maximum of a list of numbers",
example: "[-50 100 25] | math max",
result: Some(Value::test_int(100)),
},
Example {
description: "Find the maxima of the columns of a table",
example: "[{a: 1 b: 3} {a: 2 b: -1}] | math max",
result: Some(Value::test_record(record! {
"a" => Value::test_int(2),
"b" => Value::test_int(3),
})),
},
Example {
description: "Find the maximum of a list of dates",
example: "[2022-02-02 2022-12-30 2012-12-12] | math max",
result: Some(Value::test_date(
"2022-12-30 00:00:00Z".parse().unwrap_or_default(),
)),
},
]
}
}
pub fn maximum(values: &[Value], span: Span, head: Span) -> Result<Value, ShellError> {
let max_func = reducer_for(Reduce::Maximum);
max_func(Value::nothing(head), values.to_vec(), span, head)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(MathMax {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/math/round.rs | crates/nu-command/src/math/round.rs | use crate::math::utils::ensure_bounded;
use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct MathRound;
impl Command for MathRound {
fn name(&self) -> &str {
"math round"
}
fn signature(&self) -> Signature {
Signature::build("math round")
.input_output_types(vec![
(Type::Number, Type::Number),
(
Type::List(Box::new(Type::Number)),
Type::List(Box::new(Type::Number)),
),
(Type::Range, Type::List(Box::new(Type::Number))),
])
.allow_variants_without_examples(true)
.named(
"precision",
SyntaxShape::Number,
"digits of precision",
Some('p'),
)
.category(Category::Math)
}
fn description(&self) -> &str {
"Returns the input number rounded to the specified precision."
}
fn search_terms(&self) -> Vec<&str> {
vec!["approx", "closest", "nearest"]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let precision_param: Option<i64> = call.get_flag(engine_state, stack, "precision")?;
let head = call.head;
// This doesn't match explicit nulls
if let PipelineData::Empty = input {
return Err(ShellError::PipelineEmpty { dst_span: head });
}
if let PipelineData::Value(ref v @ Value::Range { ref val, .. }, ..) = input {
let span = v.span();
ensure_bounded(val, span, head)?;
}
input.map(
move |value| operate(value, head, precision_param),
engine_state.signals(),
)
}
fn run_const(
&self,
working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let precision_param: Option<i64> = call.get_flag_const(working_set, "precision")?;
let head = call.head;
// This doesn't match explicit nulls
if let PipelineData::Empty = input {
return Err(ShellError::PipelineEmpty { dst_span: head });
}
if let PipelineData::Value(ref v @ Value::Range { ref val, .. }, ..) = input {
let span = v.span();
ensure_bounded(val, span, head)?;
}
input.map(
move |value| operate(value, head, precision_param),
working_set.permanent().signals(),
)
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Apply the round function to a list of numbers",
example: "[1.5 2.3 -3.1] | math round",
result: Some(Value::list(
vec![Value::test_int(2), Value::test_int(2), Value::test_int(-3)],
Span::test_data(),
)),
},
Example {
description: "Apply the round function with precision specified",
example: "[1.555 2.333 -3.111] | math round --precision 2",
result: Some(Value::list(
vec![
Value::test_float(1.56),
Value::test_float(2.33),
Value::test_float(-3.11),
],
Span::test_data(),
)),
},
Example {
description: "Apply negative precision to a list of numbers",
example: "[123, 123.3, -123.4] | math round --precision -1",
result: Some(Value::list(
vec![
Value::test_int(120),
Value::test_int(120),
Value::test_int(-120),
],
Span::test_data(),
)),
},
]
}
}
fn operate(value: Value, head: Span, precision: Option<i64>) -> Value {
// We treat int values as float values in order to avoid code repetition in the match closure
let span = value.span();
let value = if let Value::Int { val, .. } = value {
Value::float(val as f64, span)
} else {
value
};
match value {
Value::Float { val, .. } => {
if !val.is_finite() {
return Value::error(
ShellError::UnsupportedInput {
msg: "cannot round non-finite number".into(),
input: "value originates from here".into(),
msg_span: span,
input_span: span,
},
span,
);
}
match precision {
Some(precision_number) => Value::float(
(val * ((10_f64).powf(precision_number as f64))).round()
/ (10_f64).powf(precision_number as f64),
span,
),
None => Value::int(val.round() as i64, span),
}
}
Value::Error { .. } => value,
other => Value::error(
ShellError::OnlySupportsThisInputType {
exp_input_type: "numeric".into(),
wrong_type: other.get_type().to_string(),
dst_span: head,
src_span: other.span(),
},
head,
),
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(MathRound {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/math/min.rs | crates/nu-command/src/math/min.rs | use crate::math::{
reducers::{Reduce, reducer_for},
utils::run_with_function,
};
use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct MathMin;
impl Command for MathMin {
fn name(&self) -> &str {
"math min"
}
fn signature(&self) -> Signature {
Signature::build("math min")
.input_output_types(vec![
(Type::List(Box::new(Type::Number)), Type::Number),
(Type::List(Box::new(Type::Duration)), Type::Duration),
(Type::List(Box::new(Type::Filesize)), Type::Filesize),
(Type::List(Box::new(Type::Any)), Type::Any),
(Type::Range, Type::Number),
(Type::table(), Type::record()),
(Type::record(), Type::record()),
])
.allow_variants_without_examples(true)
.category(Category::Math)
}
fn description(&self) -> &str {
"Finds the minimum within a list of values or tables."
}
fn search_terms(&self) -> Vec<&str> {
vec!["minimum", "smallest"]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
run_with_function(call, input, minimum)
}
fn run_const(
&self,
_working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
run_with_function(call, input, minimum)
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Compute the minimum of a list of numbers",
example: "[-50 100 25] | math min",
result: Some(Value::test_int(-50)),
},
Example {
description: "Compute the minima of the columns of a table",
example: "[{a: 1 b: 3} {a: 2 b: -1}] | math min",
result: Some(Value::test_record(record! {
"a" => Value::test_int(1),
"b" => Value::test_int(-1),
})),
},
Example {
description: "Find the minimum of a list of arbitrary values (Warning: Weird)",
example: "[-50 'hello' true] | math min",
result: Some(Value::test_bool(true)),
},
]
}
}
pub fn minimum(values: &[Value], span: Span, head: Span) -> Result<Value, ShellError> {
let min_func = reducer_for(Reduce::Minimum);
min_func(Value::nothing(head), values.to_vec(), span, head)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(MathMin {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/math/utils.rs | crates/nu-command/src/math/utils.rs | use core::slice;
use indexmap::IndexMap;
use nu_protocol::{
IntoPipelineData, PipelineData, Range, ShellError, Signals, Span, Value, engine::Call,
};
pub fn run_with_function(
call: &Call,
input: PipelineData,
mf: impl Fn(&[Value], Span, Span) -> Result<Value, ShellError>,
) -> Result<PipelineData, ShellError> {
let name = call.head;
let res = calculate(input, name, mf);
match res {
Ok(v) => Ok(v.into_pipeline_data()),
Err(e) => Err(e),
}
}
fn helper_for_tables(
values: &[Value],
val_span: Span,
name: Span,
mf: impl Fn(&[Value], Span, Span) -> Result<Value, ShellError>,
) -> Result<Value, ShellError> {
// If we are not dealing with Primitives, then perhaps we are dealing with a table
// Create a key for each column name
let mut column_values = IndexMap::new();
for val in values {
match val {
Value::Record { val, .. } => {
for (key, value) in &**val {
column_values
.entry(key.clone())
.and_modify(|v: &mut Vec<Value>| v.push(value.clone()))
.or_insert_with(|| vec![value.clone()]);
}
}
Value::Error { error, .. } => return Err(*error.clone()),
_ => {
//Turns out we are not dealing with a table
return mf(values, val.span(), name);
}
}
}
// The mathematical function operates over the columns of the table
let mut column_totals = IndexMap::new();
for (col_name, col_vals) in column_values {
if let Ok(out) = mf(&col_vals, val_span, name) {
column_totals.insert(col_name, out);
}
}
if column_totals.keys().len() == 0 {
return Err(ShellError::UnsupportedInput {
msg: "Unable to give a result with this input".to_string(),
input: "value originates from here".into(),
msg_span: name,
input_span: val_span,
});
}
Ok(Value::record(column_totals.into_iter().collect(), name))
}
pub fn calculate(
values: PipelineData,
name: Span,
mf: impl Fn(&[Value], Span, Span) -> Result<Value, ShellError>,
) -> Result<Value, ShellError> {
// TODO implement spans for ListStream, thus negating the need for unwrap_or().
let span = values.span().unwrap_or(name);
match values {
PipelineData::ListStream(s, ..) => {
helper_for_tables(&s.into_iter().collect::<Vec<Value>>(), span, name, mf)
}
PipelineData::Value(Value::List { ref vals, .. }, ..) => match &vals[..] {
[Value::Record { .. }, _end @ ..] => helper_for_tables(
vals,
values.span().expect("PipelineData::value had no span"),
name,
mf,
),
_ => mf(vals, span, name),
},
PipelineData::Value(Value::Record { val, .. }, ..) => {
let mut record = val.into_owned();
record
.iter_mut()
.try_for_each(|(_, val)| -> Result<(), ShellError> {
*val = mf(slice::from_ref(val), span, name)?;
Ok(())
})?;
Ok(Value::record(record, span))
}
PipelineData::Value(Value::Range { val, .. }, ..) => {
ensure_bounded(val.as_ref(), span, name)?;
let new_vals: Result<Vec<Value>, ShellError> = val
.into_range_iter(span, Signals::empty())
.map(|val| mf(&[val], span, name))
.collect();
mf(&new_vals?, span, name)
}
PipelineData::Value(val, ..) => mf(&[val], span, name),
PipelineData::Empty => Err(ShellError::PipelineEmpty { dst_span: name }),
val => Err(ShellError::UnsupportedInput {
msg: "Only ints, floats, lists, records, or ranges are supported".into(),
input: "value originates from here".into(),
msg_span: name,
input_span: val
.span()
.expect("non-Empty non-ListStream PipelineData had no span"),
}),
}
}
pub fn ensure_bounded(range: &Range, val_span: Span, call_span: Span) -> Result<(), ShellError> {
if range.is_bounded() {
return Ok(());
}
Err(ShellError::IncorrectValue {
msg: "Range must be bounded".to_string(),
val_span,
call_span,
})
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/math/variance.rs | crates/nu-command/src/math/variance.rs | use crate::math::utils::run_with_function;
use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct MathVariance;
impl Command for MathVariance {
fn name(&self) -> &str {
"math variance"
}
fn signature(&self) -> Signature {
Signature::build("math variance")
.input_output_types(vec![
(Type::List(Box::new(Type::Number)), Type::Number),
(Type::Range, Type::Number),
(Type::table(), Type::record()),
(Type::record(), Type::record()),
])
.switch(
"sample",
"calculate sample variance (i.e. using N-1 as the denominator)",
Some('s'),
)
.allow_variants_without_examples(true)
.category(Category::Math)
}
fn description(&self) -> &str {
"Returns the variance of a list of numbers or of each column in a table."
}
fn search_terms(&self) -> Vec<&str> {
vec!["deviation", "dispersion", "variation", "statistics"]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let sample = call.has_flag(engine_state, stack, "sample")?;
let name = call.head;
let span = input.span().unwrap_or(name);
let input: PipelineData = match input.try_expand_range() {
Err(_) => {
return Err(ShellError::IncorrectValue {
msg: "Range must be bounded".to_string(),
val_span: span,
call_span: name,
});
}
Ok(val) => val,
};
run_with_function(call, input, compute_variance(sample))
}
fn run_const(
&self,
working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let sample = call.has_flag_const(working_set, "sample")?;
let name = call.head;
let span = input.span().unwrap_or(name);
let input: PipelineData = match input.try_expand_range() {
Err(_) => {
return Err(ShellError::IncorrectValue {
msg: "Range must be bounded".to_string(),
val_span: span,
call_span: name,
});
}
Ok(val) => val,
};
run_with_function(call, input, compute_variance(sample))
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Get the variance of a list of numbers",
example: "[1 2 3 4 5] | math variance",
result: Some(Value::test_float(2.0)),
},
Example {
description: "Get the sample variance of a list of numbers",
example: "[1 2 3 4 5] | math variance --sample",
result: Some(Value::test_float(2.5)),
},
Example {
description: "Compute the variance of each column in a table",
example: "[[a b]; [1 2] [3 4]] | math variance",
result: Some(Value::test_record(record! {
"a" => Value::test_int(1),
"b" => Value::test_int(1),
})),
},
]
}
}
fn sum_of_squares(values: &[Value], span: Span) -> Result<Value, ShellError> {
let n = Value::int(values.len() as i64, span);
let mut sum_x = Value::int(0, span);
let mut sum_x2 = Value::int(0, span);
for value in values {
let v = match &value {
Value::Int { .. } | Value::Float { .. } => Ok(value),
Value::Error { error, .. } => Err(*error.clone()),
other => Err(ShellError::UnsupportedInput {
msg: format!(
"Attempted to compute the sum of squares of a non-int, non-float value '{}' with a type of `{}`.",
other.coerce_string()?,
other.get_type()
),
input: "value originates from here".into(),
msg_span: span,
input_span: value.span(),
}),
}?;
let v_squared = &v.mul(span, v, span)?;
sum_x2 = sum_x2.add(span, v_squared, span)?;
sum_x = sum_x.add(span, v, span)?;
}
let sum_x_squared = sum_x.mul(span, &sum_x, span)?;
let sum_x_squared_div_n = sum_x_squared.div(span, &n, span)?;
let ss = sum_x2.sub(span, &sum_x_squared_div_n, span)?;
Ok(ss)
}
pub fn compute_variance(
sample: bool,
) -> impl Fn(&[Value], Span, Span) -> Result<Value, ShellError> {
move |values: &[Value], span: Span, head: Span| {
let n = if sample {
values.len() - 1
} else {
values.len()
};
// sum_of_squares() needs the span of the original value, not the call head.
let ss = sum_of_squares(values, span)?;
let n = Value::int(n as i64, head);
ss.div(head, &n, head)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(MathVariance {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/math/mod.rs | crates/nu-command/src/math/mod.rs | mod abs;
mod avg;
mod ceil;
mod floor;
mod log;
pub mod math_;
mod max;
mod median;
mod min;
mod mode;
mod product;
mod reducers;
mod round;
mod sqrt;
mod stddev;
mod sum;
mod utils;
mod variance;
pub use abs::MathAbs;
pub use avg::MathAvg;
pub use ceil::MathCeil;
pub use floor::MathFloor;
pub use math_::MathCommand as Math;
pub use max::MathMax;
pub use median::MathMedian;
pub use min::MathMin;
pub use mode::MathMode;
pub use product::MathProduct;
pub use round::MathRound;
pub use sqrt::MathSqrt;
pub use stddev::MathStddev;
pub use sum::MathSum;
pub use variance::MathVariance;
pub use log::MathLog;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/math/math_.rs | crates/nu-command/src/math/math_.rs | use nu_engine::{command_prelude::*, get_full_help};
#[derive(Clone)]
pub struct MathCommand;
impl Command for MathCommand {
fn name(&self) -> &str {
"math"
}
fn signature(&self) -> Signature {
Signature::build("math")
.category(Category::Math)
.input_output_types(vec![(Type::Nothing, Type::String)])
}
fn description(&self) -> &str {
"Use mathematical functions as aggregate functions on a list of numbers or tables."
}
fn extra_description(&self) -> &str {
"You must use one of the following subcommands. Using this command as-is will only produce this help message."
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
Ok(Value::string(get_full_help(self, engine_state, stack), call.head).into_pipeline_data())
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/math/sqrt.rs | crates/nu-command/src/math/sqrt.rs | use crate::math::utils::ensure_bounded;
use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct MathSqrt;
impl Command for MathSqrt {
fn name(&self) -> &str {
"math sqrt"
}
fn signature(&self) -> Signature {
Signature::build("math sqrt")
.input_output_types(vec![
(Type::Number, Type::Float),
(
Type::List(Box::new(Type::Number)),
Type::List(Box::new(Type::Float)),
),
(Type::Range, Type::List(Box::new(Type::Number))),
])
.allow_variants_without_examples(true)
.category(Category::Math)
}
fn description(&self) -> &str {
"Returns the square root of the input number."
}
fn search_terms(&self) -> Vec<&str> {
vec!["square", "root"]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
// This doesn't match explicit nulls
if let PipelineData::Empty = input {
return Err(ShellError::PipelineEmpty { dst_span: head });
}
if let PipelineData::Value(ref v @ Value::Range { ref val, .. }, ..) = input {
let span = v.span();
ensure_bounded(val, span, head)?;
}
input.map(move |value| operate(value, head), engine_state.signals())
}
fn run_const(
&self,
working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
// This doesn't match explicit nulls
if let PipelineData::Empty = input {
return Err(ShellError::PipelineEmpty { dst_span: head });
}
if let PipelineData::Value(ref v @ Value::Range { ref val, .. }, ..) = input {
let span = v.span();
ensure_bounded(val, span, head)?;
}
input.map(
move |value| operate(value, head),
working_set.permanent().signals(),
)
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
description: "Compute the square root of each number in a list",
example: "[9 16] | math sqrt",
result: Some(Value::list(
vec![Value::test_float(3.0), Value::test_float(4.0)],
Span::test_data(),
)),
}]
}
}
fn operate(value: Value, head: Span) -> Value {
let span = value.span();
match value {
Value::Int { val, .. } => {
let squared = (val as f64).sqrt();
if squared.is_nan() {
return error_negative_sqrt(head, span);
}
Value::float(squared, span)
}
Value::Float { val, .. } => {
let squared = val.sqrt();
if squared.is_nan() {
return error_negative_sqrt(head, span);
}
Value::float(squared, span)
}
Value::Error { .. } => value,
other => Value::error(
ShellError::OnlySupportsThisInputType {
exp_input_type: "numeric".into(),
wrong_type: other.get_type().to_string(),
dst_span: head,
src_span: other.span(),
},
head,
),
}
}
fn error_negative_sqrt(head: Span, span: Span) -> Value {
Value::error(
ShellError::UnsupportedInput {
msg: String::from("Can't square root a negative number"),
input: "value originates from here".into(),
msg_span: head,
input_span: span,
},
span,
)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(MathSqrt {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/math/reducers.rs | crates/nu-command/src/math/reducers.rs | use nu_protocol::{ShellError, Span, Value};
use std::cmp::Ordering;
pub enum Reduce {
Summation,
Product,
Minimum,
Maximum,
}
pub type ReducerFunction =
Box<dyn Fn(Value, Vec<Value>, Span, Span) -> Result<Value, ShellError> + Send + Sync + 'static>;
pub fn reducer_for(command: Reduce) -> ReducerFunction {
match command {
Reduce::Summation => Box::new(|_, values, span, head| sum(values, span, head)),
Reduce::Product => Box::new(|_, values, span, head| product(values, span, head)),
Reduce::Minimum => Box::new(|_, values, span, head| min(values, span, head)),
Reduce::Maximum => Box::new(|_, values, span, head| max(values, span, head)),
}
}
pub fn max(data: Vec<Value>, span: Span, head: Span) -> Result<Value, ShellError> {
let mut biggest = data
.first()
.ok_or_else(|| ShellError::UnsupportedInput {
msg: "Empty input".to_string(),
input: "value originates from here".into(),
msg_span: head,
input_span: span,
})?
.clone();
for value in &data {
if value.partial_cmp(&biggest) == Some(Ordering::Greater) {
biggest = value.clone();
}
}
Ok(biggest)
}
pub fn min(data: Vec<Value>, span: Span, head: Span) -> Result<Value, ShellError> {
let mut smallest = data
.first()
.ok_or_else(|| ShellError::UnsupportedInput {
msg: "Empty input".to_string(),
input: "value originates from here".into(),
msg_span: head,
input_span: span,
})?
.clone();
for value in &data {
if value.partial_cmp(&smallest) == Some(Ordering::Less) {
smallest = value.clone();
}
}
Ok(smallest)
}
pub fn sum(data: Vec<Value>, span: Span, head: Span) -> Result<Value, ShellError> {
let initial_value = data.first();
let mut acc = match initial_value {
Some(v) => {
let span = v.span();
match v {
Value::Filesize { .. } => Ok(Value::filesize(0, span)),
Value::Duration { .. } => Ok(Value::duration(0, span)),
Value::Int { .. } | Value::Float { .. } => Ok(Value::int(0, span)),
_ => Ok(Value::nothing(head)),
}
}
None => Err(ShellError::UnsupportedInput {
msg: "Empty input".to_string(),
input: "value originates from here".into(),
msg_span: head,
input_span: span,
}),
}?;
for value in &data {
match value {
Value::Int { .. }
| Value::Float { .. }
| Value::Filesize { .. }
| Value::Duration { .. } => {
acc = acc.add(head, value, head)?;
}
Value::Error { error, .. } => return Err(*error.clone()),
other => {
return Err(ShellError::UnsupportedInput {
msg: format!(
"Attempted to compute the sum of a value '{}' that cannot be summed with a type of `{}`.",
other.coerce_string()?,
other.get_type()
),
input: "value originates from here".into(),
msg_span: head,
input_span: other.span(),
});
}
}
}
Ok(acc)
}
pub fn product(data: Vec<Value>, span: Span, head: Span) -> Result<Value, ShellError> {
let initial_value = data.first();
let mut acc = match initial_value {
Some(v) => {
let span = v.span();
match v {
Value::Int { .. } | Value::Float { .. } => Ok(Value::int(1, span)),
_ => Ok(Value::nothing(head)),
}
}
None => Err(ShellError::UnsupportedInput {
msg: "Empty input".to_string(),
input: "value originates from here".into(),
msg_span: head,
input_span: span,
}),
}?;
for value in &data {
match value {
Value::Int { .. } | Value::Float { .. } => {
acc = acc.mul(head, value, head)?;
}
Value::Error { error, .. } => return Err(*error.clone()),
other => {
return Err(ShellError::UnsupportedInput {
msg: format!(
"Attempted to compute the product of a value '{}' that cannot be multiplied with a type of `{}`.",
other.coerce_string()?,
other.get_type()
),
input: "value originates from here".into(),
msg_span: head,
input_span: other.span(),
});
}
}
}
Ok(acc)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/math/ceil.rs | crates/nu-command/src/math/ceil.rs | use crate::math::utils::ensure_bounded;
use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct MathCeil;
impl Command for MathCeil {
fn name(&self) -> &str {
"math ceil"
}
fn signature(&self) -> Signature {
Signature::build("math ceil")
.input_output_types(vec![
(Type::Number, Type::Int),
(
Type::List(Box::new(Type::Number)),
Type::List(Box::new(Type::Int)),
),
(Type::Range, Type::List(Box::new(Type::Number))),
])
.allow_variants_without_examples(true)
.category(Category::Math)
}
fn description(&self) -> &str {
"Returns the ceil of a number (smallest integer greater than or equal to that number)."
}
fn search_terms(&self) -> Vec<&str> {
vec!["ceiling", "round up", "rounding", "integer"]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
// This doesn't match explicit nulls
if let PipelineData::Empty = input {
return Err(ShellError::PipelineEmpty { dst_span: head });
}
if let PipelineData::Value(ref v @ Value::Range { ref val, .. }, ..) = input {
let span = v.span();
ensure_bounded(val, span, head)?;
}
input.map(move |value| operate(value, head), engine_state.signals())
}
fn run_const(
&self,
working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
// This doesn't match explicit nulls
if let PipelineData::Empty = input {
return Err(ShellError::PipelineEmpty { dst_span: head });
}
if let PipelineData::Value(ref v @ Value::Range { ref val, .. }, ..) = input {
let span = v.span();
ensure_bounded(val, span, head)?;
}
input.map(
move |value| operate(value, head),
working_set.permanent().signals(),
)
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
description: "Apply the ceil function to a list of numbers",
example: "[1.5 2.3 -3.1] | math ceil",
result: Some(Value::list(
vec![Value::test_int(2), Value::test_int(3), Value::test_int(-3)],
Span::test_data(),
)),
}]
}
}
fn operate(value: Value, head: Span) -> Value {
let span = value.span();
match value {
Value::Int { .. } => value,
Value::Float { val, .. } => Value::int(val.ceil() as i64, span),
Value::Error { .. } => value,
other => Value::error(
ShellError::OnlySupportsThisInputType {
exp_input_type: "numeric".into(),
wrong_type: other.get_type().to_string(),
dst_span: head,
src_span: other.span(),
},
head,
),
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(MathCeil {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/math/avg.rs | crates/nu-command/src/math/avg.rs | use crate::math::{
reducers::{Reduce, reducer_for},
utils::run_with_function,
};
use nu_engine::command_prelude::*;
const NS_PER_SEC: i64 = 1_000_000_000;
#[derive(Clone)]
pub struct MathAvg;
impl Command for MathAvg {
fn name(&self) -> &str {
"math avg"
}
fn signature(&self) -> Signature {
Signature::build("math avg")
.input_output_types(vec![
(Type::List(Box::new(Type::Duration)), Type::Duration),
(Type::Duration, Type::Duration),
(Type::List(Box::new(Type::Filesize)), Type::Filesize),
(Type::Filesize, Type::Filesize),
(Type::List(Box::new(Type::Number)), Type::Number),
(Type::Number, Type::Number),
(Type::Range, Type::Number),
(Type::table(), Type::record()),
(Type::record(), Type::record()),
])
.allow_variants_without_examples(true)
.category(Category::Math)
}
fn description(&self) -> &str {
"Returns the average of a list of numbers."
}
fn search_terms(&self) -> Vec<&str> {
vec!["average", "mean", "statistics"]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
run_with_function(call, input, average)
}
fn run_const(
&self,
_working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
run_with_function(call, input, average)
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Compute the average of a list of numbers",
example: "[-50 100.0 25] | math avg",
result: Some(Value::test_float(25.0)),
},
Example {
description: "Compute the average of a list of durations",
example: "[2sec 1min] | math avg",
result: Some(Value::test_duration(31 * NS_PER_SEC)),
},
Example {
description: "Compute the average of each column in a table",
example: "[[a b]; [1 2] [3 4]] | math avg",
result: Some(Value::test_record(record! {
"a" => Value::test_int(2),
"b" => Value::test_int(3),
})),
},
]
}
}
pub fn average(values: &[Value], span: Span, head: Span) -> Result<Value, ShellError> {
let sum = reducer_for(Reduce::Summation);
let total = &sum(Value::int(0, head), values.to_vec(), span, head)?;
let span = total.span();
match total {
Value::Filesize { val, .. } => Ok(Value::filesize(val.get() / values.len() as i64, span)),
Value::Duration { val, .. } => Ok(Value::duration(val / values.len() as i64, span)),
_ => total.div(head, &Value::int(values.len() as i64, head), head),
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(MathAvg {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/math/mode.rs | crates/nu-command/src/math/mode.rs | use crate::math::utils::run_with_function;
use nu_engine::command_prelude::*;
use std::{cmp::Ordering, collections::HashMap};
#[derive(Clone)]
pub struct MathMode;
#[derive(Hash, Eq, PartialEq, Debug)]
enum NumberTypes {
Float,
Int,
Duration,
Filesize,
}
#[derive(Hash, Eq, PartialEq, Debug)]
struct HashableType {
bytes: [u8; 8],
original_type: NumberTypes,
}
impl HashableType {
fn new(bytes: [u8; 8], original_type: NumberTypes) -> HashableType {
HashableType {
bytes,
original_type,
}
}
}
impl Command for MathMode {
fn name(&self) -> &str {
"math mode"
}
fn signature(&self) -> Signature {
Signature::build("math mode")
.input_output_types(vec![
(
Type::List(Box::new(Type::Number)),
Type::List(Box::new(Type::Number)),
),
(
Type::List(Box::new(Type::Duration)),
Type::List(Box::new(Type::Duration)),
),
(
Type::List(Box::new(Type::Filesize)),
Type::List(Box::new(Type::Filesize)),
),
(Type::table(), Type::record()),
])
.allow_variants_without_examples(true)
.category(Category::Math)
}
fn description(&self) -> &str {
"Returns the most frequent element(s) from a list of numbers or tables."
}
fn search_terms(&self) -> Vec<&str> {
vec!["common", "often"]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
run_with_function(call, input, mode)
}
fn run_const(
&self,
_working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
run_with_function(call, input, mode)
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Compute the mode(s) of a list of numbers",
example: "[3 3 9 12 12 15] | math mode",
result: Some(Value::test_list(vec![
Value::test_int(3),
Value::test_int(12),
])),
},
Example {
description: "Compute the mode(s) of the columns of a table",
example: "[{a: 1 b: 3} {a: 2 b: -1} {a: 1 b: 5}] | math mode",
result: Some(Value::test_record(record! {
"a" => Value::list(vec![Value::test_int(1)], Span::test_data()),
"b" => Value::list(
vec![Value::test_int(-1), Value::test_int(3), Value::test_int(5)],
Span::test_data(),
),
})),
},
]
}
}
pub fn mode(values: &[Value], span: Span, head: Span) -> Result<Value, ShellError> {
//In e-q, Value doesn't implement Hash or Eq, so we have to get the values inside
// But f64 doesn't implement Hash, so we get the binary representation to use as
// key in the HashMap
let hashable_values = values
.iter()
.filter(|x| !x.as_float().is_ok_and(f64::is_nan))
.map(|val| match val {
Value::Int { val, .. } => Ok(HashableType::new(val.to_ne_bytes(), NumberTypes::Int)),
Value::Duration { val, .. } => {
Ok(HashableType::new(val.to_ne_bytes(), NumberTypes::Duration))
}
Value::Float { val, .. } => {
Ok(HashableType::new(val.to_ne_bytes(), NumberTypes::Float))
}
Value::Filesize { val, .. } => Ok(HashableType::new(
val.get().to_ne_bytes(),
NumberTypes::Filesize,
)),
Value::Error { error, .. } => Err(*error.clone()),
_ => Err(ShellError::UnsupportedInput {
msg: "Unable to give a result with this input".to_string(),
input: "value originates from here".into(),
msg_span: head,
input_span: span,
}),
})
.collect::<Result<Vec<HashableType>, ShellError>>()?;
let mut frequency_map = HashMap::new();
for v in hashable_values {
let counter = frequency_map.entry(v).or_insert(0);
*counter += 1;
}
let mut max_freq = -1;
let mut modes = Vec::<Value>::new();
for (value, frequency) in &frequency_map {
match max_freq.cmp(frequency) {
Ordering::Less => {
max_freq = *frequency;
modes.clear();
modes.push(recreate_value(value, head));
}
Ordering::Equal => {
modes.push(recreate_value(value, head));
}
Ordering::Greater => (),
}
}
modes.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal));
Ok(Value::list(modes, head))
}
fn recreate_value(hashable_value: &HashableType, head: Span) -> Value {
let bytes = hashable_value.bytes;
match &hashable_value.original_type {
NumberTypes::Int => Value::int(i64::from_ne_bytes(bytes), head),
NumberTypes::Float => Value::float(f64::from_ne_bytes(bytes), head),
NumberTypes::Duration => Value::duration(i64::from_ne_bytes(bytes), head),
NumberTypes::Filesize => Value::filesize(i64::from_ne_bytes(bytes), head),
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(MathMode {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/math/floor.rs | crates/nu-command/src/math/floor.rs | use crate::math::utils::ensure_bounded;
use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct MathFloor;
impl Command for MathFloor {
fn name(&self) -> &str {
"math floor"
}
fn signature(&self) -> Signature {
Signature::build("math floor")
.input_output_types(vec![
(Type::Number, Type::Int),
(
Type::List(Box::new(Type::Number)),
Type::List(Box::new(Type::Int)),
),
(Type::Range, Type::List(Box::new(Type::Number))),
])
.allow_variants_without_examples(true)
.category(Category::Math)
}
fn description(&self) -> &str {
"Returns the floor of a number (largest integer less than or equal to that number)."
}
fn search_terms(&self) -> Vec<&str> {
vec!["round down", "rounding", "integer"]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
match input {
// This doesn't match explicit nulls
PipelineData::Empty => return Err(ShellError::PipelineEmpty { dst_span: head }),
PipelineData::Value(ref value @ Value::Range { val: ref range, .. }, ..) => {
ensure_bounded(range, value.span(), head)?
}
_ => (),
}
input.map(move |value| operate(value, head), engine_state.signals())
}
fn run_const(
&self,
working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
// This doesn't match explicit nulls
if let PipelineData::Empty = input {
return Err(ShellError::PipelineEmpty { dst_span: head });
}
if let PipelineData::Value(ref v @ Value::Range { ref val, .. }, ..) = input {
let span = v.span();
ensure_bounded(val, span, head)?;
}
input.map(
move |value| operate(value, head),
working_set.permanent().signals(),
)
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
description: "Apply the floor function to a list of numbers",
example: "[1.5 2.3 -3.1] | math floor",
result: Some(Value::list(
vec![Value::test_int(1), Value::test_int(2), Value::test_int(-4)],
Span::test_data(),
)),
}]
}
}
fn operate(value: Value, head: Span) -> Value {
let span = value.span();
match value {
Value::Int { .. } => value,
Value::Float { val, .. } => Value::int(val.floor() as i64, span),
Value::Error { .. } => value,
other => Value::error(
ShellError::OnlySupportsThisInputType {
exp_input_type: "numeric".into(),
wrong_type: other.get_type().to_string(),
dst_span: head,
src_span: other.span(),
},
head,
),
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(MathFloor {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/math/stddev.rs | crates/nu-command/src/math/stddev.rs | use super::variance::compute_variance as variance;
use crate::math::utils::run_with_function;
use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct MathStddev;
impl Command for MathStddev {
fn name(&self) -> &str {
"math stddev"
}
fn signature(&self) -> Signature {
Signature::build("math stddev")
.input_output_types(vec![
(Type::List(Box::new(Type::Number)), Type::Number),
(Type::Range, Type::Number),
(Type::table(), Type::record()),
(Type::record(), Type::record()),
])
.switch(
"sample",
"calculate sample standard deviation (i.e. using N-1 as the denominator)",
Some('s'),
)
.allow_variants_without_examples(true)
.category(Category::Math)
}
fn description(&self) -> &str {
"Returns the standard deviation of a list of numbers, or of each column in a table."
}
fn search_terms(&self) -> Vec<&str> {
vec![
"SD",
"standard",
"deviation",
"dispersion",
"variation",
"statistics",
]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let sample = call.has_flag(engine_state, stack, "sample")?;
let name = call.head;
let span = input.span().unwrap_or(name);
let input: PipelineData = match input.try_expand_range() {
Err(_) => {
return Err(ShellError::IncorrectValue {
msg: "Range must be bounded".to_string(),
val_span: span,
call_span: name,
});
}
Ok(val) => val,
};
run_with_function(call, input, compute_stddev(sample))
}
fn run_const(
&self,
working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let sample = call.has_flag_const(working_set, "sample")?;
let name = call.head;
let span = input.span().unwrap_or(name);
let input: PipelineData = match input.try_expand_range() {
Err(_) => {
return Err(ShellError::IncorrectValue {
msg: "Range must be bounded".to_string(),
val_span: span,
call_span: name,
});
}
Ok(val) => val,
};
run_with_function(call, input, compute_stddev(sample))
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Compute the standard deviation of a list of numbers",
example: "[1 2 3 4 5] | math stddev",
result: Some(Value::test_float(std::f64::consts::SQRT_2)),
},
Example {
description: "Compute the sample standard deviation of a list of numbers",
example: "[1 2 3 4 5] | math stddev --sample",
result: Some(Value::test_float(1.5811388300841898)),
},
Example {
description: "Compute the standard deviation of each column in a table",
example: "[[a b]; [1 2] [3 4]] | math stddev",
result: Some(Value::test_record(record! {
"a" => Value::test_int(1),
"b" => Value::test_int(1),
})),
},
]
}
}
pub fn compute_stddev(sample: bool) -> impl Fn(&[Value], Span, Span) -> Result<Value, ShellError> {
move |values: &[Value], span: Span, head: Span| {
// variance() produces its own usable error, so we can use `?` to propagated the error.
let variance = variance(sample)(values, span, head)?;
let val_span = variance.span();
match variance {
Value::Float { val, .. } => Ok(Value::float(val.sqrt(), val_span)),
Value::Int { val, .. } => Ok(Value::float((val as f64).sqrt(), val_span)),
other => Ok(other),
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(MathStddev {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/conversions/fill.rs | crates/nu-command/src/conversions/fill.rs | use nu_cmd_base::input_handler::{CmdArgument, operate};
use nu_engine::command_prelude::*;
use print_positions::print_positions;
#[derive(Clone)]
pub struct Fill;
struct Arguments {
width: usize,
alignment: FillAlignment,
character: String,
cell_paths: Option<Vec<CellPath>>,
}
impl CmdArgument for Arguments {
fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> {
self.cell_paths.take()
}
}
#[derive(Clone, Copy)]
enum FillAlignment {
Left,
Right,
Middle,
MiddleRight,
}
impl Command for Fill {
fn name(&self) -> &str {
"fill"
}
fn description(&self) -> &str {
"Fill and Align."
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build("fill")
.input_output_types(vec![
(Type::Int, Type::String),
(Type::Float, Type::String),
(Type::String, Type::String),
(Type::Filesize, Type::String),
(
Type::List(Box::new(Type::Int)),
Type::List(Box::new(Type::String)),
),
(
Type::List(Box::new(Type::Float)),
Type::List(Box::new(Type::String)),
),
(
Type::List(Box::new(Type::String)),
Type::List(Box::new(Type::String)),
),
(
Type::List(Box::new(Type::Filesize)),
Type::List(Box::new(Type::String)),
),
// General case for heterogeneous lists
(
Type::List(Box::new(Type::Any)),
Type::List(Box::new(Type::String)),
),
])
.allow_variants_without_examples(true)
.named(
"width",
SyntaxShape::Int,
"The width of the output. Defaults to 1",
Some('w'),
)
.param(
Flag::new("alignment")
.short('a')
.arg(SyntaxShape::String)
.desc(
"The alignment of the output. Defaults to Left (Left(l), Right(r), \
Center(c/m), MiddleRight(cr/mr))",
)
.completion(Completion::new_list(&[
"left",
"right",
"middle",
"middleright",
])),
)
.named(
"character",
SyntaxShape::String,
"The character to fill with. Defaults to ' ' (space)",
Some('c'),
)
.category(Category::Conversions)
}
fn search_terms(&self) -> Vec<&str> {
vec!["display", "render", "format", "pad", "align", "repeat"]
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Fill a string on the left side to a width of 15 with the character '─'",
example: "'nushell' | fill --alignment l --character '─' --width 15",
result: Some(Value::string("nushell────────", Span::test_data())),
},
Example {
description: "Fill a string on the right side to a width of 15 with the character '─'",
example: "'nushell' | fill --alignment r --character '─' --width 15",
result: Some(Value::string("────────nushell", Span::test_data())),
},
Example {
description: "Fill an empty string with 10 '─' characters",
example: "'' | fill --character '─' --width 10",
result: Some(Value::string("──────────", Span::test_data())),
},
Example {
description: "Fill a number on the left side to a width of 5 with the character '0'",
example: "1 | fill --alignment right --character '0' --width 5",
result: Some(Value::string("00001", Span::test_data())),
},
Example {
description: "Fill a number on both sides to a width of 5 with the character '0'",
example: "1.1 | fill --alignment center --character '0' --width 5",
result: Some(Value::string("01.10", Span::test_data())),
},
Example {
description: "Fill a filesize on both sides to a width of 10 with the character '0'",
example: "1kib | fill --alignment middle --character '0' --width 10",
result: Some(Value::string("0001024000", Span::test_data())),
},
]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
fill(engine_state, stack, call, input)
}
}
fn fill(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
let width_arg: Option<usize> = call.get_flag(engine_state, stack, "width")?;
let alignment_arg: Option<String> = call.get_flag(engine_state, stack, "alignment")?;
let character_arg: Option<String> = call.get_flag(engine_state, stack, "character")?;
let cell_paths: Vec<CellPath> = call.rest(engine_state, stack, 0)?;
let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths);
let alignment = if let Some(arg) = alignment_arg {
match arg.to_ascii_lowercase().as_str() {
"l" | "left" => FillAlignment::Left,
"r" | "right" => FillAlignment::Right,
"c" | "center" | "m" | "middle" => FillAlignment::Middle,
"cr" | "centerright" | "mr" | "middleright" => FillAlignment::MiddleRight,
_ => FillAlignment::Left,
}
} else {
FillAlignment::Left
};
let width = width_arg.unwrap_or(1);
let character = character_arg.unwrap_or_else(|| " ".to_string());
let arg = Arguments {
width,
alignment,
character,
cell_paths,
};
operate(action, arg, input, call.head, engine_state.signals())
}
fn action(input: &Value, args: &Arguments, span: Span) -> Value {
match input {
Value::Int { val, .. } => fill_int(*val, args, span),
Value::Filesize { val, .. } => fill_int(val.get(), args, span),
Value::Float { val, .. } => fill_float(*val, args, span),
Value::String { val, .. } => fill_string(val, args, span),
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => input.clone(),
other => Value::error(
ShellError::OnlySupportsThisInputType {
exp_input_type: "int, filesize, float, string".into(),
wrong_type: other.get_type().to_string(),
dst_span: span,
src_span: other.span(),
},
span,
),
}
}
fn fill_float(num: f64, args: &Arguments, span: Span) -> Value {
let s = num.to_string();
let out_str = pad(&s, args.width, &args.character, args.alignment, false);
Value::string(out_str, span)
}
fn fill_int(num: i64, args: &Arguments, span: Span) -> Value {
let s = num.to_string();
let out_str = pad(&s, args.width, &args.character, args.alignment, false);
Value::string(out_str, span)
}
fn fill_string(s: &str, args: &Arguments, span: Span) -> Value {
let out_str = pad(s, args.width, &args.character, args.alignment, false);
Value::string(out_str, span)
}
fn pad(s: &str, width: usize, pad_char: &str, alignment: FillAlignment, truncate: bool) -> String {
// Attribution: Most of this function was taken from https://github.com/ogham/rust-pad and tweaked. Thank you!
// Use width instead of len for graphical display
let cols = print_positions(s).count();
if cols >= width {
if truncate {
return s[..width].to_string();
} else {
return s.to_string();
}
}
let diff = width - cols;
let (left_pad, right_pad) = match alignment {
FillAlignment::Left => (0, diff),
FillAlignment::Right => (diff, 0),
FillAlignment::Middle => (diff / 2, diff - diff / 2),
FillAlignment::MiddleRight => (diff - diff / 2, diff / 2),
};
let mut new_str = String::new();
for _ in 0..left_pad {
new_str.push_str(pad_char)
}
new_str.push_str(s);
for _ in 0..right_pad {
new_str.push_str(pad_char)
}
new_str
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(Fill {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/conversions/split_cell_path.rs | crates/nu-command/src/conversions/split_cell_path.rs | use nu_engine::command_prelude::*;
use nu_protocol::{IntoValue, ast::PathMember, casing::Casing};
#[derive(Clone)]
pub struct SplitCellPath;
impl Command for SplitCellPath {
fn name(&self) -> &str {
"split cell-path"
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.input_output_types(vec![
(Type::CellPath, Type::List(Box::new(Type::Any))),
(
Type::CellPath,
Type::List(Box::new(Type::Record(
[
("value".into(), Type::Any),
("optional".into(), Type::Bool),
("insensitive".into(), Type::Bool),
]
.into(),
))),
),
])
.category(Category::Conversions)
.allow_variants_without_examples(true)
}
fn description(&self) -> &str {
"Split a cell-path into its components."
}
fn search_terms(&self) -> Vec<&str> {
vec!["convert"]
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let input_type = input.get_type();
let src_span = match input {
// Early return on correct type and empty pipeline
PipelineData::Value(Value::CellPath { val, .. }, _) => {
return Ok(split_cell_path(val, head)?.into_pipeline_data());
}
PipelineData::Empty => return Err(ShellError::PipelineEmpty { dst_span: head }),
// Extract span from incorrect pipeline types
// NOTE: Match arms can't be combined, `stream`s are of different types
PipelineData::Value(other, _) => other.span(),
PipelineData::ListStream(stream, ..) => stream.span(),
PipelineData::ByteStream(stream, ..) => stream.span(),
};
Err(ShellError::OnlySupportsThisInputType {
exp_input_type: "cell-path".into(),
wrong_type: input_type.to_string(),
dst_span: head,
src_span,
})
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Split a cell-path into its components",
example: "$.5?.c | split cell-path",
result: Some(Value::test_list(vec![
Value::test_record(record! {
"value" => Value::test_int(5),
"optional" => Value::test_bool(true),
"insensitive" => Value::test_bool(false),
}),
Value::test_record(record! {
"value" => Value::test_string("c"),
"optional" => Value::test_bool(false),
"insensitive" => Value::test_bool(false),
}),
])),
},
Example {
description: "Split a complex cell-path",
example: r#"$.a!.b?.1."2"."c.d" | split cell-path"#,
result: Some(Value::test_list(vec![
Value::test_record(record! {
"value" => Value::test_string("a"),
"optional" => Value::test_bool(false),
"insensitive" => Value::test_bool(true),
}),
Value::test_record(record! {
"value" => Value::test_string("b"),
"optional" => Value::test_bool(true),
"insensitive" => Value::test_bool(false),
}),
Value::test_record(record! {
"value" => Value::test_int(1),
"optional" => Value::test_bool(false),
"insensitive" => Value::test_bool(false),
}),
Value::test_record(record! {
"value" => Value::test_string("2"),
"optional" => Value::test_bool(false),
"insensitive" => Value::test_bool(false),
}),
Value::test_record(record! {
"value" => Value::test_string("c.d"),
"optional" => Value::test_bool(false),
"insensitive" => Value::test_bool(false),
}),
])),
},
]
}
}
fn split_cell_path(val: CellPath, span: Span) -> Result<Value, ShellError> {
#[derive(IntoValue)]
struct PathMemberRecord {
value: Value,
optional: bool,
insensitive: bool,
}
impl PathMemberRecord {
fn from_path_member(pm: PathMember) -> Self {
let (optional, insensitive, internal_span) = match pm {
PathMember::String {
optional,
casing,
span,
..
} => (optional, casing == Casing::Insensitive, span),
PathMember::Int { optional, span, .. } => (optional, false, span),
};
let value = match pm {
PathMember::String { val, .. } => Value::string(val, internal_span),
PathMember::Int { val, .. } => Value::int(val as i64, internal_span),
};
Self {
value,
optional,
insensitive,
}
}
}
let members = val
.members
.into_iter()
.map(|pm| {
let span = match pm {
PathMember::String { span, .. } | PathMember::Int { span, .. } => span,
};
PathMemberRecord::from_path_member(pm).into_value(span)
})
.collect();
Ok(Value::list(members, span))
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SplitCellPath {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/conversions/mod.rs | crates/nu-command/src/conversions/mod.rs | mod fill;
pub(crate) mod into;
mod split_cell_path;
pub use fill::Fill;
pub use into::*;
pub use split_cell_path::SplitCellPath;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/conversions/into/filesize.rs | crates/nu-command/src/conversions/into/filesize.rs | use nu_cmd_base::input_handler::{CellPathOnlyArgs, operate};
use nu_engine::command_prelude::*;
use nu_utils::get_system_locale;
#[derive(Clone)]
pub struct IntoFilesize;
impl Command for IntoFilesize {
fn name(&self) -> &str {
"into filesize"
}
fn signature(&self) -> Signature {
Signature::build("into filesize")
.input_output_types(vec![
(Type::Int, Type::Filesize),
(Type::Number, Type::Filesize),
(Type::String, Type::Filesize),
(Type::Filesize, Type::Filesize),
(Type::table(), Type::table()),
(Type::record(), Type::record()),
(
Type::List(Box::new(Type::Int)),
Type::List(Box::new(Type::Filesize)),
),
(
Type::List(Box::new(Type::Number)),
Type::List(Box::new(Type::Filesize)),
),
(
Type::List(Box::new(Type::String)),
Type::List(Box::new(Type::Filesize)),
),
(
Type::List(Box::new(Type::Filesize)),
Type::List(Box::new(Type::Filesize)),
),
// Catch all for heterogeneous lists.
(
Type::List(Box::new(Type::Any)),
Type::List(Box::new(Type::Filesize)),
),
])
.allow_variants_without_examples(true)
.rest(
"rest",
SyntaxShape::CellPath,
"For a data structure input, convert data at the given cell paths.",
)
.category(Category::Conversions)
}
fn description(&self) -> &str {
"Convert value to filesize."
}
fn search_terms(&self) -> Vec<&str> {
vec!["convert", "number", "bytes"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let cell_paths: Vec<CellPath> = call.rest(engine_state, stack, 0)?;
let args = CellPathOnlyArgs::from(cell_paths);
operate(action, args, input, call.head, engine_state.signals())
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Convert string to filesize in table",
example: r#"[[device size]; ["/dev/sda1" "200"] ["/dev/loop0" "50"]] | into filesize size"#,
result: Some(Value::test_list(vec![
Value::test_record(record! {
"device" => Value::test_string("/dev/sda1"),
"size" => Value::test_filesize(200),
}),
Value::test_record(record! {
"device" => Value::test_string("/dev/loop0"),
"size" => Value::test_filesize(50),
}),
])),
},
Example {
description: "Convert string to filesize",
example: "'2' | into filesize",
result: Some(Value::test_filesize(2)),
},
Example {
description: "Convert float to filesize",
example: "8.3 | into filesize",
result: Some(Value::test_filesize(8)),
},
Example {
description: "Convert int to filesize",
example: "5 | into filesize",
result: Some(Value::test_filesize(5)),
},
Example {
description: "Convert file size to filesize",
example: "4KB | into filesize",
result: Some(Value::test_filesize(4000)),
},
Example {
description: "Convert string with unit to filesize",
example: "'-1KB' | into filesize",
result: Some(Value::test_filesize(-1000)),
},
]
}
}
fn action(input: &Value, _args: &CellPathOnlyArgs, span: Span) -> Value {
let value_span = input.span();
match input {
Value::Filesize { .. } => input.clone(),
Value::Int { val, .. } => Value::filesize(*val, value_span),
Value::Float { val, .. } => Value::filesize(*val as i64, value_span),
Value::String { val, .. } => match i64_from_string(val, value_span) {
Ok(val) => Value::filesize(val, value_span),
Err(error) => Value::error(error, value_span),
},
Value::Nothing { .. } => Value::filesize(0, value_span),
other => Value::error(
ShellError::OnlySupportsThisInputType {
exp_input_type: "string and int".into(),
wrong_type: other.get_type().to_string(),
dst_span: span,
src_span: value_span,
},
span,
),
}
}
fn i64_from_string(a_string: &str, span: Span) -> Result<i64, ShellError> {
// Get the Locale so we know what the thousands separator is
let locale = get_system_locale();
// Now that we know the locale, get the thousands separator and remove it
// so strings like 1,123,456 can be parsed as 1123456
let no_comma_string = a_string.replace(locale.separator(), "");
let clean_string = no_comma_string.trim();
// Handle negative file size
if let Some(stripped_negative_string) = clean_string.strip_prefix('-') {
match stripped_negative_string.parse::<bytesize::ByteSize>() {
Ok(n) => i64_from_byte_size(n, true, span),
Err(_) => Err(string_convert_error(span)),
}
} else if let Some(stripped_positive_string) = clean_string.strip_prefix('+') {
match stripped_positive_string.parse::<bytesize::ByteSize>() {
Ok(n) if stripped_positive_string.starts_with(|c: char| c.is_ascii_digit()) => {
i64_from_byte_size(n, false, span)
}
_ => Err(string_convert_error(span)),
}
} else {
match clean_string.parse::<bytesize::ByteSize>() {
Ok(n) => i64_from_byte_size(n, false, span),
Err(_) => Err(string_convert_error(span)),
}
}
}
fn i64_from_byte_size(
byte_size: bytesize::ByteSize,
is_negative: bool,
span: Span,
) -> Result<i64, ShellError> {
match i64::try_from(byte_size.as_u64()) {
Ok(n) => Ok(if is_negative { -n } else { n }),
Err(_) => Err(string_convert_error(span)),
}
}
fn string_convert_error(span: Span) -> ShellError {
ShellError::CantConvert {
to_type: "filesize".into(),
from_type: "string".into(),
span,
help: None,
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(IntoFilesize {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/conversions/into/command.rs | crates/nu-command/src/conversions/into/command.rs | use nu_engine::{command_prelude::*, get_full_help};
#[derive(Clone)]
pub struct Into;
impl Command for Into {
fn name(&self) -> &str {
"into"
}
fn signature(&self) -> Signature {
Signature::build("into")
.category(Category::Conversions)
.input_output_types(vec![(Type::Nothing, Type::String)])
}
fn description(&self) -> &str {
"Commands to convert data from one type to another."
}
fn extra_description(&self) -> &str {
"You must use one of the following subcommands. Using this command as-is will only produce this help message."
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
Ok(Value::string(get_full_help(self, engine_state, stack), call.head).into_pipeline_data())
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/conversions/into/datetime.rs | crates/nu-command/src/conversions/into/datetime.rs | use crate::{generate_strftime_list, parse_date_from_string};
use chrono::{
DateTime, Datelike, FixedOffset, Local, NaiveDate, NaiveDateTime, NaiveTime, TimeZone,
Timelike, Utc,
};
use nu_cmd_base::input_handler::{CmdArgument, operate};
use nu_engine::command_prelude::*;
const HOUR: i32 = 60 * 60;
const ALLOWED_COLUMNS: [&str; 10] = [
"year",
"month",
"day",
"hour",
"minute",
"second",
"millisecond",
"microsecond",
"nanosecond",
"timezone",
];
#[derive(Clone, Debug)]
struct Arguments {
zone_options: Option<Spanned<Zone>>,
format_options: Option<Spanned<DatetimeFormat>>,
cell_paths: Option<Vec<CellPath>>,
}
impl CmdArgument for Arguments {
fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> {
self.cell_paths.take()
}
}
// In case it may be confused with chrono::TimeZone
#[derive(Clone, Debug)]
enum Zone {
Utc,
Local,
East(u8),
West(u8),
Error, // we want Nushell to cast it instead of Rust
}
impl Zone {
const OPTIONS: &[&str] = &["utc", "local"];
fn new(i: i64) -> Self {
if i.abs() <= 12 {
// guaranteed here
if i >= 0 {
Self::East(i as u8) // won't go out of range
} else {
Self::West(-i as u8) // same here
}
} else {
Self::Error // Out of range
}
}
fn from_string(s: &str) -> Self {
match s.to_ascii_lowercase().as_str() {
"utc" | "u" => Self::Utc,
"local" | "l" => Self::Local,
_ => Self::Error,
}
}
}
#[derive(Clone)]
pub struct IntoDatetime;
impl Command for IntoDatetime {
fn name(&self) -> &str {
"into datetime"
}
fn signature(&self) -> Signature {
Signature::build("into datetime")
.input_output_types(vec![
(Type::Date, Type::Date),
(Type::Int, Type::Date),
(Type::String, Type::Date),
(
Type::List(Box::new(Type::String)),
Type::List(Box::new(Type::Date)),
),
(Type::table(), Type::table()),
(Type::Nothing, Type::table()),
(Type::record(), Type::record()),
(Type::record(), Type::Date),
// FIXME Type::Any input added to disable pipeline input type checking, as run-time checks can raise undesirable type errors
// which aren't caught by the parser. see https://github.com/nushell/nushell/pull/14922 for more details
// only applicable for --list flag
(Type::Any, Type::table()),
])
.allow_variants_without_examples(true)
.param(
Flag::new("timezone")
.short('z')
.arg(SyntaxShape::String)
.desc(
"Specify timezone if the input is a Unix timestamp. Valid options: 'UTC' \
('u') or 'LOCAL' ('l')",
)
.completion(Completion::new_list(Zone::OPTIONS)),
)
.named(
"offset",
SyntaxShape::Int,
"Specify timezone by offset from UTC if the input is a Unix timestamp, like '+8', \
'-4'",
Some('o'),
)
.named(
"format",
SyntaxShape::String,
"Specify expected format of INPUT string to parse to datetime. Use --list to see \
options",
Some('f'),
)
.switch(
"list",
"Show all possible variables for use in --format flag",
Some('l'),
)
.rest(
"rest",
SyntaxShape::CellPath,
"For a data structure input, convert data at the given cell paths.",
)
.category(Category::Conversions)
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
if call.has_flag(engine_state, stack, "list")? {
Ok(generate_strftime_list(call.head, true).into_pipeline_data())
} else {
let cell_paths = call.rest(engine_state, stack, 0)?;
let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths);
// if zone-offset is specified, then zone will be neglected
let timezone = call.get_flag::<Spanned<String>>(engine_state, stack, "timezone")?;
let zone_options =
match &call.get_flag::<Spanned<i64>>(engine_state, stack, "offset")? {
Some(zone_offset) => Some(Spanned {
item: Zone::new(zone_offset.item),
span: zone_offset.span,
}),
None => timezone.as_ref().map(|zone| Spanned {
item: Zone::from_string(&zone.item),
span: zone.span,
}),
};
let format_options = call
.get_flag::<Spanned<String>>(engine_state, stack, "format")?
.as_ref()
.map(|fmt| Spanned {
item: DatetimeFormat(fmt.item.to_string()),
span: fmt.span,
});
let args = Arguments {
zone_options,
format_options,
cell_paths,
};
operate(action, args, input, call.head, engine_state.signals())
}
}
fn description(&self) -> &str {
"Convert text or timestamp into a datetime."
}
fn search_terms(&self) -> Vec<&str> {
vec!["convert", "timezone", "UTC"]
}
fn examples(&self) -> Vec<Example<'_>> {
let example_result_1 = |nanos: i64| {
Some(Value::date(
Utc.timestamp_nanos(nanos).into(),
Span::test_data(),
))
};
vec![
Example {
description: "Convert timestamp string to datetime with timezone offset",
example: "'27.02.2021 1:55 pm +0000' | into datetime",
#[allow(clippy::inconsistent_digit_grouping)]
result: example_result_1(1614434100_000000000),
},
Example {
description: "Convert standard timestamp string to datetime with timezone offset",
example: "'2021-02-27T13:55:40.2246+00:00' | into datetime",
#[allow(clippy::inconsistent_digit_grouping)]
result: example_result_1(1614434140_224600000),
},
Example {
description: "Convert non-standard timestamp string, with timezone offset, to \
datetime using a custom format",
example: "'20210227_135540+0000' | into datetime --format '%Y%m%d_%H%M%S%z'",
#[allow(clippy::inconsistent_digit_grouping)]
result: example_result_1(1614434140_000000000),
},
Example {
description: "Convert non-standard timestamp string, without timezone offset, to \
datetime with custom formatting",
example: "'16.11.1984 8:00 am' | into datetime --format '%d.%m.%Y %H:%M %P'",
#[allow(clippy::inconsistent_digit_grouping)]
result: Some(Value::date(
Local
.from_local_datetime(
&NaiveDateTime::parse_from_str(
"16.11.1984 8:00 am",
"%d.%m.%Y %H:%M %P",
)
.expect("date calculation should not fail in test"),
)
.unwrap()
.with_timezone(Local::now().offset()),
Span::test_data(),
)),
},
Example {
description: "Convert nanosecond-precision unix timestamp to a datetime with \
offset from UTC",
example: "1614434140123456789 | into datetime --offset -5",
#[allow(clippy::inconsistent_digit_grouping)]
result: example_result_1(1614434140_123456789),
},
Example {
description: "Convert standard (seconds) unix timestamp to a UTC datetime",
example: "1614434140 | into datetime -f '%s'",
#[allow(clippy::inconsistent_digit_grouping)]
result: example_result_1(1614434140_000000000),
},
Example {
description: "Using a datetime as input simply returns the value",
example: "2021-02-27T13:55:40 | into datetime",
#[allow(clippy::inconsistent_digit_grouping)]
result: example_result_1(1614434140_000000000),
},
Example {
description: "Using a record as input",
example: "{year: 2025, month: 3, day: 30, hour: 12, minute: 15, second: 59, \
timezone: '+02:00'} | into datetime",
#[allow(clippy::inconsistent_digit_grouping)]
result: example_result_1(1743329759_000000000),
},
Example {
description: "Convert list of timestamps to datetimes",
example: r#"["2023-03-30 10:10:07 -05:00", "2023-05-05 13:43:49 -05:00", "2023-06-05 01:37:42 -05:00"] | into datetime"#,
result: Some(Value::list(
vec![
Value::date(
DateTime::parse_from_str(
"2023-03-30 10:10:07 -05:00",
"%Y-%m-%d %H:%M:%S %z",
)
.expect("date calculation should not fail in test"),
Span::test_data(),
),
Value::date(
DateTime::parse_from_str(
"2023-05-05 13:43:49 -05:00",
"%Y-%m-%d %H:%M:%S %z",
)
.expect("date calculation should not fail in test"),
Span::test_data(),
),
Value::date(
DateTime::parse_from_str(
"2023-06-05 01:37:42 -05:00",
"%Y-%m-%d %H:%M:%S %z",
)
.expect("date calculation should not fail in test"),
Span::test_data(),
),
],
Span::test_data(),
)),
},
]
}
}
#[derive(Clone, Debug)]
struct DatetimeFormat(String);
fn action(input: &Value, args: &Arguments, head: Span) -> Value {
let timezone = &args.zone_options;
let dateformat = &args.format_options;
// noop if the input is already a datetime
if let Value::Date { .. } = input {
return input.clone();
}
if let Value::Record { val: record, .. } = input {
if let Some(tz) = timezone {
return Value::error(
ShellError::IncompatibleParameters {
left_message: "got a record as input".into(),
left_span: head,
right_message: "the timezone should be included in the record".into(),
right_span: tz.span,
},
head,
);
}
if let Some(dt) = dateformat {
return Value::error(
ShellError::IncompatibleParameters {
left_message: "got a record as input".into(),
left_span: head,
right_message: "cannot be used with records".into(),
right_span: dt.span,
},
head,
);
}
let span = input.span();
return merge_record(record, head, span).unwrap_or_else(|err| Value::error(err, span));
}
// Let's try dtparse first
if matches!(input, Value::String { .. }) && dateformat.is_none() {
let span = input.span();
if let Ok(input_val) = input.coerce_str()
&& let Ok(date) = parse_date_from_string(&input_val, span)
{
return Value::date(date, span);
}
}
// Check to see if input looks like a Unix timestamp (i.e. can it be parsed to an int?)
let timestamp = match input {
Value::Int { val, .. } => Ok(*val),
Value::String { val, .. } => val.parse::<i64>(),
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => return input.clone(),
other => {
return Value::error(
ShellError::OnlySupportsThisInputType {
exp_input_type: "string and int".into(),
wrong_type: other.get_type().to_string(),
dst_span: head,
src_span: other.span(),
},
head,
);
}
};
if dateformat.is_none()
&& let Ok(ts) = timestamp
{
return match timezone {
// note all these `.timestamp_nanos()` could overflow if we didn't check range in `<date> | into int`.
// default to UTC
None => Value::date(Utc.timestamp_nanos(ts).into(), head),
Some(Spanned { item, span }) => match item {
Zone::Utc => {
let dt = Utc.timestamp_nanos(ts);
Value::date(dt.into(), *span)
}
Zone::Local => {
let dt = Local.timestamp_nanos(ts);
Value::date(dt.into(), *span)
}
Zone::East(i) => match FixedOffset::east_opt((*i as i32) * HOUR) {
Some(eastoffset) => {
let dt = eastoffset.timestamp_nanos(ts);
Value::date(dt, *span)
}
None => Value::error(
ShellError::DatetimeParseError {
msg: input.to_abbreviated_string(&nu_protocol::Config::default()),
span: *span,
},
*span,
),
},
Zone::West(i) => match FixedOffset::west_opt((*i as i32) * HOUR) {
Some(westoffset) => {
let dt = westoffset.timestamp_nanos(ts);
Value::date(dt, *span)
}
None => Value::error(
ShellError::DatetimeParseError {
msg: input.to_abbreviated_string(&nu_protocol::Config::default()),
span: *span,
},
*span,
),
},
Zone::Error => Value::error(
// This is an argument error, not an input error
ShellError::TypeMismatch {
err_message: "Invalid timezone or offset".to_string(),
span: *span,
},
*span,
),
},
};
};
// If input is not a timestamp, try parsing it as a string
let span = input.span();
let parse_as_string = |val: &str| {
match dateformat {
Some(dt_format) => {
// Handle custom format specifiers for compact formats
let format_str = dt_format
.item
.0
.replace("%J", "%Y%m%d") // %J for joined date (YYYYMMDD)
.replace("%Q", "%H%M%S"); // %Q for sequential time (HHMMSS)
match DateTime::parse_from_str(val, &format_str) {
Ok(dt) => match timezone {
None => Value::date(dt, head),
Some(Spanned { item, span }) => match item {
Zone::Utc => Value::date(dt, head),
Zone::Local => Value::date(dt.with_timezone(&Local).into(), *span),
Zone::East(i) => match FixedOffset::east_opt((*i as i32) * HOUR) {
Some(eastoffset) => {
Value::date(dt.with_timezone(&eastoffset), *span)
}
None => Value::error(
ShellError::DatetimeParseError {
msg: input
.to_abbreviated_string(&nu_protocol::Config::default()),
span: *span,
},
*span,
),
},
Zone::West(i) => match FixedOffset::west_opt((*i as i32) * HOUR) {
Some(westoffset) => {
Value::date(dt.with_timezone(&westoffset), *span)
}
None => Value::error(
ShellError::DatetimeParseError {
msg: input
.to_abbreviated_string(&nu_protocol::Config::default()),
span: *span,
},
*span,
),
},
Zone::Error => Value::error(
// This is an argument error, not an input error
ShellError::TypeMismatch {
err_message: "Invalid timezone or offset".to_string(),
span: *span,
},
*span,
),
},
},
Err(reason) => parse_with_format(val, &format_str, head).unwrap_or_else(|_| {
Value::error(
ShellError::CantConvert {
to_type: format!(
"could not parse as datetime using format '{}'",
dt_format.item.0
),
from_type: reason.to_string(),
span: head,
help: Some(
"you can use `into datetime` without a format string to \
enable flexible parsing"
.to_string(),
),
},
head,
)
}),
}
}
// Tries to automatically parse the date
// (i.e. without a format string)
// and assumes the system's local timezone if none is specified
None => match parse_date_from_string(val, span) {
Ok(date) => Value::date(date, span),
Err(err) => err,
},
}
};
match input {
Value::String { val, .. } => parse_as_string(val),
Value::Int { val, .. } => parse_as_string(&val.to_string()),
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => input.clone(),
other => Value::error(
ShellError::OnlySupportsThisInputType {
exp_input_type: "string".into(),
wrong_type: other.get_type().to_string(),
dst_span: head,
src_span: other.span(),
},
head,
),
}
}
fn merge_record(record: &Record, head: Span, span: Span) -> Result<Value, ShellError> {
if let Some(invalid_col) = record
.columns()
.find(|key| !ALLOWED_COLUMNS.contains(&key.as_str()))
{
let allowed_cols = ALLOWED_COLUMNS.join(", ");
return Err(ShellError::UnsupportedInput {
msg: format!(
"Column '{invalid_col}' is not valid for a structured datetime. Allowed columns \
are: {allowed_cols}"
),
input: "value originates from here".into(),
msg_span: head,
input_span: span,
});
};
// Empty fields are filled in a specific way: the time units bigger than the biggest provided fields are assumed to be current and smaller ones are zeroed.
// And local timezone is used if not provided.
#[derive(Debug)]
enum RecordColumnDefault {
Now,
Zero,
}
let mut record_column_default = RecordColumnDefault::Now;
let now = Local::now();
let mut now_nanosecond = now.nanosecond();
let now_millisecond = now_nanosecond / 1_000_000;
now_nanosecond %= 1_000_000;
let now_microsecond = now_nanosecond / 1_000;
now_nanosecond %= 1_000;
let year: i32 = match record.get("year") {
Some(val) => {
record_column_default = RecordColumnDefault::Zero;
match val {
Value::Int { val, .. } => *val as i32,
other => {
return Err(ShellError::OnlySupportsThisInputType {
exp_input_type: "int".to_string(),
wrong_type: other.get_type().to_string(),
dst_span: head,
src_span: other.span(),
});
}
}
}
None => now.year(),
};
let month = match record.get("month") {
Some(col_val) => {
record_column_default = RecordColumnDefault::Zero;
parse_value_from_record_as_u32("month", col_val, &head, &span)?
}
None => match record_column_default {
RecordColumnDefault::Now => now.month(),
RecordColumnDefault::Zero => 1,
},
};
let day = match record.get("day") {
Some(col_val) => {
record_column_default = RecordColumnDefault::Zero;
parse_value_from_record_as_u32("day", col_val, &head, &span)?
}
None => match record_column_default {
RecordColumnDefault::Now => now.day(),
RecordColumnDefault::Zero => 1,
},
};
let hour = match record.get("hour") {
Some(col_val) => {
record_column_default = RecordColumnDefault::Zero;
parse_value_from_record_as_u32("hour", col_val, &head, &span)?
}
None => match record_column_default {
RecordColumnDefault::Now => now.hour(),
RecordColumnDefault::Zero => 0,
},
};
let minute = match record.get("minute") {
Some(col_val) => {
record_column_default = RecordColumnDefault::Zero;
parse_value_from_record_as_u32("minute", col_val, &head, &span)?
}
None => match record_column_default {
RecordColumnDefault::Now => now.minute(),
RecordColumnDefault::Zero => 0,
},
};
let second = match record.get("second") {
Some(col_val) => {
record_column_default = RecordColumnDefault::Zero;
parse_value_from_record_as_u32("second", col_val, &head, &span)?
}
None => match record_column_default {
RecordColumnDefault::Now => now.second(),
RecordColumnDefault::Zero => 0,
},
};
let millisecond = match record.get("millisecond") {
Some(col_val) => {
record_column_default = RecordColumnDefault::Zero;
parse_value_from_record_as_u32("millisecond", col_val, &head, &span)?
}
None => match record_column_default {
RecordColumnDefault::Now => now_millisecond,
RecordColumnDefault::Zero => 0,
},
};
let microsecond = match record.get("microsecond") {
Some(col_val) => {
record_column_default = RecordColumnDefault::Zero;
parse_value_from_record_as_u32("microsecond", col_val, &head, &span)?
}
None => match record_column_default {
RecordColumnDefault::Now => now_microsecond,
RecordColumnDefault::Zero => 0,
},
};
let nanosecond = match record.get("nanosecond") {
Some(col_val) => parse_value_from_record_as_u32("nanosecond", col_val, &head, &span)?,
None => match record_column_default {
RecordColumnDefault::Now => now_nanosecond,
RecordColumnDefault::Zero => 0,
},
};
let offset: FixedOffset = match record.get("timezone") {
Some(timezone) => parse_timezone_from_record(timezone, &head, &timezone.span())?,
None => now.offset().to_owned(),
};
let total_nanoseconds = nanosecond + microsecond * 1_000 + millisecond * 1_000_000;
let date = match NaiveDate::from_ymd_opt(year, month, day) {
Some(d) => d,
None => {
return Err(ShellError::IncorrectValue {
msg: "one of more values are incorrect and do not represent valid date".to_string(),
val_span: head,
call_span: span,
});
}
};
let time = match NaiveTime::from_hms_nano_opt(hour, minute, second, total_nanoseconds) {
Some(t) => t,
None => {
return Err(ShellError::IncorrectValue {
msg: "one of more values are incorrect and do not represent valid time".to_string(),
val_span: head,
call_span: span,
});
}
};
let date_time = NaiveDateTime::new(date, time);
let date_time_fixed = match offset.from_local_datetime(&date_time).single() {
Some(d) => d,
None => {
return Err(ShellError::IncorrectValue {
msg: "Ambiguous or invalid timezone conversion".to_string(),
val_span: head,
call_span: span,
});
}
};
Ok(Value::date(date_time_fixed, span))
}
fn parse_value_from_record_as_u32(
col: &str,
col_val: &Value,
head: &Span,
span: &Span,
) -> Result<u32, ShellError> {
let value: u32 = match col_val {
Value::Int { val, .. } => {
if *val < 0 || *val > u32::MAX as i64 {
return Err(ShellError::IncorrectValue {
msg: format!("incorrect value for {col}"),
val_span: *head,
call_span: *span,
});
}
*val as u32
}
other => {
return Err(ShellError::OnlySupportsThisInputType {
exp_input_type: "int".to_string(),
wrong_type: other.get_type().to_string(),
dst_span: *head,
src_span: other.span(),
});
}
};
Ok(value)
}
fn parse_timezone_from_record(
timezone: &Value,
head: &Span,
span: &Span,
) -> Result<FixedOffset, ShellError> {
match timezone {
Value::String { val, .. } => {
let offset: FixedOffset = match val.parse() {
Ok(offset) => offset,
Err(_) => {
return Err(ShellError::IncorrectValue {
msg: "invalid timezone".to_string(),
val_span: *span,
call_span: *head,
});
}
};
Ok(offset)
}
other => Err(ShellError::OnlySupportsThisInputType {
exp_input_type: "string".to_string(),
wrong_type: other.get_type().to_string(),
dst_span: *head,
src_span: other.span(),
}),
}
}
fn parse_with_format(val: &str, fmt: &str, head: Span) -> Result<Value, ()> {
// try parsing at date + time
if let Ok(dt) = NaiveDateTime::parse_from_str(val, fmt) {
let dt_native = Local.from_local_datetime(&dt).single().unwrap_or_default();
return Ok(Value::date(dt_native.into(), head));
}
// try parsing at date only
if let Ok(date) = NaiveDate::parse_from_str(val, fmt)
&& let Some(dt) = date.and_hms_opt(0, 0, 0)
{
let dt_native = Local.from_local_datetime(&dt).single().unwrap_or_default();
return Ok(Value::date(dt_native.into(), head));
}
// try parsing at time only
if let Ok(time) = NaiveTime::parse_from_str(val, fmt) {
let now = Local::now().naive_local().date();
let dt_native = Local
.from_local_datetime(&now.and_time(time))
.single()
.unwrap_or_default();
return Ok(Value::date(dt_native.into(), head));
}
Err(())
}
#[cfg(test)]
mod tests {
use super::*;
use super::{DatetimeFormat, IntoDatetime, Zone, action};
use nu_protocol::Type::Error;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(IntoDatetime {})
}
#[test]
fn takes_a_date_format_with_timezone() {
let date_str = Value::test_string("16.11.1984 8:00 am +0000");
let fmt_options = Some(Spanned {
item: DatetimeFormat("%d.%m.%Y %H:%M %P %z".to_string()),
span: Span::test_data(),
});
let args = Arguments {
zone_options: None,
format_options: fmt_options,
cell_paths: None,
};
let actual = action(&date_str, &args, Span::test_data());
let expected = Value::date(
DateTime::parse_from_str("16.11.1984 8:00 am +0000", "%d.%m.%Y %H:%M %P %z").unwrap(),
Span::test_data(),
);
assert_eq!(actual, expected)
}
#[test]
fn takes_a_date_format_without_timezone() {
let date_str = Value::test_string("16.11.1984 8:00 am");
let fmt_options = Some(Spanned {
item: DatetimeFormat("%d.%m.%Y %H:%M %P".to_string()),
span: Span::test_data(),
});
let args = Arguments {
zone_options: None,
format_options: fmt_options,
cell_paths: None,
};
let actual = action(&date_str, &args, Span::test_data());
let expected = Value::date(
Local
.from_local_datetime(
&NaiveDateTime::parse_from_str("16.11.1984 8:00 am", "%d.%m.%Y %H:%M %P")
.unwrap(),
)
.unwrap()
.with_timezone(Local::now().offset()),
Span::test_data(),
);
assert_eq!(actual, expected)
}
#[test]
fn takes_iso8601_date_format() {
let date_str = Value::test_string("2020-08-04T16:39:18+00:00");
let args = Arguments {
zone_options: None,
format_options: None,
cell_paths: None,
};
let actual = action(&date_str, &args, Span::test_data());
let expected = Value::date(
DateTime::parse_from_str("2020-08-04T16:39:18+00:00", "%Y-%m-%dT%H:%M:%S%z").unwrap(),
Span::test_data(),
);
assert_eq!(actual, expected)
}
#[test]
fn takes_timestamp_offset() {
let date_str = Value::test_string("1614434140000000000");
let timezone_option = Some(Spanned {
item: Zone::East(8),
span: Span::test_data(),
});
let args = Arguments {
zone_options: timezone_option,
format_options: None,
cell_paths: None,
};
let actual = action(&date_str, &args, Span::test_data());
let expected = Value::date(
DateTime::parse_from_str("2021-02-27 21:55:40 +08:00", "%Y-%m-%d %H:%M:%S %z").unwrap(),
Span::test_data(),
);
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | true |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/conversions/into/string.rs | crates/nu-command/src/conversions/into/string.rs | use nu_cmd_base::input_handler::{CmdArgument, operate};
use nu_engine::command_prelude::*;
use nu_protocol::Config;
use nu_utils::get_system_locale;
use num_format::ToFormattedString;
use std::sync::Arc;
struct Arguments {
decimals_value: Option<i64>,
cell_paths: Option<Vec<CellPath>>,
config: Arc<Config>,
group_digits: bool,
}
impl CmdArgument for Arguments {
fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> {
self.cell_paths.take()
}
}
#[derive(Clone)]
pub struct IntoString;
impl Command for IntoString {
fn name(&self) -> &str {
"into string"
}
fn signature(&self) -> Signature {
Signature::build("into string")
.input_output_types(vec![
(Type::Binary, Type::String),
(Type::Int, Type::String),
(Type::Number, Type::String),
(Type::String, Type::String),
(Type::Glob, Type::String),
(Type::Bool, Type::String),
(Type::Filesize, Type::String),
(Type::Date, Type::String),
(Type::Duration, Type::String),
(Type::CellPath, Type::String),
(Type::Range, Type::String),
(
Type::List(Box::new(Type::Any)),
Type::List(Box::new(Type::String)),
),
(Type::table(), Type::table()),
(Type::record(), Type::record()),
])
.allow_variants_without_examples(true) // https://github.com/nushell/nushell/issues/7032
.rest(
"rest",
SyntaxShape::CellPath,
"For a data structure input, convert data at the given cell paths.",
)
.switch(
"group-digits",
"group digits together by the locale specific thousands separator",
Some('g'),
)
.named(
"decimals",
SyntaxShape::Int,
"decimal digits to which to round",
Some('d'),
)
.category(Category::Conversions)
}
fn description(&self) -> &str {
"Convert value to string."
}
fn search_terms(&self) -> Vec<&str> {
vec!["convert", "text"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
string_helper(engine_state, stack, call, input)
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "convert int to string and append three decimal places",
example: "5 | into string --decimals 3",
result: Some(Value::test_string("5.000")),
},
Example {
description: "convert float to string and round to nearest integer",
example: "1.7 | into string --decimals 0",
result: Some(Value::test_string("2")),
},
Example {
description: "convert float to string",
example: "1.7 | into string --decimals 1",
result: Some(Value::test_string("1.7")),
},
Example {
description: "convert float to string and limit to 2 decimals",
example: "1.734 | into string --decimals 2",
result: Some(Value::test_string("1.73")),
},
Example {
description: "convert float to string",
example: "4.3 | into string",
result: Some(Value::test_string("4.3")),
},
Example {
description: "convert string to string",
example: "'1234' | into string",
result: Some(Value::test_string("1234")),
},
Example {
description: "convert boolean to string",
example: "true | into string",
result: Some(Value::test_string("true")),
},
Example {
description: "convert date to string",
example: "'2020-10-10 10:00:00 +02:00' | into datetime | into string",
result: Some(Value::test_string("Sat Oct 10 10:00:00 2020")),
},
Example {
description: "convert filepath to string",
example: "ls Cargo.toml | get name | into string",
result: None,
},
Example {
description: "convert filesize to string",
example: "1kB | into string",
result: Some(Value::test_string("1.0 kB")),
},
Example {
description: "convert duration to string",
example: "9day | into string",
result: Some(Value::test_string("1wk 2day")),
},
Example {
description: "convert cell-path to string",
example: "$.name | into string",
result: Some(Value::test_string("$.name")),
},
]
}
}
fn string_helper(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let decimals_value: Option<i64> = call.get_flag(engine_state, stack, "decimals")?;
let group_digits = call.has_flag(engine_state, stack, "group-digits")?;
if let Some(decimal_val) = decimals_value
&& decimal_val.is_negative()
{
return Err(ShellError::TypeMismatch {
err_message: "Cannot accept negative integers for decimals arguments".to_string(),
span: head,
});
}
let cell_paths = call.rest(engine_state, stack, 0)?;
let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths);
if let PipelineData::ByteStream(stream, metadata) = input {
// Just set the type - that should be good enough. There is no guarantee that the data
// within a string stream is actually valid UTF-8. But refuse to do it if it was already set
// to binary
if stream.type_().is_string_coercible() {
Ok(PipelineData::byte_stream(
stream.with_type(ByteStreamType::String),
metadata,
))
} else {
Err(ShellError::CantConvert {
to_type: "string".into(),
from_type: "binary".into(),
span: stream.span(),
help: Some("try using the `decode` command".into()),
})
}
} else {
let config = stack.get_config(engine_state);
let args = Arguments {
decimals_value,
cell_paths,
config,
group_digits,
};
operate(action, args, input, head, engine_state.signals())
}
}
fn action(input: &Value, args: &Arguments, span: Span) -> Value {
let digits = args.decimals_value;
let config = &args.config;
let group_digits = args.group_digits;
match input {
Value::Int { val, .. } => {
let decimal_value = digits.unwrap_or(0) as usize;
let res = format_int(*val, group_digits, decimal_value);
Value::string(res, span)
}
Value::Float { val, .. } => {
if let Some(decimal_value) = digits {
let decimal_value = decimal_value as usize;
Value::string(format!("{val:.decimal_value$}"), span)
} else {
Value::string(val.to_string(), span)
}
}
Value::Bool { val, .. } => Value::string(val.to_string(), span),
Value::Date { val, .. } => Value::string(val.format("%c").to_string(), span),
Value::String { val, .. } => Value::string(val, span),
Value::Glob { val, .. } => Value::string(val, span),
Value::CellPath { val, .. } => Value::string(val.to_string(), span),
Value::Filesize { val, .. } => {
if group_digits {
let decimal_value = digits.unwrap_or(0) as usize;
Value::string(format_int(val.get(), group_digits, decimal_value), span)
} else {
Value::string(input.to_expanded_string(", ", config), span)
}
}
Value::Duration { val: _, .. } => Value::string(input.to_expanded_string("", config), span),
Value::Nothing { .. } => Value::string("".to_string(), span),
Value::Record { .. } => Value::error(
// Watch out for CantConvert's argument order
ShellError::CantConvert {
to_type: "string".into(),
from_type: "record".into(),
span,
help: Some("try using the `to nuon` command".into()),
},
span,
),
Value::Binary { .. } => Value::error(
ShellError::CantConvert {
to_type: "string".into(),
from_type: "binary".into(),
span,
help: Some("try using the `decode` command".into()),
},
span,
),
Value::Custom { val, .. } => {
// Only custom values that have a base value that can be converted to string are
// accepted.
val.to_base_value(input.span())
.and_then(|base_value| match action(&base_value, args, span) {
Value::Error { .. } => Err(ShellError::CantConvert {
to_type: String::from("string"),
from_type: val.type_name(),
span,
help: Some("this custom value can't be represented as a string".into()),
}),
success => Ok(success),
})
.unwrap_or_else(|err| Value::error(err, span))
}
Value::Error { .. } => input.clone(),
x => Value::error(
ShellError::CantConvert {
to_type: String::from("string"),
from_type: x.get_type().to_string(),
span,
help: None,
},
span,
),
}
}
fn format_int(int: i64, group_digits: bool, decimals: usize) -> String {
let locale = get_system_locale();
let str = if group_digits {
int.to_formatted_string(&locale)
} else {
int.to_string()
};
if decimals > 0 {
let decimal_point = locale.decimal();
format!(
"{}{decimal_point}{dummy:0<decimals$}",
str,
decimal_point = decimal_point,
dummy = "",
decimals = decimals
)
} else {
str
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(IntoString {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/conversions/into/value.rs | crates/nu-command/src/conversions/into/value.rs | use std::sync::OnceLock;
use nu_engine::command_prelude::*;
use nu_protocol::{
BlockId, DeprecationEntry, DeprecationType, ReportMode, debugger::WithoutDebug,
report_shell_warning,
};
// TODO: remove this after deprecation phase
static DEPRECATED_REDIRECT_BLOCK_ID: OnceLock<BlockId> = OnceLock::new();
#[derive(Clone)]
pub struct IntoValue;
impl Command for IntoValue {
fn name(&self) -> &str {
"into value"
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.description(self.description())
.extra_description(self.extra_description())
.input_output_type(Type::Any, Type::Any)
.category(Category::Conversions)
// TODO: remove these after deprecation phase
.named(
"columns",
SyntaxShape::List(Box::new(SyntaxShape::Any)),
"list of columns to update",
Some('c'),
)
.switch(
"prefer-filesizes",
"For ints display them as human-readable file sizes",
Some('f'),
)
}
fn deprecation_info(&self) -> Vec<DeprecationEntry> {
vec![
DeprecationEntry {
ty: DeprecationType::Flag("columns".to_string()),
report_mode: ReportMode::EveryUse,
since: Some("0.108.0".into()),
expected_removal: Some("0.109.0".into()),
help: Some("Use this flag on `detect type`.".into()),
},
DeprecationEntry {
ty: DeprecationType::Flag("prefer-filesizes".to_string()),
report_mode: ReportMode::EveryUse,
since: Some("0.108.0".into()),
expected_removal: Some("0.109.0".into()),
help: Some("Use this flag on `detect type`.".into()),
},
]
}
fn description(&self) -> &str {
"Convert custom values into base values."
}
fn extra_description(&self) -> &str {
"Custom values from plugins have a base value representation. \
This extracts that base value representation. \
For streams use `collect`."
}
fn search_terms(&self) -> Vec<&str> {
vec!["custom", "base", "convert", "conversion"]
}
fn examples(&self) -> Vec<Example<'_>> {
vec![]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
if let PipelineData::Value(v @ Value::Custom { .. }, metadata) = input {
let span = v.span();
let val = v.into_custom_value()?;
return Ok(PipelineData::value(val.to_base_value(span)?, metadata));
}
if let Some(block_id) = DEPRECATED_REDIRECT_BLOCK_ID.get() {
report_shell_warning(
Some(stack),
engine_state,
&ShellWarning::Deprecated {
dep_type: "Moved Command".into(),
label: "Detecting types of tables is moved to `detect types`.".into(),
span: call.head,
help: Some("Use `update cells {detect type}` instead. In the future this will be a no-op for nushell native values.".into()),
report_mode: ReportMode::EveryUse,
},
);
let Some(block) = engine_state.try_get_block(*block_id) else {
return Err(ShellError::GenericError {
error: "Block ID not found".into(),
msg: format!("Block ID {} not found in this EngineState", block_id.get()),
span: Some(call.head),
help: Some("Make sure the same EngineState for IntoValue::add_deprecated_call was used here.".into()),
inner: vec![],
});
};
let execution_data =
nu_engine::eval_block::<WithoutDebug>(engine_state, stack, block, input)?;
return Ok(execution_data.body);
}
Ok(input)
}
}
impl IntoValue {
// TODO: remove this method after deprecation phase
// This is a major hack to get the `update cell {detect type}` call possible without writing to
// much code that will be thrown away anyway.
pub fn add_deprecated_call(engine_state: &mut EngineState) {
let code = b"update cells {detect type}";
let mut working_set = StateWorkingSet::new(engine_state);
let block = nu_parser::parse(
&mut working_set,
Some("`into value` inner redirect"),
code,
false,
);
debug_assert!(
working_set.parse_errors.is_empty(),
"parsing `update cells {{detect type}}` errored"
);
debug_assert!(
working_set.compile_errors.is_empty(),
"compiling `update cells {{detect type}}` errored"
);
let block_id = working_set.add_block(block);
if engine_state.merge_delta(working_set.delta).is_err() {
log::error!("could not merge delta for deprecated redirect block of `into value`");
return;
}
if DEPRECATED_REDIRECT_BLOCK_ID.set(block_id).is_err() {
log::error!("could not set block id for deprecated redirect block of `into value`");
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/conversions/into/glob.rs | crates/nu-command/src/conversions/into/glob.rs | use nu_cmd_base::input_handler::{CmdArgument, operate};
use nu_engine::command_prelude::*;
struct Arguments {
cell_paths: Option<Vec<CellPath>>,
}
impl CmdArgument for Arguments {
fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> {
self.cell_paths.take()
}
}
#[derive(Clone)]
pub struct IntoGlob;
impl Command for IntoGlob {
fn name(&self) -> &str {
"into glob"
}
fn signature(&self) -> Signature {
Signature::build("into glob")
.input_output_types(vec![
(Type::Glob, Type::Glob),
(Type::String, Type::Glob),
(
Type::List(Box::new(Type::String)),
Type::List(Box::new(Type::Glob)),
),
(Type::table(), Type::table()),
(Type::record(), Type::record()),
])
.allow_variants_without_examples(true) // https://github.com/nushell/nushell/issues/7032
.rest(
"rest",
SyntaxShape::CellPath,
"For a data structure input, convert data at the given cell paths.",
)
.category(Category::Conversions)
}
fn description(&self) -> &str {
"Convert value to glob."
}
fn search_terms(&self) -> Vec<&str> {
vec!["convert", "text"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
glob_helper(engine_state, stack, call, input)
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "convert string to glob",
example: "'1234' | into glob",
result: Some(Value::test_glob("1234")),
},
Example {
description: "convert glob to glob",
example: "'1234' | into glob | into glob",
result: Some(Value::test_glob("1234")),
},
Example {
description: "convert filepath to glob",
example: "ls Cargo.toml | get name | into glob",
result: None,
},
]
}
}
fn glob_helper(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let cell_paths = call.rest(engine_state, stack, 0)?;
let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths);
if let PipelineData::ByteStream(stream, ..) = input {
// TODO: in the future, we may want this to stream out, converting each to bytes
Ok(Value::glob(stream.into_string()?, false, head).into_pipeline_data())
} else {
let args = Arguments { cell_paths };
operate(action, args, input, head, engine_state.signals())
}
}
fn action(input: &Value, _args: &Arguments, span: Span) -> Value {
match input {
Value::String { val, .. } => Value::glob(val.to_string(), false, span),
Value::Glob { .. } => input.clone(),
x => Value::error(
ShellError::CantConvert {
to_type: String::from("glob"),
from_type: x.get_type().to_string(),
span,
help: None,
},
span,
),
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(IntoGlob {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/conversions/into/bool.rs | crates/nu-command/src/conversions/into/bool.rs | use nu_cmd_base::input_handler::{CmdArgument, operate};
use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct IntoBool;
impl Command for IntoBool {
fn name(&self) -> &str {
"into bool"
}
fn signature(&self) -> Signature {
Signature::build("into bool")
.input_output_types(vec![
(Type::Int, Type::Bool),
(Type::Number, Type::Bool),
(Type::String, Type::Bool),
(Type::Bool, Type::Bool),
(Type::Nothing, Type::Bool),
(Type::List(Box::new(Type::Any)), Type::table()),
(Type::table(), Type::table()),
(Type::record(), Type::record()),
])
.switch(
"relaxed",
"Relaxes conversion to also allow null and any strings.",
None,
)
.allow_variants_without_examples(true)
.rest(
"rest",
SyntaxShape::CellPath,
"For a data structure input, convert data at the given cell paths.",
)
.category(Category::Conversions)
}
fn description(&self) -> &str {
"Convert value to boolean."
}
fn search_terms(&self) -> Vec<&str> {
vec!["convert", "boolean", "true", "false", "1", "0"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let relaxed = call
.has_flag(engine_state, stack, "relaxed")
.unwrap_or(false);
into_bool(engine_state, stack, call, input, relaxed)
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Convert value to boolean in table",
example: "[[value]; ['false'] ['1'] [0] [1.0] [true]] | into bool value",
result: Some(Value::test_list(vec![
Value::test_record(record! {
"value" => Value::test_bool(false),
}),
Value::test_record(record! {
"value" => Value::test_bool(true),
}),
Value::test_record(record! {
"value" => Value::test_bool(false),
}),
Value::test_record(record! {
"value" => Value::test_bool(true),
}),
Value::test_record(record! {
"value" => Value::test_bool(true),
}),
])),
},
Example {
description: "Convert bool to boolean",
example: "true | into bool",
result: Some(Value::test_bool(true)),
},
Example {
description: "convert int to boolean",
example: "1 | into bool",
result: Some(Value::test_bool(true)),
},
Example {
description: "convert float to boolean",
example: "0.3 | into bool",
result: Some(Value::test_bool(true)),
},
Example {
description: "convert float string to boolean",
example: "'0.0' | into bool",
result: Some(Value::test_bool(false)),
},
Example {
description: "convert string to boolean",
example: "'true' | into bool",
result: Some(Value::test_bool(true)),
},
Example {
description: "interpret a null as false",
example: "null | into bool --relaxed",
result: Some(Value::test_bool(false)),
},
Example {
description: "interpret any non-false, non-zero string as true",
example: "'something' | into bool --relaxed",
result: Some(Value::test_bool(true)),
},
]
}
}
struct IntoBoolCmdArgument {
cell_paths: Option<Vec<CellPath>>,
relaxed: bool,
}
impl CmdArgument for IntoBoolCmdArgument {
fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> {
self.cell_paths.take()
}
}
fn into_bool(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
relaxed: bool,
) -> Result<PipelineData, ShellError> {
let cell_paths = Some(call.rest(engine_state, stack, 0)?).filter(|v| !v.is_empty());
let args = IntoBoolCmdArgument {
cell_paths,
relaxed,
};
operate(action, args, input, call.head, engine_state.signals())
}
fn strict_string_to_boolean(s: &str, span: Span) -> Result<bool, ShellError> {
match s.trim().to_ascii_lowercase().as_str() {
"true" => Ok(true),
"false" => Ok(false),
o => {
let val = o.parse::<f64>();
match val {
Ok(f) => Ok(f != 0.0),
Err(_) => Err(ShellError::CantConvert {
to_type: "boolean".to_string(),
from_type: "string".to_string(),
span,
help: Some(
r#"the strings "true" and "false" can be converted into a bool"#
.to_string(),
),
}),
}
}
}
}
fn action(input: &Value, args: &IntoBoolCmdArgument, span: Span) -> Value {
let err = || {
Value::error(
ShellError::OnlySupportsThisInputType {
exp_input_type: "bool, int, float or string".into(),
wrong_type: input.get_type().to_string(),
dst_span: span,
src_span: input.span(),
},
span,
)
};
match (input, args.relaxed) {
(Value::Error { .. } | Value::Bool { .. }, _) => input.clone(),
// In strict mode is this an error, while in relaxed this is just `false`
(Value::Nothing { .. }, false) => err(),
(Value::String { val, .. }, false) => match strict_string_to_boolean(val, span) {
Ok(val) => Value::bool(val, span),
Err(error) => Value::error(error, span),
},
_ => match input.coerce_bool() {
Ok(val) => Value::bool(val, span),
Err(_) => err(),
},
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(IntoBool {})
}
#[test]
fn test_strict_handling() {
let span = Span::test_data();
let args = IntoBoolCmdArgument {
cell_paths: vec![].into(),
relaxed: false,
};
assert!(action(&Value::test_nothing(), &args, span).is_error());
assert!(action(&Value::test_string("abc"), &args, span).is_error());
assert!(action(&Value::test_string("true"), &args, span).is_true());
assert!(action(&Value::test_string("FALSE"), &args, span).is_false());
}
#[test]
fn test_relaxed_handling() {
let span = Span::test_data();
let args = IntoBoolCmdArgument {
cell_paths: vec![].into(),
relaxed: true,
};
assert!(action(&Value::test_nothing(), &args, span).is_false());
assert!(action(&Value::test_string("abc"), &args, span).is_true());
assert!(action(&Value::test_string("true"), &args, span).is_true());
assert!(action(&Value::test_string("FALSE"), &args, span).is_false());
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/conversions/into/record.rs | crates/nu-command/src/conversions/into/record.rs | use chrono::{DateTime, Datelike, FixedOffset, Timelike};
use nu_engine::command_prelude::*;
use nu_protocol::format_duration_as_timeperiod;
#[derive(Clone)]
pub struct IntoRecord;
impl Command for IntoRecord {
fn name(&self) -> &str {
"into record"
}
fn signature(&self) -> Signature {
Signature::build("into record")
.input_output_types(vec![
(Type::Date, Type::record()),
(Type::Duration, Type::record()),
(Type::List(Box::new(Type::Any)), Type::record()),
(Type::record(), Type::record()),
])
.category(Category::Conversions)
}
fn description(&self) -> &str {
"Convert value to record."
}
fn search_terms(&self) -> Vec<&str> {
vec!["convert"]
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
into_record(call, input)
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Convert from one row table to record",
example: "[[value]; [false]] | into record",
result: Some(Value::test_record(record! {
"value" => Value::test_bool(false),
})),
},
Example {
description: "Convert from list of records to record",
example: "[{foo: bar} {baz: quux}] | into record",
result: Some(Value::test_record(record! {
"foo" => Value::test_string("bar"),
"baz" => Value::test_string("quux"),
})),
},
Example {
description: "Convert from list of pairs into record",
example: "[[foo bar] [baz quux]] | into record",
result: Some(Value::test_record(record! {
"foo" => Value::test_string("bar"),
"baz" => Value::test_string("quux"),
})),
},
Example {
description: "convert duration to record (weeks max)",
example: "(-500day - 4hr - 5sec) | into record",
result: Some(Value::test_record(record! {
"week" => Value::test_int(71),
"day" => Value::test_int(3),
"hour" => Value::test_int(4),
"second" => Value::test_int(5),
"sign" => Value::test_string("-"),
})),
},
Example {
description: "convert record to record",
example: "{a: 1, b: 2} | into record",
result: Some(Value::test_record(record! {
"a" => Value::test_int(1),
"b" => Value::test_int(2),
})),
},
Example {
description: "convert date to record",
example: "2020-04-12T22:10:57+02:00 | into record",
result: Some(Value::test_record(record! {
"year" => Value::test_int(2020),
"month" => Value::test_int(4),
"day" => Value::test_int(12),
"hour" => Value::test_int(22),
"minute" => Value::test_int(10),
"second" => Value::test_int(57),
"millisecond" => Value::test_int(0),
"microsecond" => Value::test_int(0),
"nanosecond" => Value::test_int(0),
"timezone" => Value::test_string("+02:00"),
})),
},
Example {
description: "convert date components to table columns",
example: "2020-04-12T22:10:57+02:00 | into record | transpose | transpose -r",
result: None,
},
]
}
}
fn into_record(call: &Call, input: PipelineData) -> Result<PipelineData, ShellError> {
let span = input.span().unwrap_or(call.head);
match input {
PipelineData::Value(Value::Date { val, .. }, _) => {
Ok(parse_date_into_record(val, span).into_pipeline_data())
}
PipelineData::Value(Value::Duration { val, .. }, _) => {
Ok(parse_duration_into_record(val, span).into_pipeline_data())
}
PipelineData::Value(Value::List { .. }, _) | PipelineData::ListStream(..) => {
let mut record = Record::new();
let metadata = input.metadata();
enum ExpectedType {
Record,
Pair,
}
let mut expected_type = None;
for item in input.into_iter() {
let span = item.span();
match item {
Value::Record { val, .. }
if matches!(expected_type, None | Some(ExpectedType::Record)) =>
{
// Don't use .extend() unless that gets changed to check for duplicate keys
for (key, val) in val.into_owned() {
record.insert(key, val);
}
expected_type = Some(ExpectedType::Record);
}
Value::List { mut vals, .. }
if matches!(expected_type, None | Some(ExpectedType::Pair)) =>
{
if vals.len() == 2 {
let (val, key) = vals.pop().zip(vals.pop()).expect("length is < 2");
record.insert(key.coerce_into_string()?, val);
} else {
return Err(ShellError::IncorrectValue {
msg: format!(
"expected inner list with two elements, but found {} element(s)",
vals.len()
),
val_span: span,
call_span: call.head,
});
}
expected_type = Some(ExpectedType::Pair);
}
Value::Nothing { .. } => {}
Value::Error { error, .. } => return Err(*error),
_ => {
return Err(ShellError::TypeMismatch {
err_message: format!(
"expected {}, found {} (while building record from list)",
match expected_type {
Some(ExpectedType::Record) => "record",
Some(ExpectedType::Pair) => "list with two elements",
None => "record or list with two elements",
},
item.get_type(),
),
span,
});
}
}
}
Ok(Value::record(record, span).into_pipeline_data_with_metadata(metadata))
}
PipelineData::Value(Value::Record { .. }, _) => Ok(input),
PipelineData::Value(Value::Error { error, .. }, _) => Err(*error),
other => Err(ShellError::TypeMismatch {
err_message: format!("Can't convert {} to record", other.get_type()),
span,
}),
}
}
fn parse_date_into_record(date: DateTime<FixedOffset>, span: Span) -> Value {
Value::record(
record! {
"year" => Value::int(date.year() as i64, span),
"month" => Value::int(date.month() as i64, span),
"day" => Value::int(date.day() as i64, span),
"hour" => Value::int(date.hour() as i64, span),
"minute" => Value::int(date.minute() as i64, span),
"second" => Value::int(date.second() as i64, span),
"millisecond" => Value::int(date.timestamp_subsec_millis() as i64, span),
"microsecond" => Value::int((date.nanosecond() / 1_000 % 1_000) as i64, span),
"nanosecond" => Value::int((date.nanosecond() % 1_000) as i64, span),
"timezone" => Value::string(date.offset().to_string(), span),
},
span,
)
}
fn parse_duration_into_record(duration: i64, span: Span) -> Value {
let (sign, periods) = format_duration_as_timeperiod(duration);
let mut record = Record::new();
for p in periods {
let num_with_unit = p.to_text().to_string();
let split = num_with_unit.split(' ').collect::<Vec<&str>>();
record.push(
match split[1] {
"ns" => "nanosecond",
"µs" => "microsecond",
"ms" => "millisecond",
"sec" => "second",
"min" => "minute",
"hr" => "hour",
"day" => "day",
"wk" => "week",
_ => "unknown",
},
Value::int(split[0].parse().unwrap_or(0), span),
);
}
record.push(
"sign",
Value::string(if sign == -1 { "-" } else { "+" }, span),
);
Value::record(record, span)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(IntoRecord {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/conversions/into/mod.rs | crates/nu-command/src/conversions/into/mod.rs | mod binary;
mod bool;
mod cell_path;
mod command;
mod datetime;
mod duration;
mod filesize;
mod float;
mod glob;
mod int;
mod record;
mod string;
mod value;
pub use binary::IntoBinary;
pub use bool::IntoBool;
pub use cell_path::IntoCellPath;
pub use command::Into;
pub use datetime::IntoDatetime;
pub use duration::IntoDuration;
pub use filesize::IntoFilesize;
pub use float::IntoFloat;
pub use glob::IntoGlob;
pub use int::IntoInt;
pub use record::IntoRecord;
pub use string::IntoString;
pub use value::IntoValue;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/conversions/into/binary.rs | crates/nu-command/src/conversions/into/binary.rs | use nu_cmd_base::input_handler::{CmdArgument, operate};
use nu_engine::command_prelude::*;
struct Arguments {
cell_paths: Option<Vec<CellPath>>,
compact: bool,
little_endian: bool,
}
impl CmdArgument for Arguments {
fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> {
self.cell_paths.take()
}
}
#[derive(Clone)]
pub struct IntoBinary;
impl Command for IntoBinary {
fn name(&self) -> &str {
"into binary"
}
fn signature(&self) -> Signature {
Signature::build("into binary")
.input_output_types(vec![
(Type::Binary, Type::Binary),
(Type::Int, Type::Binary),
(Type::Number, Type::Binary),
(Type::String, Type::Binary),
(Type::Bool, Type::Binary),
(Type::Filesize, Type::Binary),
(Type::Date, Type::Binary),
(Type::table(), Type::table()),
(Type::record(), Type::record()),
])
.allow_variants_without_examples(true) // TODO: supply exhaustive examples
.switch("compact", "output without padding zeros", Some('c'))
.named(
"endian",
SyntaxShape::String,
"byte encode endian. Does not affect string, date or binary. In containers, only individual elements are affected. Available options: native(default), little, big",
Some('e'),
)
.rest(
"rest",
SyntaxShape::CellPath,
"For a data structure input, convert data at the given cell paths.",
)
.category(Category::Conversions)
}
fn description(&self) -> &str {
"Convert value to a binary primitive."
}
fn search_terms(&self) -> Vec<&str> {
vec!["convert", "bytes"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
into_binary(engine_state, stack, call, input)
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "convert string to a nushell binary primitive",
example: "'This is a string that is exactly 52 characters long.' | into binary",
result: Some(Value::binary(
"This is a string that is exactly 52 characters long."
.to_string()
.as_bytes()
.to_vec(),
Span::test_data(),
)),
},
Example {
description: "convert a number to a nushell binary primitive",
example: "1 | into binary",
result: Some(Value::binary(
i64::from(1).to_ne_bytes().to_vec(),
Span::test_data(),
)),
},
Example {
description: "convert a number to a nushell binary primitive (big endian)",
example: "258 | into binary --endian big",
result: Some(Value::binary(
i64::from(258).to_be_bytes().to_vec(),
Span::test_data(),
)),
},
Example {
description: "convert a number to a nushell binary primitive (little endian)",
example: "258 | into binary --endian little",
result: Some(Value::binary(
i64::from(258).to_le_bytes().to_vec(),
Span::test_data(),
)),
},
Example {
description: "convert a boolean to a nushell binary primitive",
example: "true | into binary",
result: Some(Value::binary(
i64::from(1).to_ne_bytes().to_vec(),
Span::test_data(),
)),
},
Example {
description: "convert a filesize to a nushell binary primitive",
example: "ls | where name == LICENSE | get size | into binary",
result: None,
},
Example {
description: "convert a filepath to a nushell binary primitive",
example: "ls | where name == LICENSE | get name | path expand | into binary",
result: None,
},
Example {
description: "convert a float to a nushell binary primitive",
example: "1.234 | into binary",
result: Some(Value::binary(
1.234f64.to_ne_bytes().to_vec(),
Span::test_data(),
)),
},
Example {
description: "convert an int to a nushell binary primitive with compact enabled",
example: "10 | into binary --compact",
result: Some(Value::binary(vec![10], Span::test_data())),
},
]
}
}
fn into_binary(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let cell_paths = call.rest(engine_state, stack, 0)?;
let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths);
if let PipelineData::ByteStream(stream, metadata) = input {
// Just set the type - that should be good enough
Ok(PipelineData::byte_stream(
stream.with_type(ByteStreamType::Binary),
metadata,
))
} else {
let endian = call.get_flag::<Spanned<String>>(engine_state, stack, "endian")?;
let little_endian = if let Some(endian) = endian {
match endian.item.as_str() {
"native" => cfg!(target_endian = "little"),
"little" => true,
"big" => false,
_ => {
return Err(ShellError::TypeMismatch {
err_message: "Endian must be one of native, little, big".to_string(),
span: endian.span,
});
}
}
} else {
cfg!(target_endian = "little")
};
let args = Arguments {
cell_paths,
compact: call.has_flag(engine_state, stack, "compact")?,
little_endian,
};
operate(action, args, input, head, engine_state.signals())
}
}
fn action(input: &Value, args: &Arguments, span: Span) -> Value {
let value = match input {
Value::Binary { .. } => input.clone(),
Value::Int { val, .. } => Value::binary(
if args.little_endian {
val.to_le_bytes()
} else {
val.to_be_bytes()
}
.to_vec(),
span,
),
Value::Float { val, .. } => Value::binary(
if args.little_endian {
val.to_le_bytes()
} else {
val.to_be_bytes()
}
.to_vec(),
span,
),
Value::Filesize { val, .. } => Value::binary(
if args.little_endian {
val.get().to_le_bytes()
} else {
val.get().to_be_bytes()
}
.to_vec(),
span,
),
Value::String { val, .. } => Value::binary(val.as_bytes().to_vec(), span),
Value::Bool { val, .. } => Value::binary(
{
let as_int = i64::from(*val);
if args.little_endian {
as_int.to_le_bytes()
} else {
as_int.to_be_bytes()
}
.to_vec()
},
span,
),
Value::Duration { val, .. } => Value::binary(
if args.little_endian {
val.to_le_bytes()
} else {
val.to_be_bytes()
}
.to_vec(),
span,
),
Value::Date { val, .. } => {
Value::binary(val.format("%c").to_string().as_bytes().to_vec(), span)
}
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => input.clone(),
other => Value::error(
ShellError::OnlySupportsThisInputType {
exp_input_type: "int, float, filesize, string, date, duration, binary, or bool"
.into(),
wrong_type: other.get_type().to_string(),
dst_span: span,
src_span: other.span(),
},
span,
),
};
if args.compact {
let val_span = value.span();
if let Value::Binary { val, .. } = value {
let val = if args.little_endian {
match val.iter().rposition(|&x| x != 0) {
Some(idx) => &val[..idx + 1],
// all 0s should just return a single 0 byte
None => &[0],
}
} else {
match val.iter().position(|&x| x != 0) {
Some(idx) => &val[idx..],
None => &[0],
}
};
Value::binary(val.to_vec(), val_span)
} else {
value
}
} else {
value
}
}
#[cfg(test)]
mod test {
use rstest::rstest;
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(IntoBinary {})
}
#[rstest]
#[case(vec![10], vec![10], vec![10])]
#[case(vec![10, 0, 0], vec![10], vec![10, 0, 0])]
#[case(vec![0, 0, 10], vec![0, 0, 10], vec![10])]
#[case(vec![0, 10, 0, 0], vec![0, 10], vec![10, 0, 0])]
fn test_compact(#[case] input: Vec<u8>, #[case] little: Vec<u8>, #[case] big: Vec<u8>) {
let s = Value::test_binary(input);
let actual = action(
&s,
&Arguments {
cell_paths: None,
compact: true,
little_endian: cfg!(target_endian = "little"),
},
Span::test_data(),
);
if cfg!(target_endian = "little") {
assert_eq!(actual, Value::test_binary(little));
} else {
assert_eq!(actual, Value::test_binary(big));
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/conversions/into/float.rs | crates/nu-command/src/conversions/into/float.rs | use nu_cmd_base::input_handler::{CellPathOnlyArgs, operate};
use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct IntoFloat;
impl Command for IntoFloat {
fn name(&self) -> &str {
"into float"
}
fn signature(&self) -> Signature {
Signature::build("into float")
.input_output_types(vec![
(Type::Int, Type::Float),
(Type::String, Type::Float),
(Type::Bool, Type::Float),
(Type::Float, Type::Float),
(Type::table(), Type::table()),
(Type::record(), Type::record()),
(
Type::List(Box::new(Type::Any)),
Type::List(Box::new(Type::Float)),
),
])
.rest(
"rest",
SyntaxShape::CellPath,
"For a data structure input, convert data at the given cell paths.",
)
.allow_variants_without_examples(true)
.category(Category::Conversions)
}
fn description(&self) -> &str {
"Convert data into floating point number."
}
fn search_terms(&self) -> Vec<&str> {
vec!["convert", "number", "floating", "decimal"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let cell_paths: Vec<CellPath> = call.rest(engine_state, stack, 0)?;
let args = CellPathOnlyArgs::from(cell_paths);
operate(action, args, input, call.head, engine_state.signals())
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Convert string to float in table",
example: "[[num]; ['5.01']] | into float num",
result: Some(Value::test_list(vec![Value::test_record(record! {
"num" => Value::test_float(5.01),
})])),
},
Example {
description: "Convert string to floating point number",
example: "'1.345' | into float",
result: Some(Value::test_float(1.345)),
},
Example {
description: "Coerce list of ints and floats to float",
example: "[4 -5.9] | into float",
result: Some(Value::test_list(vec![
Value::test_float(4.0),
Value::test_float(-5.9),
])),
},
Example {
description: "Convert boolean to float",
example: "true | into float",
result: Some(Value::test_float(1.0)),
},
]
}
}
fn action(input: &Value, _args: &CellPathOnlyArgs, head: Span) -> Value {
let span = input.span();
match input {
Value::Float { .. } => input.clone(),
Value::String { val: s, .. } => {
let other = s.trim();
match other.parse::<f64>() {
Ok(x) => Value::float(x, head),
Err(reason) => Value::error(
ShellError::CantConvert {
to_type: "float".to_string(),
from_type: reason.to_string(),
span,
help: None,
},
span,
),
}
}
Value::Int { val: v, .. } => Value::float(*v as f64, span),
Value::Bool { val: b, .. } => Value::float(
match b {
true => 1.0,
false => 0.0,
},
span,
),
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => input.clone(),
other => Value::error(
ShellError::OnlySupportsThisInputType {
exp_input_type: "string, int or bool".into(),
wrong_type: other.get_type().to_string(),
dst_span: head,
src_span: other.span(),
},
head,
),
}
}
#[cfg(test)]
mod tests {
use super::*;
use nu_protocol::Type::Error;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(IntoFloat {})
}
#[test]
#[allow(clippy::approx_constant)]
fn string_to_float() {
let word = Value::test_string("3.1415");
let expected = Value::test_float(3.1415);
let actual = action(&word, &CellPathOnlyArgs::from(vec![]), Span::test_data());
assert_eq!(actual, expected);
}
#[test]
fn communicates_parsing_error_given_an_invalid_floatlike_string() {
let invalid_str = Value::test_string("11.6anra");
let actual = action(
&invalid_str,
&CellPathOnlyArgs::from(vec![]),
Span::test_data(),
);
assert_eq!(actual.get_type(), Error);
}
#[test]
fn int_to_float() {
let input_int = Value::test_int(10);
let expected = Value::test_float(10.0);
let actual = action(
&input_int,
&CellPathOnlyArgs::from(vec![]),
Span::test_data(),
);
assert_eq!(actual, expected);
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/conversions/into/cell_path.rs | crates/nu-command/src/conversions/into/cell_path.rs | use nu_engine::command_prelude::*;
use nu_protocol::{ast::PathMember, casing::Casing};
#[derive(Clone)]
pub struct IntoCellPath;
impl Command for IntoCellPath {
fn name(&self) -> &str {
"into cell-path"
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build("into cell-path")
.input_output_types(vec![
(Type::CellPath, Type::CellPath),
(Type::Int, Type::CellPath),
(Type::List(Box::new(Type::Any)), Type::CellPath),
(
Type::List(Box::new(Type::Record(
[
("value".into(), Type::Any),
("optional".into(), Type::Bool),
("insensitive".into(), Type::Bool),
]
.into(),
))),
Type::CellPath,
),
])
.category(Category::Conversions)
.allow_variants_without_examples(true)
}
fn description(&self) -> &str {
"Convert value to a cell-path."
}
fn search_terms(&self) -> Vec<&str> {
vec!["convert"]
}
fn extra_description(&self) -> &str {
"Converting a string directly into a cell path is intentionally not supported."
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
into_cell_path(call, input)
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Convert integer into cell path",
example: "5 | into cell-path",
result: Some(Value::test_cell_path(CellPath {
members: vec![PathMember::test_int(5, false)],
})),
},
Example {
description: "Convert cell path into cell path",
example: "5 | into cell-path | into cell-path",
result: Some(Value::test_cell_path(CellPath {
members: vec![PathMember::test_int(5, false)],
})),
},
Example {
description: "Convert string into cell path",
example: "'some.path' | split row '.' | into cell-path",
result: Some(Value::test_cell_path(CellPath {
members: vec![
PathMember::test_string("some".into(), false, Casing::Sensitive),
PathMember::test_string("path".into(), false, Casing::Sensitive),
],
})),
},
Example {
description: "Convert list into cell path",
example: "[5 c 7 h] | into cell-path",
result: Some(Value::test_cell_path(CellPath {
members: vec![
PathMember::test_int(5, false),
PathMember::test_string("c".into(), false, Casing::Sensitive),
PathMember::test_int(7, false),
PathMember::test_string("h".into(), false, Casing::Sensitive),
],
})),
},
Example {
description: "Convert table into cell path",
example: "[[value, optional, insensitive]; [5 true false] [c false false] [d false true]] | into cell-path",
result: Some(Value::test_cell_path(CellPath {
members: vec![
PathMember::test_int(5, true),
PathMember::test_string("c".into(), false, Casing::Sensitive),
PathMember::test_string("d".into(), false, Casing::Insensitive),
],
})),
},
]
}
}
fn into_cell_path(call: &Call, input: PipelineData) -> Result<PipelineData, ShellError> {
let head = call.head;
match input {
PipelineData::Value(value, _) => Ok(value_to_cell_path(value, head)?.into_pipeline_data()),
PipelineData::ListStream(stream, ..) => {
let list: Vec<_> = stream.into_iter().collect();
Ok(list_to_cell_path(&list, head)?.into_pipeline_data())
}
PipelineData::ByteStream(stream, ..) => Err(ShellError::OnlySupportsThisInputType {
exp_input_type: "list, int".into(),
wrong_type: stream.type_().describe().into(),
dst_span: head,
src_span: stream.span(),
}),
PipelineData::Empty => Err(ShellError::PipelineEmpty { dst_span: head }),
}
}
fn int_to_cell_path(val: i64, span: Span) -> Value {
let member = match int_to_path_member(val, span) {
Ok(m) => m,
Err(e) => {
return Value::error(e, span);
}
};
let path = CellPath {
members: vec![member],
};
Value::cell_path(path, span)
}
fn int_to_path_member(val: i64, span: Span) -> Result<PathMember, ShellError> {
let Ok(val) = val.try_into() else {
return Err(ShellError::NeedsPositiveValue { span });
};
Ok(PathMember::int(val, false, span))
}
fn list_to_cell_path(vals: &[Value], span: Span) -> Result<Value, ShellError> {
let mut members = vec![];
for val in vals {
members.push(value_to_path_member(val, span)?);
}
let path = CellPath { members };
Ok(Value::cell_path(path, span))
}
fn record_to_path_member(
record: &Record,
val_span: Span,
span: Span,
) -> Result<PathMember, ShellError> {
let Some(value) = record.get("value") else {
return Err(ShellError::CantFindColumn {
col_name: "value".into(),
span: Some(val_span),
src_span: span,
});
};
let mut member = value_to_path_member(value, span)?;
if let Some(optional) = record.get("optional")
&& optional.as_bool()?
{
member.make_optional();
};
if let Some(insensitive) = record.get("insensitive")
&& insensitive.as_bool()?
{
member.make_insensitive();
};
Ok(member)
}
fn value_to_cell_path(value: Value, span: Span) -> Result<Value, ShellError> {
match value {
Value::CellPath { .. } => Ok(value),
Value::Int { val, .. } => Ok(int_to_cell_path(val, span)),
Value::List { vals, .. } => list_to_cell_path(&vals, span),
other => Err(ShellError::OnlySupportsThisInputType {
exp_input_type: "int, list".into(),
wrong_type: other.get_type().to_string(),
dst_span: span,
src_span: other.span(),
}),
}
}
fn value_to_path_member(val: &Value, span: Span) -> Result<PathMember, ShellError> {
let val_span = val.span();
let member = match val {
Value::Int { val, .. } => int_to_path_member(*val, val_span)?,
Value::String { val, .. } => {
PathMember::string(val.into(), false, Casing::Sensitive, val_span)
}
Value::Record { val, .. } => record_to_path_member(val, val_span, span)?,
other => {
return Err(ShellError::CantConvert {
to_type: "int or string".to_string(),
from_type: other.get_type().to_string(),
span: val.span(),
help: None,
});
}
};
Ok(member)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(IntoCellPath {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/conversions/into/int.rs | crates/nu-command/src/conversions/into/int.rs | use chrono::{FixedOffset, TimeZone};
use nu_cmd_base::input_handler::{CmdArgument, operate};
use nu_engine::command_prelude::*;
use nu_utils::get_system_locale;
struct Arguments {
radix: u32,
cell_paths: Option<Vec<CellPath>>,
signed: bool,
little_endian: bool,
}
impl CmdArgument for Arguments {
fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> {
self.cell_paths.take()
}
}
#[derive(Clone)]
pub struct IntoInt;
impl Command for IntoInt {
fn name(&self) -> &str {
"into int"
}
fn signature(&self) -> Signature {
Signature::build("into int")
.input_output_types(vec![
(Type::String, Type::Int),
(Type::Number, Type::Int),
(Type::Bool, Type::Int),
// Unix timestamp in nanoseconds
(Type::Date, Type::Int),
(Type::Duration, Type::Int),
(Type::Filesize, Type::Int),
(Type::Binary, Type::Int),
(Type::table(), Type::table()),
(Type::record(), Type::record()),
(
Type::List(Box::new(Type::String)),
Type::List(Box::new(Type::Int)),
),
(
Type::List(Box::new(Type::Number)),
Type::List(Box::new(Type::Int)),
),
(
Type::List(Box::new(Type::Bool)),
Type::List(Box::new(Type::Int)),
),
(
Type::List(Box::new(Type::Date)),
Type::List(Box::new(Type::Int)),
),
(
Type::List(Box::new(Type::Duration)),
Type::List(Box::new(Type::Int)),
),
(
Type::List(Box::new(Type::Filesize)),
Type::List(Box::new(Type::Int)),
),
// Relaxed case to support heterogeneous lists
(
Type::List(Box::new(Type::Any)),
Type::List(Box::new(Type::Int)),
),
])
.allow_variants_without_examples(true)
.named("radix", SyntaxShape::Number, "radix of integer", Some('r'))
.param(
Flag::new("endian")
.short('e')
.arg(SyntaxShape::String)
.desc("byte encode endian, available options: native(default), little, big")
.completion(Completion::new_list(&["native", "little", "big"])),
)
.switch(
"signed",
"always treat input number as a signed number",
Some('s'),
)
.rest(
"rest",
SyntaxShape::CellPath,
"For a data structure input, convert data at the given cell paths.",
)
.category(Category::Conversions)
}
fn description(&self) -> &str {
"Convert value to integer."
}
fn search_terms(&self) -> Vec<&str> {
vec!["convert", "number", "natural"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let cell_paths = call.rest(engine_state, stack, 0)?;
let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths);
let radix = call.get_flag::<Value>(engine_state, stack, "radix")?;
let radix: u32 = match radix {
Some(val) => {
let span = val.span();
match val {
Value::Int { val, .. } => {
if !(2..=36).contains(&val) {
return Err(ShellError::TypeMismatch {
err_message: "Radix must lie in the range [2, 36]".to_string(),
span,
});
}
val as u32
}
_ => 10,
}
}
None => 10,
};
let endian = call.get_flag::<Value>(engine_state, stack, "endian")?;
let little_endian = match endian {
Some(val) => {
let span = val.span();
match val {
Value::String { val, .. } => match val.as_str() {
"native" => cfg!(target_endian = "little"),
"little" => true,
"big" => false,
_ => {
return Err(ShellError::TypeMismatch {
err_message: "Endian must be one of native, little, big"
.to_string(),
span,
});
}
},
_ => false,
}
}
None => cfg!(target_endian = "little"),
};
let signed = call.has_flag(engine_state, stack, "signed")?;
let args = Arguments {
radix,
little_endian,
signed,
cell_paths,
};
operate(action, args, input, call.head, engine_state.signals())
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Convert string to int in table",
example: "[[num]; ['-5'] [4] [1.5]] | into int num",
result: None,
},
Example {
description: "Convert string to int",
example: "'2' | into int",
result: Some(Value::test_int(2)),
},
Example {
description: "Convert float to int",
example: "5.9 | into int",
result: Some(Value::test_int(5)),
},
Example {
description: "Convert decimal string to int",
example: "'5.9' | into int",
result: Some(Value::test_int(5)),
},
Example {
description: "Convert file size to int",
example: "4KB | into int",
result: Some(Value::test_int(4000)),
},
Example {
description: "Convert bool to int",
example: "[false, true] | into int",
result: Some(Value::list(
vec![Value::test_int(0), Value::test_int(1)],
Span::test_data(),
)),
},
Example {
description: "Convert date to int (Unix nanosecond timestamp)",
example: "1983-04-13T12:09:14.123456789-05:00 | into int",
result: Some(Value::test_int(419101754123456789)),
},
Example {
description: "Convert to int from binary data (radix: 2)",
example: "'1101' | into int --radix 2",
result: Some(Value::test_int(13)),
},
Example {
description: "Convert to int from hex",
example: "'FF' | into int --radix 16",
result: Some(Value::test_int(255)),
},
Example {
description: "Convert octal string to int",
example: "'0o10132' | into int",
result: Some(Value::test_int(4186)),
},
Example {
description: "Convert 0 padded string to int",
example: "'0010132' | into int",
result: Some(Value::test_int(10132)),
},
Example {
description: "Convert 0 padded string to int with radix 8",
example: "'0010132' | into int --radix 8",
result: Some(Value::test_int(4186)),
},
Example {
description: "Convert binary value to int",
example: "0x[10] | into int",
result: Some(Value::test_int(16)),
},
Example {
description: "Convert binary value to signed int",
example: "0x[a0] | into int --signed",
result: Some(Value::test_int(-96)),
},
]
}
}
fn action(input: &Value, args: &Arguments, head: Span) -> Value {
let radix = args.radix;
let signed = args.signed;
let little_endian = args.little_endian;
let val_span = input.span();
match input {
Value::Int { val: _, .. } => {
if radix == 10 {
input.clone()
} else {
convert_int(input, head, radix)
}
}
Value::Filesize { val, .. } => Value::int(val.get(), head),
Value::Float { val, .. } => Value::int(
{
if radix == 10 {
*val as i64
} else {
match convert_int(&Value::int(*val as i64, head), head, radix).as_int() {
Ok(v) => v,
_ => {
return Value::error(
ShellError::CantConvert {
to_type: "float".to_string(),
from_type: "int".to_string(),
span: head,
help: None,
},
head,
);
}
}
}
},
head,
),
Value::String { val, .. } => {
if radix == 10 {
match int_from_string(val, head) {
Ok(val) => Value::int(val, head),
Err(error) => Value::error(error, head),
}
} else {
convert_int(input, head, radix)
}
}
Value::Bool { val, .. } => {
if *val {
Value::int(1, head)
} else {
Value::int(0, head)
}
}
Value::Date { val, .. } => {
if val
< &FixedOffset::east_opt(0)
.expect("constant")
.with_ymd_and_hms(1677, 9, 21, 0, 12, 44)
.unwrap()
|| val
> &FixedOffset::east_opt(0)
.expect("constant")
.with_ymd_and_hms(2262, 4, 11, 23, 47, 16)
.unwrap()
{
Value::error (
ShellError::IncorrectValue {
msg: "DateTime out of range for timestamp: 1677-09-21T00:12:43Z to 2262-04-11T23:47:16".to_string(),
val_span,
call_span: head,
},
head,
)
} else {
Value::int(val.timestamp_nanos_opt().unwrap_or_default(), head)
}
}
Value::Duration { val, .. } => Value::int(*val, head),
Value::Binary { val, .. } => {
use byteorder::{BigEndian, ByteOrder, LittleEndian};
let mut val = val.to_vec();
let size = val.len();
if size == 0 {
return Value::int(0, head);
}
if size > 8 {
return Value::error(
ShellError::IncorrectValue {
msg: format!("binary input is too large to convert to int ({size} bytes)"),
val_span,
call_span: head,
},
head,
);
}
match (little_endian, signed) {
(true, true) => Value::int(LittleEndian::read_int(&val, size), head),
(false, true) => Value::int(BigEndian::read_int(&val, size), head),
(true, false) => {
while val.len() < 8 {
val.push(0);
}
val.resize(8, 0);
Value::int(LittleEndian::read_i64(&val), head)
}
(false, false) => {
while val.len() < 8 {
val.insert(0, 0);
}
val.resize(8, 0);
Value::int(BigEndian::read_i64(&val), head)
}
}
}
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => input.clone(),
other => Value::error(
ShellError::OnlySupportsThisInputType {
exp_input_type: "int, float, filesize, date, string, binary, duration, or bool"
.into(),
wrong_type: other.get_type().to_string(),
dst_span: head,
src_span: other.span(),
},
head,
),
}
}
fn convert_int(input: &Value, head: Span, radix: u32) -> Value {
let i = match input {
Value::Int { val, .. } => val.to_string(),
Value::String { val, .. } => {
let val = val.trim();
if val.starts_with("0x") // hex
|| val.starts_with("0b") // binary
|| val.starts_with("0o")
// octal
{
match int_from_string(val, head) {
Ok(x) => return Value::int(x, head),
Err(e) => return Value::error(e, head),
}
} else if val.starts_with("00") {
// It's a padded string
match i64::from_str_radix(val, radix) {
Ok(n) => return Value::int(n, head),
Err(e) => {
return Value::error(
ShellError::CantConvert {
to_type: "string".to_string(),
from_type: "int".to_string(),
span: head,
help: Some(e.to_string()),
},
head,
);
}
}
}
val.to_string()
}
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => return input.clone(),
other => {
return Value::error(
ShellError::OnlySupportsThisInputType {
exp_input_type: "string and int".into(),
wrong_type: other.get_type().to_string(),
dst_span: head,
src_span: other.span(),
},
head,
);
}
};
match i64::from_str_radix(i.trim(), radix) {
Ok(n) => Value::int(n, head),
Err(_reason) => Value::error(
ShellError::CantConvert {
to_type: "string".to_string(),
from_type: "int".to_string(),
span: head,
help: None,
},
head,
),
}
}
fn int_from_string(a_string: &str, span: Span) -> Result<i64, ShellError> {
// Get the Locale so we know what the thousands separator is
let locale = get_system_locale();
// Now that we know the locale, get the thousands separator and remove it
// so strings like 1,123,456 can be parsed as 1123456
let no_comma_string = a_string.replace(locale.separator(), "");
let trimmed = no_comma_string.trim();
match trimmed {
b if b.starts_with("0b") => {
let num = match i64::from_str_radix(b.trim_start_matches("0b"), 2) {
Ok(n) => n,
Err(_reason) => {
return Err(ShellError::CantConvert {
to_type: "int".to_string(),
from_type: "string".to_string(),
span,
help: Some(r#"digits following "0b" can only be 0 or 1"#.to_string()),
});
}
};
Ok(num)
}
h if h.starts_with("0x") => {
let num =
match i64::from_str_radix(h.trim_start_matches("0x"), 16) {
Ok(n) => n,
Err(_reason) => return Err(ShellError::CantConvert {
to_type: "int".to_string(),
from_type: "string".to_string(),
span,
help: Some(
r#"hexadecimal digits following "0x" should be in 0-9, a-f, or A-F"#
.to_string(),
),
}),
};
Ok(num)
}
o if o.starts_with("0o") => {
let num = match i64::from_str_radix(o.trim_start_matches("0o"), 8) {
Ok(n) => n,
Err(_reason) => {
return Err(ShellError::CantConvert {
to_type: "int".to_string(),
from_type: "string".to_string(),
span,
help: Some(r#"octal digits following "0o" should be in 0-7"#.to_string()),
});
}
};
Ok(num)
}
_ => match trimmed.parse::<i64>() {
Ok(n) => Ok(n),
Err(_) => match a_string.parse::<f64>() {
Ok(f) => Ok(f as i64),
_ => Err(ShellError::CantConvert {
to_type: "int".to_string(),
from_type: "string".to_string(),
span,
help: Some(format!(
r#"string "{trimmed}" does not represent a valid integer"#
)),
}),
},
},
}
}
#[cfg(test)]
mod test {
use chrono::{DateTime, FixedOffset};
use rstest::rstest;
use super::Value;
use super::*;
use nu_protocol::Type::Error;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(IntoInt {})
}
#[test]
fn turns_to_integer() {
let word = Value::test_string("10");
let expected = Value::test_int(10);
let actual = action(
&word,
&Arguments {
radix: 10,
cell_paths: None,
signed: false,
little_endian: false,
},
Span::test_data(),
);
assert_eq!(actual, expected);
}
#[test]
fn turns_binary_to_integer() {
let s = Value::test_string("0b101");
let actual = action(
&s,
&Arguments {
radix: 10,
cell_paths: None,
signed: false,
little_endian: false,
},
Span::test_data(),
);
assert_eq!(actual, Value::test_int(5));
}
#[test]
fn turns_hex_to_integer() {
let s = Value::test_string("0xFF");
let actual = action(
&s,
&Arguments {
radix: 16,
cell_paths: None,
signed: false,
little_endian: false,
},
Span::test_data(),
);
assert_eq!(actual, Value::test_int(255));
}
#[test]
fn communicates_parsing_error_given_an_invalid_integerlike_string() {
let integer_str = Value::test_string("36anra");
let actual = action(
&integer_str,
&Arguments {
radix: 10,
cell_paths: None,
signed: false,
little_endian: false,
},
Span::test_data(),
);
assert_eq!(actual.get_type(), Error)
}
#[rstest]
#[case("2262-04-11T23:47:16+00:00", 0x7fff_ffff_ffff_ffff)]
#[case("1970-01-01T00:00:00+00:00", 0)]
#[case("1677-09-21T00:12:44+00:00", -0x7fff_ffff_ffff_ffff)]
fn datetime_to_int_values_that_work(
#[case] dt_in: DateTime<FixedOffset>,
#[case] int_expected: i64,
) {
let s = Value::test_date(dt_in);
let actual = action(
&s,
&Arguments {
radix: 10,
cell_paths: None,
signed: false,
little_endian: false,
},
Span::test_data(),
);
// ignore fractional seconds -- I don't want to hard code test values that might vary due to leap nanoseconds.
let exp_truncated = (int_expected / 1_000_000_000) * 1_000_000_000;
assert_eq!(actual, Value::test_int(exp_truncated));
}
#[rstest]
#[case("2262-04-11T23:47:17+00:00", "DateTime out of range for timestamp")]
#[case("1677-09-21T00:12:43+00:00", "DateTime out of range for timestamp")]
fn datetime_to_int_values_that_fail(
#[case] dt_in: DateTime<FixedOffset>,
#[case] err_expected: &str,
) {
let s = Value::test_date(dt_in);
let actual = action(
&s,
&Arguments {
radix: 10,
cell_paths: None,
signed: false,
little_endian: false,
},
Span::test_data(),
);
if let Value::Error { error, .. } = actual {
if let ShellError::IncorrectValue { msg: e, .. } = *error {
assert!(
e.contains(err_expected),
"{e:?} doesn't contain {err_expected}"
);
} else {
panic!("Unexpected error variant {error:?}")
}
} else {
panic!("Unexpected actual value {actual:?}")
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/conversions/into/duration.rs | crates/nu-command/src/conversions/into/duration.rs | use std::str::FromStr;
use nu_cmd_base::input_handler::{CmdArgument, operate};
use nu_engine::command_prelude::*;
use nu_parser::{DURATION_UNIT_GROUPS, parse_unit_value};
use nu_protocol::{SUPPORTED_DURATION_UNITS, Unit, ast::Expr};
const NS_PER_US: i64 = 1_000;
const NS_PER_MS: i64 = 1_000_000;
const NS_PER_SEC: i64 = 1_000_000_000;
const NS_PER_MINUTE: i64 = 60 * NS_PER_SEC;
const NS_PER_HOUR: i64 = 60 * NS_PER_MINUTE;
const NS_PER_DAY: i64 = 24 * NS_PER_HOUR;
const NS_PER_WEEK: i64 = 7 * NS_PER_DAY;
const ALLOWED_COLUMNS: [&str; 9] = [
"week",
"day",
"hour",
"minute",
"second",
"millisecond",
"microsecond",
"nanosecond",
"sign",
];
const ALLOWED_SIGNS: [&str; 2] = ["+", "-"];
#[derive(Clone, Debug)]
struct Arguments {
unit: Option<Spanned<Unit>>,
cell_paths: Option<Vec<CellPath>>,
}
impl CmdArgument for Arguments {
fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> {
self.cell_paths.take()
}
}
#[derive(Clone)]
pub struct IntoDuration;
impl Command for IntoDuration {
fn name(&self) -> &str {
"into duration"
}
fn signature(&self) -> Signature {
Signature::build("into duration")
.input_output_types(vec![
(Type::Int, Type::Duration),
(Type::Float, Type::Duration),
(Type::String, Type::Duration),
(Type::Duration, Type::Duration),
(Type::record(), Type::record()),
(Type::record(), Type::Duration),
(Type::table(), Type::table()),
])
.allow_variants_without_examples(true)
.param(
Flag::new("unit")
.short('u')
.arg(SyntaxShape::String)
.desc(
"Unit to convert number into (will have an effect only with integer input)",
)
.completion(Completion::new_list(SUPPORTED_DURATION_UNITS.as_slice())),
)
.rest(
"rest",
SyntaxShape::CellPath,
"For a data structure input, convert data at the given cell paths.",
)
.category(Category::Conversions)
}
fn description(&self) -> &str {
"Convert value to duration."
}
fn extra_description(&self) -> &str {
"Max duration value is i64::MAX nanoseconds; max duration time unit is wk (weeks)."
}
fn search_terms(&self) -> Vec<&str> {
vec!["convert", "time", "period"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let cell_paths = call.rest(engine_state, stack, 0)?;
let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths);
let unit = match call.get_flag::<Spanned<String>>(engine_state, stack, "unit")? {
Some(spanned_unit) => match Unit::from_str(&spanned_unit.item) {
Ok(u) => match u {
Unit::Filesize(_) => {
return Err(ShellError::InvalidUnit {
span: spanned_unit.span,
supported_units: SUPPORTED_DURATION_UNITS.join(", "),
});
}
_ => Some(Spanned {
item: u,
span: spanned_unit.span,
}),
},
Err(_) => {
return Err(ShellError::InvalidUnit {
span: spanned_unit.span,
supported_units: SUPPORTED_DURATION_UNITS.join(", "),
});
}
},
None => None,
};
let args = Arguments { unit, cell_paths };
operate(action, args, input, call.head, engine_state.signals())
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Convert duration string to duration value",
example: "'7min' | into duration",
result: Some(Value::test_duration(7 * 60 * NS_PER_SEC)),
},
Example {
description: "Convert compound duration string to duration value",
example: "'1day 2hr 3min 4sec' | into duration",
result: Some(Value::test_duration(
(((((/* 1 * */24) + 2) * 60) + 3) * 60 + 4) * NS_PER_SEC,
)),
},
Example {
description: "Convert table of duration strings to table of duration values",
example: "[[value]; ['1sec'] ['2min'] ['3hr'] ['4day'] ['5wk']] | into duration value",
result: Some(Value::test_list(vec![
Value::test_record(record! {
"value" => Value::test_duration(NS_PER_SEC),
}),
Value::test_record(record! {
"value" => Value::test_duration(2 * 60 * NS_PER_SEC),
}),
Value::test_record(record! {
"value" => Value::test_duration(3 * 60 * 60 * NS_PER_SEC),
}),
Value::test_record(record! {
"value" => Value::test_duration(4 * 24 * 60 * 60 * NS_PER_SEC),
}),
Value::test_record(record! {
"value" => Value::test_duration(5 * 7 * 24 * 60 * 60 * NS_PER_SEC),
}),
])),
},
Example {
description: "Convert duration to duration",
example: "420sec | into duration",
result: Some(Value::test_duration(7 * 60 * NS_PER_SEC)),
},
Example {
description: "Convert a number of ns to duration",
example: "1_234_567 | into duration",
result: Some(Value::test_duration(1_234_567)),
},
Example {
description: "Convert a number of an arbitrary unit to duration",
example: "1_234 | into duration --unit ms",
result: Some(Value::test_duration(1_234 * 1_000_000)),
},
Example {
description: "Convert a floating point number of an arbitrary unit to duration",
example: "1.234 | into duration --unit sec",
result: Some(Value::test_duration(1_234 * 1_000_000)),
},
Example {
description: "Convert a record to a duration",
example: "{day: 10, hour: 2, minute: 6, second: 50, sign: '+'} | into duration",
result: Some(Value::duration(
10 * NS_PER_DAY + 2 * NS_PER_HOUR + 6 * NS_PER_MINUTE + 50 * NS_PER_SEC,
Span::test_data(),
)),
},
]
}
}
fn split_whitespace_indices(s: &str, span: Span) -> impl Iterator<Item = (&str, Span)> {
s.split_whitespace().map(move |sub| {
// Gets the offset of the `sub` substring inside the string `s`.
// `wrapping_` operations are necessary because the pointers can
// overflow on 32-bit platforms. The result will not overflow, because
// `sub` is within `s`, and the end of `s` has to be a valid memory
// address.
//
// XXX: this should be replaced with `str::substr_range` from the
// standard library when it's stabilized.
let start_offset = span
.start
.wrapping_add(sub.as_ptr() as usize)
.wrapping_sub(s.as_ptr() as usize);
(sub, Span::new(start_offset, start_offset + sub.len()))
})
}
fn compound_to_duration(s: &str, span: Span) -> Result<i64, ShellError> {
let mut duration_ns: i64 = 0;
for (substring, substring_span) in split_whitespace_indices(s, span) {
let sub_ns = string_to_duration(substring, substring_span)?;
duration_ns += sub_ns;
}
Ok(duration_ns)
}
fn string_to_duration(s: &str, span: Span) -> Result<i64, ShellError> {
if let Some(Ok(expression)) = parse_unit_value(
s.as_bytes(),
span,
DURATION_UNIT_GROUPS,
Type::Duration,
|x| x,
) && let Expr::ValueWithUnit(value) = expression.expr
&& let Expr::Int(x) = value.expr.expr
{
match value.unit.item {
Unit::Nanosecond => return Ok(x),
Unit::Microsecond => return Ok(x * 1000),
Unit::Millisecond => return Ok(x * 1000 * 1000),
Unit::Second => return Ok(x * NS_PER_SEC),
Unit::Minute => return Ok(x * 60 * NS_PER_SEC),
Unit::Hour => return Ok(x * 60 * 60 * NS_PER_SEC),
Unit::Day => return Ok(x * 24 * 60 * 60 * NS_PER_SEC),
Unit::Week => return Ok(x * 7 * 24 * 60 * 60 * NS_PER_SEC),
_ => {}
}
}
Err(ShellError::InvalidUnit {
span,
supported_units: SUPPORTED_DURATION_UNITS.join(", "),
})
}
fn action(input: &Value, args: &Arguments, head: Span) -> Value {
let value_span = input.span();
let unit_option = &args.unit;
if let Value::Record { .. } | Value::Duration { .. } = input
&& let Some(unit) = unit_option
{
return Value::error(
ShellError::IncompatibleParameters {
left_message: "got a record as input".into(),
left_span: head,
right_message: "the units should be included in the record".into(),
right_span: unit.span,
},
head,
);
}
let unit = match unit_option {
Some(unit) => &unit.item,
None => &Unit::Nanosecond,
};
match input {
Value::Duration { .. } => input.clone(),
Value::Record { val, .. } => {
merge_record(val, head, value_span).unwrap_or_else(|err| Value::error(err, value_span))
}
Value::String { val, .. } => {
if let Ok(num) = val.parse::<f64>() {
let ns = unit_to_ns_factor(unit);
return Value::duration((num * (ns as f64)) as i64, head);
}
match compound_to_duration(val, value_span) {
Ok(val) => Value::duration(val, head),
Err(error) => Value::error(error, head),
}
}
Value::Float { val, .. } => {
let ns = unit_to_ns_factor(unit);
Value::duration((*val * (ns as f64)) as i64, head)
}
Value::Int { val, .. } => {
let ns = unit_to_ns_factor(unit);
Value::duration(*val * ns, head)
}
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => input.clone(),
other => Value::error(
ShellError::OnlySupportsThisInputType {
exp_input_type: "string or duration".into(),
wrong_type: other.get_type().to_string(),
dst_span: head,
src_span: other.span(),
},
head,
),
}
}
fn merge_record(record: &Record, head: Span, span: Span) -> Result<Value, ShellError> {
if let Some(invalid_col) = record
.columns()
.find(|key| !ALLOWED_COLUMNS.contains(&key.as_str()))
{
let allowed_cols = ALLOWED_COLUMNS.join(", ");
return Err(ShellError::UnsupportedInput {
msg: format!(
"Column '{invalid_col}' is not valid for a structured duration. Allowed columns are: {allowed_cols}"
),
input: "value originates from here".into(),
msg_span: head,
input_span: span,
});
};
let mut duration: i64 = 0;
if let Some(col_val) = record.get("week") {
let week = parse_number_from_record(col_val, &head)?;
duration += week * NS_PER_WEEK;
};
if let Some(col_val) = record.get("day") {
let day = parse_number_from_record(col_val, &head)?;
duration += day * NS_PER_DAY;
};
if let Some(col_val) = record.get("hour") {
let hour = parse_number_from_record(col_val, &head)?;
duration += hour * NS_PER_HOUR;
};
if let Some(col_val) = record.get("minute") {
let minute = parse_number_from_record(col_val, &head)?;
duration += minute * NS_PER_MINUTE;
};
if let Some(col_val) = record.get("second") {
let second = parse_number_from_record(col_val, &head)?;
duration += second * NS_PER_SEC;
};
if let Some(col_val) = record.get("millisecond") {
let millisecond = parse_number_from_record(col_val, &head)?;
duration += millisecond * NS_PER_MS;
};
if let Some(col_val) = record.get("microsecond") {
let microsecond = parse_number_from_record(col_val, &head)?;
duration += microsecond * NS_PER_US;
};
if let Some(col_val) = record.get("nanosecond") {
let nanosecond = parse_number_from_record(col_val, &head)?;
duration += nanosecond;
};
if let Some(sign) = record.get("sign") {
match sign {
Value::String { val, .. } => {
if !ALLOWED_SIGNS.contains(&val.as_str()) {
let allowed_signs = ALLOWED_SIGNS.join(", ");
return Err(ShellError::IncorrectValue {
msg: format!("Invalid sign. Allowed signs are {allowed_signs}").to_string(),
val_span: sign.span(),
call_span: head,
});
}
if val == "-" {
duration = -duration;
}
}
other => {
return Err(ShellError::OnlySupportsThisInputType {
exp_input_type: "int".to_string(),
wrong_type: other.get_type().to_string(),
dst_span: head,
src_span: other.span(),
});
}
}
};
Ok(Value::duration(duration, span))
}
fn parse_number_from_record(col_val: &Value, head: &Span) -> Result<i64, ShellError> {
let value = match col_val {
Value::Int { val, .. } => {
if *val < 0 {
return Err(ShellError::IncorrectValue {
msg: "number should be positive".to_string(),
val_span: col_val.span(),
call_span: *head,
});
}
*val
}
other => {
return Err(ShellError::OnlySupportsThisInputType {
exp_input_type: "int".to_string(),
wrong_type: other.get_type().to_string(),
dst_span: *head,
src_span: other.span(),
});
}
};
Ok(value)
}
fn unit_to_ns_factor(unit: &Unit) -> i64 {
match unit {
Unit::Nanosecond => 1,
Unit::Microsecond => NS_PER_US,
Unit::Millisecond => NS_PER_MS,
Unit::Second => NS_PER_SEC,
Unit::Minute => NS_PER_MINUTE,
Unit::Hour => NS_PER_HOUR,
Unit::Day => NS_PER_DAY,
Unit::Week => NS_PER_WEEK,
_ => 0,
}
}
#[cfg(test)]
mod test {
use super::*;
use rstest::rstest;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(IntoDuration {})
}
const NS_PER_SEC: i64 = 1_000_000_000;
#[rstest]
#[case("3ns", 3)]
#[case("4us", 4 * NS_PER_US)]
#[case("4\u{00B5}s", 4 * NS_PER_US)] // micro sign
#[case("4\u{03BC}s", 4 * NS_PER_US)] // mu symbol
#[case("5ms", 5 * NS_PER_MS)]
#[case("1sec", NS_PER_SEC)]
#[case("7min", 7 * NS_PER_MINUTE)]
#[case("42hr", 42 * NS_PER_HOUR)]
#[case("123day", 123 * NS_PER_DAY)]
#[case("3wk", 3 * NS_PER_WEEK)]
#[case("86hr 26ns", 86 * 3600 * NS_PER_SEC + 26)] // compound duration string
#[case("14ns 3hr 17sec", 14 + 3 * NS_PER_HOUR + 17 * NS_PER_SEC)] // compound string with units in random order
fn turns_string_to_duration(#[case] phrase: &str, #[case] expected_duration_val: i64) {
let args = Arguments {
unit: Some(Spanned {
item: Unit::Nanosecond,
span: Span::test_data(),
}),
cell_paths: None,
};
let actual = action(&Value::test_string(phrase), &args, Span::test_data());
match actual {
Value::Duration {
val: observed_val, ..
} => {
assert_eq!(expected_duration_val, observed_val, "expected != observed")
}
other => {
panic!("Expected Value::Duration, observed {other:?}");
}
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/detect.rs | crates/nu-command/src/strings/detect.rs | use nu_engine::{command_prelude::*, get_full_help};
#[derive(Clone)]
pub struct Detect;
impl Command for Detect {
fn name(&self) -> &str {
"detect"
}
fn signature(&self) -> Signature {
Signature::build("detect")
.category(Category::Strings)
.input_output_types(vec![(Type::Nothing, Type::String)])
}
fn description(&self) -> &str {
"Various commands for detecting things."
}
fn extra_description(&self) -> &str {
"You must use one of the following subcommands. Using this command as-is will only produce this help message."
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> std::result::Result<PipelineData, ShellError> {
Ok(Value::string(get_full_help(self, engine_state, stack), call.head).into_pipeline_data())
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.