Compare commits

...

18 Commits
v0.5.2 ... main

@ -1,6 +1,6 @@
[package]
name = "embed-nu"
version = "0.5.2"
version = "0.9.1"
edition = "2021"
license = "Apache-2.0"
repository = "https://github.com/Trivernis/embed-nu"
@ -10,11 +10,12 @@ authors = ["trivernis <trivernis@proton.me>"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
miette = "5.5.0"
nu-command = "0.75.0"
nu-engine = "0.75.0"
nu-parser = "0.75.0"
nu-protocol = "0.75.0"
paste = "1.0.11"
miette = "7.1.0"
nu-cmd-lang = "0.90.1"
nu-command = "0.90.1"
nu-engine = "0.90.1"
nu-parser = "0.90.1"
nu-protocol = "0.90.1"
paste = "1.0.14"
rusty-value = { version = "0.6.0", features = ["derive"] }
thiserror = "1.0.38"
thiserror = "1.0.57"

@ -0,0 +1,79 @@
/// Copy of the nushell print command with a slight adjustment for pipelines
/// Source: https://github.com/nushell/nushell/blob/98525043edd20abb62da09726d75816d09d68f1e/crates/nu-cli/src/print.rs
use nu_engine::CallExt;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Category, IntoPipelineData, PipelineData, ShellError, Signature, Span, SyntaxShape, Type, Value,
};
use crate::NewEmpty;
#[derive(Clone)]
pub struct PrintCommand;
impl Command for PrintCommand {
fn name(&self) -> &str {
"print"
}
fn signature(&self) -> Signature {
Signature::build("print")
.input_output_types(vec![
(Type::Nothing, Type::Nothing),
(Type::Any, Type::Nothing),
])
.allow_variants_without_examples(true)
.rest("rest", SyntaxShape::Any, "the values to print")
.switch(
"no-newline",
"print without inserting a newline for the line ending",
Some('n'),
)
.switch("stderr", "print to stderr instead of stdout", Some('e'))
.category(Category::Strings)
}
fn usage(&self) -> &str {
"Print the given values to stdout."
}
fn extra_usage(&self) -> &str {
r#"Unlike `echo`, this command does not return any value (`print | describe` will return "nothing").
Since this command has no output, there is no point in piping it with other commands.
`print` may be used inside blocks of code (e.g.: hooks) to display text during execution without interfering with the pipeline.
When used inside a pipeline it passes the input forward as output without interfering with it.
"#
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let args: Vec<Value> = call.rest(engine_state, stack, 0)?;
let no_newline = call.has_flag(engine_state, stack, "no-newline")?;
let to_stderr = call.has_flag(engine_state, stack, "stderr")?;
let input_val = input.into_value(Span::empty());
// This will allow for easy printing of pipelines as well
if !args.is_empty() {
for arg in args {
arg.into_pipeline_data()
.print(engine_state, stack, no_newline, to_stderr)?;
}
} else if !input_val.is_nothing() {
input_val.clone().into_pipeline_data().print(
engine_state,
stack,
no_newline,
to_stderr,
)?;
}
Ok(input_val.into_pipeline_data())
}
}

@ -1,27 +1,27 @@
use nu_cmd_lang::*;
use nu_command::*;
use nu_protocol::engine::{EngineState, StateWorkingSet};
use crate::error::CrateResult;
use crate::{commands::PrintCommand, error::CrateResult};
macro_rules! bind_commands {
($engine_state:expr, $( $command:expr),* $(,)? ) => {
bind($engine_state, |working_set| {
$( working_set.add_decl(Box::new($command)); )*
})
};
}
($engine_state:expr, $( $command:expr),* $(,)? ) => {
bind($engine_state, |working_set| {
$( working_set.add_decl(Box::new($command)); )*
})
};
}
pub fn bind_core_commands(engine_state: &mut EngineState) -> CrateResult<()> {
bind_commands!(
engine_state,
Metadata,
Alias,
Ast,
Break,
Commandline,
Collect,
Const,
Continue,
Debug,
Def,
DefEnv,
Describe,
Do,
Echo,
@ -29,16 +29,20 @@ pub fn bind_core_commands(engine_state: &mut EngineState) -> CrateResult<()> {
ExportAlias,
ExportCommand,
ExportDef,
ExportDefEnv,
ExportExtern,
ExportUse,
Extern,
For,
Help,
HelpAliases,
HelpCommands,
HelpModules,
HelpExterns,
HelpOperators,
Hide,
HideEnv,
If,
PrintCommand,
Ignore,
Overlay,
OverlayUse,
@ -46,7 +50,8 @@ pub fn bind_core_commands(engine_state: &mut EngineState) -> CrateResult<()> {
OverlayNew,
OverlayHide,
Let,
Metadata,
Loop,
Match,
Module,
Mut,
Return,
@ -57,6 +62,23 @@ pub fn bind_core_commands(engine_state: &mut EngineState) -> CrateResult<()> {
)
}
pub fn bind_debug_commands(engine_state: &mut EngineState) -> CrateResult<()> {
bind_commands!(
engine_state,
Ast,
Debug,
DebugInfo,
Explain,
Inspect,
Metadata,
TimeIt,
View,
ViewFiles,
ViewSource,
ViewSpan,
)
}
pub fn bind_chart_commands(engine_state: &mut EngineState) -> CrateResult<()> {
bind_commands!(engine_state, Histogram)
}
@ -64,86 +86,84 @@ pub fn bind_chart_commands(engine_state: &mut EngineState) -> CrateResult<()> {
pub fn bind_filter_commands(engine_state: &mut EngineState) -> CrateResult<()> {
bind_commands! {
engine_state,
All,
Any,
Append,
Collect,
Columns,
Compact,
Default,
Drop,
DropColumn,
DropNth,
Each,
EachWhile,
Empty,
Every,
Find,
First,
Flatten,
Get,
Group,
GroupBy,
Headers,
Insert,
SplitBy,
Take,
Merge,
Move,
TakeWhile,
TakeUntil,
Last,
Length,
Lines,
ParEach,
Prepend,
Range,
Reduce,
Reject,
Rename,
Reverse,
Roll,
RollDown,
RollUp,
RollLeft,
RollRight,
Rotate,
Select,
Shuffle,
Skip,
SkipUntil,
SkipWhile,
Sort,
SortBy,
SplitList,
Transpose,
Uniq,
Upsert,
Update,
UpdateCells,
Where,
Window,
Wrap,
Zip, }
All,
Any,
Append,
Columns,
Compact,
Default,
Drop,
DropColumn,
DropNth,
Each,
Empty,
Enumerate,
Every,
Filter,
Find,
First,
Flatten,
Get,
Group,
GroupBy,
Headers,
Insert,
Items,
Join,
SplitBy,
Take,
Merge,
Move,
TakeWhile,
TakeUntil,
Last,
Length,
Lines,
ParEach,
Prepend,
Range,
Reduce,
Reject,
Rename,
Reverse,
Select,
Shuffle,
Skip,
SkipUntil,
SkipWhile,
Sort,
SortBy,
SplitList,
Transpose,
Uniq,
UniqBy,
Upsert,
Update,
Values,
Where,
Window,
Wrap,
Zip,
}
}
pub fn bind_misc_commands(engine_state: &mut EngineState) -> CrateResult<()> {
bind_commands!(engine_state, History, Tutor, HistorySession)
bind_commands!(engine_state, Tutor)
}
pub fn bind_path_commands(engine_state: &mut EngineState) -> CrateResult<()> {
bind_commands! {
engine_state,
Path,
PathBasename,
PathDirname,
PathExists,
PathExpand,
PathJoin,
PathParse,
PathRelativeTo,
PathSplit,
PathType,
Path,
PathBasename,
PathDirname,
PathExists,
PathExpand,
PathJoin,
PathParse,
PathRelativeTo,
PathSplit,
PathType,
}
}
@ -151,7 +171,6 @@ pub fn bind_path_commands(engine_state: &mut EngineState) -> CrateResult<()> {
pub fn bind_system_commands(engine_state: &mut EngineState) -> CrateResult<()> {
bind_commands! {
engine_state,
Benchmark,
Complete,
External,
NuCheck,
@ -166,7 +185,6 @@ pub fn bind_system_commands(engine_state: &mut EngineState) -> CrateResult<()> {
pub fn bind_system_commands(engine_state: &mut EngineState) -> CrateResult<()> {
bind_commands! {
engine_state,
Benchmark,
Complete,
External,
NuCheck,
@ -177,63 +195,50 @@ pub fn bind_system_commands(engine_state: &mut EngineState) -> CrateResult<()> {
}
}
pub fn bind_string_commands(engine_state: &mut EngineState) -> CrateResult<()> {
#[cfg(not(any(unix, windows)))]
pub fn bind_system_commands(engine_state: &mut EngineState) -> CrateResult<()> {
bind_commands! {
engine_state,
Char,
Decode,
Encode,
DecodeBase64,
EncodeBase64,
DetectColumns,
Format,
FileSize,
Parse,
Size,
Split,
SplitChars,
SplitColumn,
SplitRow,
SplitWords,
Str,
StrCamelCase,
StrCapitalize,
StrCollect,
StrContains,
StrDistance,
StrDowncase,
StrEndswith,
StrJoin,
StrReplace,
StrIndexOf,
StrKebabCase,
StrLength,
StrLpad,
StrPascalCase,
StrReverse,
StrRpad,
StrScreamingSnakeCase,
StrSnakeCase,
StrStartsWith,
StrSubstring,
StrTrim,
StrTitleCase,
StrUpcase,
Complete,
External,
NuCheck,
Sys,
Ps,
Which
}
}
pub fn bind_bit_commands(engine_state: &mut EngineState) -> CrateResult<()> {
pub fn bind_string_commands(engine_state: &mut EngineState) -> CrateResult<()> {
bind_commands! {
engine_state,
Bits,
BitsAnd,
BitsNot,
BitsOr,
BitsXor,
BitsRotateLeft,
BitsRotateRight,
BitsShiftLeft,
BitsShiftRight,
Char,
Decode,
Encode,
DecodeBase64,
EncodeBase64,
DetectColumns,
Format,
Parse,
Split,
SplitChars,
SplitColumn,
SplitRow,
SplitWords,
Str,
StrCapitalize,
StrContains,
StrDistance,
StrDowncase,
StrEndswith,
StrJoin,
StrReplace,
StrIndexOf,
StrLength,
StrReverse,
StrStartsWith,
StrSubstring,
StrTrim,
StrUpcase
}
}
@ -259,10 +264,10 @@ pub fn bind_file_system_commands(engine_state: &mut EngineState) -> CrateResult<
bind_commands! {
engine_state,
Cd,
Cp,
UCp,
Ls,
Mkdir,
Mv,
UMv,
Open,
Rm,
Save,
@ -276,16 +281,10 @@ pub fn bind_platform_commands(engine_state: &mut EngineState) -> CrateResult<()>
bind_commands! {
engine_state,
Ansi,
AnsiGradient,
AnsiStrip,
Clear,
Du,
KeybindingsDefault,
Input,
KeybindingsListen,
Keybindings,
Kill,
KeybindingsList,
Sleep,
TermSize,
}
@ -308,50 +307,38 @@ pub fn bind_date_commands(engine_state: &mut EngineState) -> CrateResult<()> {
pub fn bind_shell_commands(engine_state: &mut EngineState) -> CrateResult<()> {
bind_commands! {
engine_state,
Enter,
Exit,
GotoShell,
NextShell,
PrevShell,
Shells,
}
}
pub fn bind_format_commands(engine_state: &mut EngineState) -> CrateResult<()> {
bind_commands! {
engine_state,
From,
FromCsv,
FromEml,
FromIcs,
FromIni,
FromJson,
FromNuon,
FromOds,
FromSsv,
FromToml,
FromTsv,
FromUrl,
FromVcf,
FromXlsx,
FromXml,
FromYaml,
FromYml,
To,
ToCsv,
ToHtml,
ToJson,
ToMd,
ToNuon,
ToText,
ToToml,
ToTsv,
Touch,
Use,
Upsert,
Where,
ToXml,
ToYaml,
From,
FromCsv,
FromJson,
FromNuon,
FromOds,
FromSsv,
FromToml,
FromTsv,
FromXlsx,
FromXml,
FromYaml,
FromYml,
To,
ToCsv,
ToJson,
ToMd,
ToNuon,
ToText,
ToToml,
ToTsv,
Touch,
Upsert,
Where,
ToXml,
ToYaml,
}
}
@ -366,12 +353,11 @@ pub fn bind_viewer_commands(engine_state: &mut EngineState) -> CrateResult<()> {
pub fn bind_conversion_commands(engine_state: &mut EngineState) -> CrateResult<()> {
bind_commands! {
engine_state,
Fmt,
Fill,
Into,
IntoBool,
IntoBinary,
IntoDatetime,
IntoDecimal,
IntoDuration,
IntoFilesize,
IntoInt,
@ -383,12 +369,11 @@ pub fn bind_conversion_commands(engine_state: &mut EngineState) -> CrateResult<(
pub fn bind_environment_commands(engine_state: &mut EngineState) -> CrateResult<()> {
bind_commands! {
engine_state,
Env,
ExportEnv,
LetEnv,
LoadEnv,
SourceEnv,
WithEnv,
ExportEnv,
LetEnv,
LoadEnv,
SourceEnv,
WithEnv,
// nu config commands have been removed as editing isn't possible
// in this environment
}
@ -397,30 +382,41 @@ pub fn bind_environment_commands(engine_state: &mut EngineState) -> CrateResult<
pub fn bind_math_commands(engine_state: &mut EngineState) -> CrateResult<()> {
bind_commands! {
engine_state,
Math,
MathAbs,
MathAvg,
MathCeil,
MathFloor,
MathMax,
MathMedian,
MathMin,
MathMode,
MathProduct,
MathRound,
MathSqrt,
MathStddev,
MathSum,
MathVariance,
Math,
MathAbs,
MathAvg,
MathCeil,
MathFloor,
MathMax,
MathMedian,
MathMin,
MathMode,
MathProduct,
MathRound,
MathSqrt,
MathStddev,
MathSum,
MathVariance,
MathLog,
}
}
pub fn bind_network_commands(engine_state: &mut EngineState) -> CrateResult<()> {
bind_commands! {
engine_state,
Url,
UrlParse,
Port,
Http,
HttpDelete,
HttpGet,
HttpHead,
HttpPatch,
HttpPost,
HttpPut,
Url,
UrlBuildQuery,
UrlEncode,
UrlJoin,
UrlParse,
Port,
}
}
@ -430,9 +426,7 @@ pub fn bind_random_commands(engine_state: &mut EngineState) -> CrateResult<()> {
Random,
RandomBool,
RandomChars,
RandomDecimal,
RandomDice,
RandomInteger,
RandomUuid,
}
}
@ -459,7 +453,6 @@ pub fn bind_hash_commands(engine_state: &mut EngineState) -> CrateResult<()> {
pub fn bind_experimental_commands(engine_state: &mut EngineState) -> CrateResult<()> {
bind_commands! {
engine_state,
ViewSource,
IsAdmin,
}
}

@ -47,13 +47,13 @@ impl ContextBuilder {
toggle_command_groups!(
core,
debug,
filter,
chart,
misc,
path,
system,
string,
bit,
byte,
file_system,
platform,

@ -36,6 +36,8 @@ macro_rules! command_group_config {
command_group_config!(
/// Enables core commands
core,
/// Enables debug commands
debug,
/// Enables filter commands
filter,
/// Enables chart commands

@ -1,11 +1,13 @@
mod bindings;
mod builder;
mod command_group_config;
use std::collections::HashMap;
pub use builder::*;
pub use command_group_config::CommandGroupConfig;
use nu_protocol::{
ast::{Block, Call},
engine::{EngineState, Stack},
engine::{EngineState, Stack, StateWorkingSet},
PipelineData, Span,
};
@ -13,7 +15,7 @@ use crate::{
argument::IntoArgument,
error::{CrateError, CrateResult},
utils::parse_nu_script,
NewEmpty,
IntoValue, NewEmpty,
};
/// Represents the evaluation context of nu scripts and commands
@ -58,15 +60,11 @@ impl Context {
pub fn get_var<S: AsRef<str>>(&self, name: S) -> Option<nu_protocol::Value> {
let name = name.as_ref();
let dollar_name = format!("${name}");
let var_id = self
.engine_state
.active_overlays(&vec![])
.iter()
.find_map(|o| {
o.vars
.get(dollar_name.as_bytes())
.or(o.vars.get(name.as_bytes()))
})?;
let var_id = self.engine_state.active_overlays(&vec![]).find_map(|o| {
o.vars
.get(dollar_name.as_bytes())
.or(o.vars.get(name.as_bytes()))
})?;
self.stack.get_var(*var_id, Span::new(0, 0)).ok()
}
@ -99,7 +97,7 @@ impl Context {
arguments: args,
redirect_stdout: true,
redirect_stderr: true,
parser_info: Vec::new(),
parser_info: HashMap::new(),
};
let data = nu_engine::eval_call(
@ -125,4 +123,21 @@ impl Context {
Ok(())
}
/// Adds a variable to the context
pub fn add_var<S: ToString, V: IntoValue>(&mut self, name: S, value: V) -> CrateResult<()> {
let mut working_set = StateWorkingSet::new(&self.engine_state);
let var_id = working_set.add_variable(
name.to_string().into_bytes(),
Span::empty(),
nu_protocol::Type::Any,
false,
);
self.stack.add_var(var_id, value.into_value());
let delta = working_set.render();
self.engine_state.merge_delta(delta)?;
Ok(())
}
}

@ -1,86 +1,20 @@
use miette::Diagnostic;
use nu_parser::ParseError;
use nu_protocol::ShellError;
use nu_protocol::{ParseError, ShellError};
use thiserror::Error;
pub type CrateResult<T> = std::result::Result<T, CrateError>;
#[derive(Clone, Debug, Error)]
#[derive(Clone, Debug, Error, Diagnostic)]
pub enum CrateError {
#[error("Shell Error {0}")]
#[diagnostic()]
NuShellError(#[from] ShellError),
#[error("Parse Error {0}")]
NuParseError(#[from] ParseError),
#[error("Parse Error {0:?}")]
#[diagnostic()]
NuParseErrors(Vec<ParseError>),
#[error("Could not find the function {0}")]
#[diagnostic()]
FunctionNotFound(String),
}
impl Diagnostic for CrateError {
fn code<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
match self {
CrateError::NuShellError(n) => n.code(),
CrateError::NuParseError(n) => n.code(),
Self::FunctionNotFound(_) => Some(Box::new("embed_nu::fn_not_found")),
}
}
fn severity(&self) -> Option<miette::Severity> {
match self {
CrateError::NuShellError(n) => n.severity(),
CrateError::NuParseError(n) => n.severity(),
_ => None,
}
}
fn help<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
match self {
CrateError::NuShellError(n) => n.help(),
CrateError::NuParseError(n) => n.help(),
CrateError::FunctionNotFound(_) => Some(Box::new(
"Make sure the function you want to execute is defined at this point.",
)),
}
}
fn url<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
match self {
CrateError::NuShellError(n) => n.url(),
CrateError::NuParseError(n) => n.url(),
_ => None,
}
}
fn source_code(&self) -> Option<&dyn miette::SourceCode> {
match self {
CrateError::NuShellError(n) => n.source_code(),
CrateError::NuParseError(n) => n.source_code(),
_ => None,
}
}
fn labels(&self) -> Option<Box<dyn Iterator<Item = miette::LabeledSpan> + '_>> {
match self {
CrateError::NuShellError(n) => n.labels(),
CrateError::NuParseError(n) => n.labels(),
_ => None,
}
}
fn related<'a>(&'a self) -> Option<Box<dyn Iterator<Item = &'a dyn Diagnostic> + 'a>> {
match self {
CrateError::NuShellError(n) => n.related(),
CrateError::NuParseError(n) => n.related(),
_ => None,
}
}
fn diagnostic_source(&self) -> Option<&dyn Diagnostic> {
match self {
CrateError::NuShellError(n) => n.diagnostic_source(),
CrateError::NuParseError(n) => n.diagnostic_source(),
_ => None,
}
}
}

@ -1,5 +1,5 @@
use nu_protocol::{
ast::{Expr, Expression},
ast::{Expr, Expression, RecordItem},
Span, Value,
};
@ -42,16 +42,13 @@ impl ValueIntoExpression for Value {
Value::Duration { val, .. } => Expr::Int(val),
Value::Date { val, .. } => Expr::DateTime(val),
Value::String { val, .. } => Expr::String(val),
Value::Record {
mut cols, mut vals, ..
} => {
let mut entries = Vec::new();
for _ in 0..cols.len() {
let col = cols.remove(0).into_expression();
let val = vals.remove(0).into_expression();
entries.push((col, val));
}
Value::Record { val, .. } => {
let entries = val
.into_iter()
.map(|(col, val)| {
RecordItem::Pair(col.into_expression(), val.into_expression())
})
.collect();
Expr::Record(entries)
}
@ -61,7 +58,7 @@ impl ValueIntoExpression for Value {
}
Value::Block { val, .. } => Expr::Block(val),
Value::Nothing { .. } => Expr::Nothing,
Value::Error { error } => Expr::String(error.to_string()),
Value::Error { error, .. } => Expr::String(error.to_string()),
Value::Binary { val, .. } => Expr::Binary(val),
Value::CellPath { val, .. } => Expr::CellPath(val),
_ => Expr::Nothing,

@ -1,4 +1,4 @@
use nu_protocol::{Span, Value};
use nu_protocol::{Record, Span, Value};
use rusty_value::{Fields, HashableValue, RustyValue};
use crate::utils::NewEmpty;
@ -48,7 +48,7 @@ impl RustyIntoValue for Vec<Value> {
fn into_value(self) -> Value {
Value::List {
vals: self,
span: Span::empty(),
internal_span: Span::empty(),
}
}
}
@ -61,7 +61,7 @@ impl RustyIntoValue for rusty_value::Value {
if let Fields::Unit = &s.fields {
Value::String {
val: s.name,
span: Span::empty(),
internal_span: Span::empty(),
}
} else {
s.fields.into_value()
@ -71,7 +71,7 @@ impl RustyIntoValue for rusty_value::Value {
if let Fields::Unit = &e.fields {
Value::String {
val: e.variant,
span: Span::empty(),
internal_span: Span::empty(),
}
} else {
e.fields.into_value()
@ -86,9 +86,8 @@ impl RustyIntoValue for rusty_value::Value {
vals.push(val.into_value());
}
Value::Record {
cols,
vals,
span: Span::empty(),
val: Record::from_raw_cols_vals_unchecked(cols, vals),
internal_span: Span::empty(),
}
}
rusty_value::Value::List(l) => {
@ -96,11 +95,11 @@ impl RustyIntoValue for rusty_value::Value {
Value::List {
vals,
span: Span::empty(),
internal_span: Span::empty(),
}
}
rusty_value::Value::None => Value::Nothing {
span: Span::empty(),
internal_span: Span::empty(),
},
}
}
@ -113,15 +112,15 @@ impl RustyIntoValue for rusty_value::Primitive {
rusty_value::Primitive::Float(f) => f.into_value(),
rusty_value::Primitive::String(val) => Value::String {
val,
span: Span::empty(),
internal_span: Span::empty(),
},
rusty_value::Primitive::Char(val) => Value::String {
val: val.to_string(),
span: Span::empty(),
internal_span: Span::empty(),
},
rusty_value::Primitive::Bool(val) => Value::Bool {
val,
span: Span::empty(),
internal_span: Span::empty(),
},
rusty_value::Primitive::OsString(osstr) => osstr.to_string_lossy().into_value(),
}
@ -140,9 +139,8 @@ impl RustyIntoValue for rusty_value::Fields {
vals.push(v.into_value());
}
Value::Record {
cols,
vals,
span: Span::empty(),
val: Record::from_raw_cols_vals_unchecked(cols, vals),
internal_span: Span::empty(),
}
}
rusty_value::Fields::Unnamed(unnamed) => {
@ -158,12 +156,12 @@ impl RustyIntoValue for rusty_value::Fields {
} else {
Value::List {
vals,
span: Span::empty(),
internal_span: Span::empty(),
}
}
}
rusty_value::Fields::Unit => Value::Nothing {
span: Span::empty(),
internal_span: Span::empty(),
},
}
}
@ -187,7 +185,7 @@ impl RustyIntoValue for rusty_value::Integer {
};
Value::Int {
val,
span: Span::empty(),
internal_span: Span::empty(),
}
}
}
@ -201,7 +199,7 @@ impl RustyIntoValue for rusty_value::Float {
};
Value::Float {
val,
span: Span::empty(),
internal_span: Span::empty(),
}
}
}

@ -1,5 +1,6 @@
#![doc=include_str!("../README.md")]
pub(crate) mod argument;
pub mod commands;
pub(crate) mod context;
pub(crate) mod error;
pub(crate) mod into_expression;
@ -10,6 +11,8 @@ pub use argument::{Argument, IntoArgument};
pub use context::{CommandGroupConfig, Context, ContextBuilder};
pub use into_expression::*;
pub use into_value::*;
pub use nu_engine::{self, CallExt};
pub use nu_parser;
pub use nu_protocol::{self, PipelineData, Value};
pub use rusty_value;
pub use utils::NewEmpty;

@ -19,14 +19,14 @@ impl NewEmpty for Span {
pub fn parse_nu_script(engine_state: &mut EngineState, contents: String) -> CrateResult<Block> {
let mut working_set = StateWorkingSet::new(&engine_state);
let (block, err) = nu_parser::parse(&mut working_set, None, &contents.into_bytes(), false, &[]);
let block = nu_parser::parse(&mut working_set, None, &contents.into_bytes(), false);
if let Some(err) = err {
Err(CrateError::from(err))
} else {
if working_set.parse_errors.is_empty() {
let delta = working_set.render();
engine_state.merge_delta(delta)?;
Ok(block)
} else {
Err(CrateError::NuParseErrors(working_set.parse_errors))
}
}

@ -1,7 +1,7 @@
use embed_nu::{rusty_value::*, IntoValue};
use embed_nu::{rusty_value::*, IntoValue, NewEmpty};
use embed_nu::{CommandGroupConfig, Context, PipelineData};
use nu_protocol::engine::Command;
use nu_protocol::{Config, Signature, SyntaxShape};
use nu_protocol::{Config, Signature, Span, SyntaxShape};
#[test]
fn it_evals_strings() {
@ -15,6 +15,23 @@ fn it_evals_strings() {
ctx.print_pipeline(pipeline).unwrap()
}
#[test]
fn it_evals_print() {
let mut ctx = get_context();
ctx.eval_raw(
r#"print "Hello World from this eval using print""#,
PipelineData::empty(),
)
.unwrap();
}
#[test]
fn it_reports_parse_errors() {
let mut ctx = get_context();
let eval_result = ctx.eval_raw(r#"let a = 1 || 2"#, PipelineData::empty());
assert!(eval_result.is_err());
}
#[test]
fn it_returns_variables() {
let mut ctx = get_context();
@ -24,6 +41,22 @@ fn it_returns_variables() {
assert_eq!(val.as_string().unwrap(), String::from("world"))
}
#[test]
fn it_accepts_variables() {
let mut ctx = get_context();
ctx.add_var("hello", "world").unwrap();
let val = ctx.get_var("hello").expect("No variable returned");
assert_eq!(val.as_string().unwrap(), String::from("world"));
let val = ctx
.eval_raw(r#"$hello"#, PipelineData::empty())
.unwrap()
.into_value(Span::empty());
assert_eq!(val.as_string().unwrap(), String::from("world"))
}
#[derive(RustyValue)]
struct TestArg {
foo: String,

Loading…
Cancel
Save