nushell/src/commands/command.rs

611 lines
17 KiB
Rust
Raw Normal View History

Add --help for commands (#1226) * WIP --help works for PerItemCommands. * De-linting * Add more comments (#1228) * Add some more docs * More docs * More docs * More docs (#1229) * Add some more docs * More docs * More docs * Add more docs * External commands: wrap values that contain spaces in quotes (#1214) (#1220) * External commands: wrap values that contain spaces in quotes (#1214) * Add fn's argument_contains_whitespace & add_quotes (#1214) * Fix formatting with cargo fmt * Don't wrap argument in quotes when $it is already quoted (#1214) * Implement --help for internal commands * Externals now spawn independently. (#1230) This commit changes the way we shell out externals when using the `"$it"` argument. Also pipes per row to an external's stdin if no `"$it"` argument is present for external commands. Further separation of logic (preparing the external's command arguments, getting the data for piping, emitting values, spawning processes) will give us a better idea for lower level details regarding external commands until we can find the right abstractions for making them more generic and unify within the pipeline calling logic of Nu internal's and external's. * Poll externals quicker. (#1231) * WIP --help works for PerItemCommands. * De-linting * Implement --help for internal commands * Make having --help the default * Update test to include new default switch Co-authored-by: Jonathan Turner <jonathandturner@users.noreply.github.com> Co-authored-by: Koenraad Verheyden <mail@koenraadverheyden.com> Co-authored-by: Andrés N. Robalino <andres@androbtech.com>
2020-01-17 23:46:18 +01:00
use crate::commands::help::get_help;
use crate::context::CommandRegistry;
use crate::deserializer::ConfigDeserializer;
use crate::evaluate::evaluate_args::evaluate_args;
use crate::prelude::*;
2019-08-02 21:15:07 +02:00
use derive_new::new;
2019-06-22 05:43:37 +02:00
use getset::Getters;
use nu_errors::ShellError;
use nu_parser::hir;
use nu_protocol::{CallInfo, EvaluatedArgs, ReturnValue, Scope, Signature, Value};
2019-06-27 06:56:48 +02:00
use serde::{Deserialize, Serialize};
2019-07-24 00:22:11 +02:00
use std::ops::Deref;
use std::sync::atomic::AtomicBool;
2019-05-10 18:59:12 +02:00
2019-07-24 00:22:11 +02:00
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct UnevaluatedCallInfo {
pub args: hir::Call,
pub source: Text,
pub name_tag: Tag,
2019-07-24 00:22:11 +02:00
}
impl UnevaluatedCallInfo {
2019-08-14 19:02:39 +02:00
pub fn evaluate(
2019-07-24 00:22:11 +02:00
self,
registry: &CommandRegistry,
2019-07-24 00:22:11 +02:00
scope: &Scope,
) -> Result<CallInfo, ShellError> {
let args = evaluate_args(&self.args, registry, scope, &self.source)?;
2019-07-24 00:22:11 +02:00
Ok(CallInfo {
args,
name_tag: self.name_tag,
2019-07-24 00:22:11 +02:00
})
}
Add --help for commands (#1226) * WIP --help works for PerItemCommands. * De-linting * Add more comments (#1228) * Add some more docs * More docs * More docs * More docs (#1229) * Add some more docs * More docs * More docs * Add more docs * External commands: wrap values that contain spaces in quotes (#1214) (#1220) * External commands: wrap values that contain spaces in quotes (#1214) * Add fn's argument_contains_whitespace & add_quotes (#1214) * Fix formatting with cargo fmt * Don't wrap argument in quotes when $it is already quoted (#1214) * Implement --help for internal commands * Externals now spawn independently. (#1230) This commit changes the way we shell out externals when using the `"$it"` argument. Also pipes per row to an external's stdin if no `"$it"` argument is present for external commands. Further separation of logic (preparing the external's command arguments, getting the data for piping, emitting values, spawning processes) will give us a better idea for lower level details regarding external commands until we can find the right abstractions for making them more generic and unify within the pipeline calling logic of Nu internal's and external's. * Poll externals quicker. (#1231) * WIP --help works for PerItemCommands. * De-linting * Implement --help for internal commands * Make having --help the default * Update test to include new default switch Co-authored-by: Jonathan Turner <jonathandturner@users.noreply.github.com> Co-authored-by: Koenraad Verheyden <mail@koenraadverheyden.com> Co-authored-by: Andrés N. Robalino <andres@androbtech.com>
2020-01-17 23:46:18 +01:00
pub fn switch_present(&self, switch: &str) -> bool {
self.args.switch_preset(switch)
}
2019-07-24 00:22:11 +02:00
}
pub trait CallInfoExt {
fn process<'de, T: Deserialize<'de>>(
&self,
shell_manager: &ShellManager,
ctrl_c: Arc<AtomicBool>,
callback: fn(T, &RunnablePerItemContext) -> Result<OutputStream, ShellError>,
) -> Result<RunnablePerItemArgs<T>, ShellError>;
}
impl CallInfoExt for CallInfo {
fn process<'de, T: Deserialize<'de>>(
&self,
shell_manager: &ShellManager,
ctrl_c: Arc<AtomicBool>,
2019-08-24 21:36:19 +02:00
callback: fn(T, &RunnablePerItemContext) -> Result<OutputStream, ShellError>,
) -> Result<RunnablePerItemArgs<T>, ShellError> {
let mut deserializer = ConfigDeserializer::from_call_info(self.clone());
Ok(RunnablePerItemArgs {
args: T::deserialize(&mut deserializer)?,
context: RunnablePerItemContext {
shell_manager: shell_manager.clone(),
name: self.name_tag.clone(),
ctrl_c,
},
callback,
})
}
}
2019-06-22 05:43:37 +02:00
#[derive(Getters)]
#[get = "pub(crate)"]
pub struct CommandArgs {
pub host: Arc<parking_lot::Mutex<Box<dyn Host>>>,
pub ctrl_c: Arc<AtomicBool>,
2019-08-07 19:49:11 +02:00
pub shell_manager: ShellManager,
2019-07-24 00:22:11 +02:00
pub call_info: UnevaluatedCallInfo,
pub input: InputStream,
2019-05-16 02:21:46 +02:00
}
2019-08-14 19:02:39 +02:00
#[derive(Getters, Clone)]
#[get = "pub(crate)"]
2019-08-03 04:17:28 +02:00
pub struct RawCommandArgs {
pub host: Arc<parking_lot::Mutex<Box<dyn Host>>>,
pub ctrl_c: Arc<AtomicBool>,
2019-08-09 06:51:21 +02:00
pub shell_manager: ShellManager,
2019-08-03 04:17:28 +02:00
pub call_info: UnevaluatedCallInfo,
}
impl RawCommandArgs {
pub fn with_input(self, input: Vec<Value>) -> CommandArgs {
2019-08-03 04:17:28 +02:00
CommandArgs {
host: self.host,
ctrl_c: self.ctrl_c,
2019-08-09 06:51:21 +02:00
shell_manager: self.shell_manager,
2019-08-03 04:17:28 +02:00
call_info: self.call_info,
input: input.into(),
}
}
}
impl std::fmt::Debug for CommandArgs {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.call_info.fmt(f)
}
}
2019-06-22 05:43:37 +02:00
impl CommandArgs {
2019-07-24 00:22:11 +02:00
pub fn evaluate_once(
self,
registry: &CommandRegistry,
2019-08-15 07:02:02 +02:00
) -> Result<EvaluatedWholeStreamCommandArgs, ShellError> {
2019-07-24 00:22:11 +02:00
let host = self.host.clone();
let ctrl_c = self.ctrl_c.clone();
2019-08-09 06:51:21 +02:00
let shell_manager = self.shell_manager.clone();
2019-07-24 00:22:11 +02:00
let input = self.input;
let call_info = self.call_info.evaluate(registry, &Scope::empty())?;
2019-08-15 07:02:02 +02:00
Ok(EvaluatedWholeStreamCommandArgs::new(
2019-08-09 06:51:21 +02:00
host,
ctrl_c,
2019-08-09 06:51:21 +02:00
shell_manager,
call_info,
input,
))
2019-07-24 00:22:11 +02:00
}
pub fn evaluate_once_with_scope(
self,
registry: &CommandRegistry,
scope: &Scope,
) -> Result<EvaluatedWholeStreamCommandArgs, ShellError> {
let host = self.host.clone();
let ctrl_c = self.ctrl_c.clone();
let shell_manager = self.shell_manager.clone();
let input = self.input;
let call_info = self.call_info.evaluate(registry, scope)?;
Ok(EvaluatedWholeStreamCommandArgs::new(
host,
ctrl_c,
shell_manager,
call_info,
input,
))
}
2019-11-04 16:47:03 +01:00
pub fn source(&self) -> Text {
self.call_info.source.clone()
}
pub fn process<'de, T: Deserialize<'de>, O: ToOutputStream>(
2019-08-02 21:15:07 +02:00
self,
registry: &CommandRegistry,
2019-11-04 16:47:03 +01:00
callback: fn(T, RunnableContext) -> Result<O, ShellError>,
) -> Result<RunnableArgs<T, O>, ShellError> {
2019-08-09 06:51:21 +02:00
let shell_manager = self.shell_manager.clone();
2019-08-03 04:17:28 +02:00
let host = self.host.clone();
2019-11-04 16:47:03 +01:00
let source = self.source();
let ctrl_c = self.ctrl_c.clone();
2019-08-02 21:15:07 +02:00
let args = self.evaluate_once(registry)?;
let call_info = args.call_info.clone();
2019-08-02 21:15:07 +02:00
let (input, args) = args.split();
let name_tag = args.call_info.name_tag;
let mut deserializer = ConfigDeserializer::from_call_info(call_info);
2019-08-02 21:15:07 +02:00
Ok(RunnableArgs {
args: T::deserialize(&mut deserializer)?,
context: RunnableContext {
input,
2019-08-03 04:17:28 +02:00
commands: registry.clone(),
2019-11-04 16:47:03 +01:00
source,
2019-08-09 06:51:21 +02:00
shell_manager,
name: name_tag,
2019-08-03 04:17:28 +02:00
host,
ctrl_c,
2019-08-03 04:17:28 +02:00
},
callback,
})
}
pub fn process_raw<'de, T: Deserialize<'de>>(
self,
registry: &CommandRegistry,
callback: fn(T, RunnableContext, RawCommandArgs) -> Result<OutputStream, ShellError>,
) -> Result<RunnableRawArgs<T>, ShellError> {
let raw_args = RawCommandArgs {
host: self.host.clone(),
ctrl_c: self.ctrl_c.clone(),
2019-08-09 06:51:21 +02:00
shell_manager: self.shell_manager.clone(),
2019-08-03 04:17:28 +02:00
call_info: self.call_info.clone(),
};
2019-08-09 06:51:21 +02:00
let shell_manager = self.shell_manager.clone();
2019-08-03 04:17:28 +02:00
let host = self.host.clone();
2019-11-04 16:47:03 +01:00
let source = self.source();
let ctrl_c = self.ctrl_c.clone();
2019-08-03 04:17:28 +02:00
let args = self.evaluate_once(registry)?;
let call_info = args.call_info.clone();
2019-08-03 04:17:28 +02:00
let (input, args) = args.split();
let name_tag = args.call_info.name_tag;
let mut deserializer = ConfigDeserializer::from_call_info(call_info);
2019-08-03 04:17:28 +02:00
Ok(RunnableRawArgs {
args: T::deserialize(&mut deserializer)?,
context: RunnableContext {
input,
2019-08-03 04:17:28 +02:00
commands: registry.clone(),
2019-11-04 16:47:03 +01:00
source,
2019-08-09 06:51:21 +02:00
shell_manager,
name: name_tag,
2019-08-03 04:17:28 +02:00
host,
ctrl_c,
2019-08-02 21:15:07 +02:00
},
2019-08-03 04:17:28 +02:00
raw_args,
2019-08-02 21:15:07 +02:00
callback,
})
}
}
pub struct RunnablePerItemContext {
pub shell_manager: ShellManager,
pub name: Tag,
pub ctrl_c: Arc<AtomicBool>,
}
2019-08-02 21:15:07 +02:00
pub struct RunnableContext {
pub input: InputStream,
2019-08-09 06:51:21 +02:00
pub shell_manager: ShellManager,
pub host: Arc<parking_lot::Mutex<Box<dyn Host>>>,
2019-11-04 16:47:03 +01:00
pub source: Text,
pub ctrl_c: Arc<AtomicBool>,
2019-08-03 04:17:28 +02:00
pub commands: CommandRegistry,
pub name: Tag,
2019-08-02 21:15:07 +02:00
}
impl RunnableContext {
pub fn get_command(&self, name: &str) -> Result<Option<Arc<Command>>, ShellError> {
self.commands.get_command(name)
}
2019-08-02 21:15:07 +02:00
}
pub struct RunnablePerItemArgs<T> {
args: T,
context: RunnablePerItemContext,
2019-08-24 21:36:19 +02:00
callback: fn(T, &RunnablePerItemContext) -> Result<OutputStream, ShellError>,
}
impl<T> RunnablePerItemArgs<T> {
2019-08-24 21:36:19 +02:00
pub fn run(self) -> Result<OutputStream, ShellError> {
(self.callback)(self.args, &self.context)
}
}
2019-11-04 16:47:03 +01:00
pub struct RunnableArgs<T, O: ToOutputStream> {
2019-08-02 21:15:07 +02:00
args: T,
context: RunnableContext,
2019-11-04 16:47:03 +01:00
callback: fn(T, RunnableContext) -> Result<O, ShellError>,
2019-08-02 21:15:07 +02:00
}
2019-11-04 16:47:03 +01:00
impl<T, O: ToOutputStream> RunnableArgs<T, O> {
2019-08-02 21:15:07 +02:00
pub fn run(self) -> Result<OutputStream, ShellError> {
2019-11-04 16:47:03 +01:00
(self.callback)(self.args, self.context).map(|v| v.to_output_stream())
2019-08-02 21:15:07 +02:00
}
2019-07-24 00:22:11 +02:00
}
2019-08-03 04:17:28 +02:00
pub struct RunnableRawArgs<T> {
args: T,
raw_args: RawCommandArgs,
context: RunnableContext,
callback: fn(T, RunnableContext, RawCommandArgs) -> Result<OutputStream, ShellError>,
}
impl<T> RunnableRawArgs<T> {
pub fn run(self) -> OutputStream {
match (self.callback)(self.args, self.context, self.raw_args) {
Ok(stream) => stream,
Err(err) => OutputStream::one(Err(err)),
}
2019-08-03 04:17:28 +02:00
}
}
2019-08-15 07:02:02 +02:00
pub struct EvaluatedWholeStreamCommandArgs {
2019-07-24 00:22:11 +02:00
pub args: EvaluatedCommandArgs,
pub input: InputStream,
}
2019-08-15 07:02:02 +02:00
impl Deref for EvaluatedWholeStreamCommandArgs {
2019-07-24 00:22:11 +02:00
type Target = EvaluatedCommandArgs;
fn deref(&self) -> &Self::Target {
&self.args
}
}
2019-08-15 07:02:02 +02:00
impl EvaluatedWholeStreamCommandArgs {
2019-07-24 00:22:11 +02:00
pub fn new(
host: Arc<parking_lot::Mutex<dyn Host>>,
ctrl_c: Arc<AtomicBool>,
2019-08-09 06:51:21 +02:00
shell_manager: ShellManager,
2019-07-24 00:22:11 +02:00
call_info: CallInfo,
input: impl Into<InputStream>,
2019-08-15 07:02:02 +02:00
) -> EvaluatedWholeStreamCommandArgs {
EvaluatedWholeStreamCommandArgs {
2019-07-24 00:22:11 +02:00
args: EvaluatedCommandArgs {
host,
ctrl_c,
2019-08-09 06:51:21 +02:00
shell_manager,
2019-07-24 00:22:11 +02:00
call_info,
},
input: input.into(),
}
}
pub fn name_tag(&self) -> Tag {
self.args.call_info.name_tag.clone()
2019-07-24 00:22:11 +02:00
}
pub fn parts(self) -> (InputStream, EvaluatedArgs) {
2019-08-15 07:02:02 +02:00
let EvaluatedWholeStreamCommandArgs { args, input } = self;
2019-07-24 00:22:11 +02:00
(input, args.call_info.args)
}
2019-08-02 21:15:07 +02:00
pub fn split(self) -> (InputStream, EvaluatedCommandArgs) {
2019-08-15 07:02:02 +02:00
let EvaluatedWholeStreamCommandArgs { args, input } = self;
2019-08-02 21:15:07 +02:00
(input, args)
}
2019-07-24 00:22:11 +02:00
}
#[derive(Getters)]
#[get = "pub"]
pub struct EvaluatedFilterCommandArgs {
args: EvaluatedCommandArgs,
}
impl Deref for EvaluatedFilterCommandArgs {
type Target = EvaluatedCommandArgs;
fn deref(&self) -> &Self::Target {
&self.args
}
}
impl EvaluatedFilterCommandArgs {
pub fn new(
host: Arc<parking_lot::Mutex<dyn Host>>,
ctrl_c: Arc<AtomicBool>,
2019-08-09 06:51:21 +02:00
shell_manager: ShellManager,
2019-07-24 00:22:11 +02:00
call_info: CallInfo,
) -> EvaluatedFilterCommandArgs {
EvaluatedFilterCommandArgs {
args: EvaluatedCommandArgs {
host,
ctrl_c,
2019-08-09 06:51:21 +02:00
shell_manager,
2019-07-24 00:22:11 +02:00
call_info,
},
}
}
}
2019-08-02 21:15:07 +02:00
#[derive(Getters, new)]
#[get = "pub(crate)"]
2019-07-24 00:22:11 +02:00
pub struct EvaluatedCommandArgs {
pub host: Arc<parking_lot::Mutex<dyn Host>>,
pub ctrl_c: Arc<AtomicBool>,
2019-08-09 06:51:21 +02:00
pub shell_manager: ShellManager,
2019-07-24 00:22:11 +02:00
pub call_info: CallInfo,
}
impl EvaluatedCommandArgs {
pub fn nth(&self, pos: usize) -> Option<&Value> {
self.call_info.args.nth(pos)
2019-06-22 05:43:37 +02:00
}
pub fn get(&self, name: &str) -> Option<&Value> {
self.call_info.args.get(name)
2019-06-22 05:43:37 +02:00
}
pub fn has(&self, name: &str) -> bool {
self.call_info.args.has(name)
2019-06-22 05:43:37 +02:00
}
}
2019-08-15 07:02:02 +02:00
pub trait WholeStreamCommand: Send + Sync {
2019-08-02 21:15:07 +02:00
fn name(&self) -> &str;
fn signature(&self) -> Signature {
Add Range and start Signature support This commit contains two improvements: - Support for a Range syntax (and a corresponding Range value) - Work towards a signature syntax Implementing the Range syntax resulted in cleaning up how operators in the core syntax works. There are now two kinds of infix operators - tight operators (`.` and `..`) - loose operators Tight operators may not be interspersed (`$it.left..$it.right` is a syntax error). Loose operators require whitespace on both sides of the operator, and can be arbitrarily interspersed. Precedence is left to right in the core syntax. Note that delimited syntax (like `( ... )` or `[ ... ]`) is a single token node in the core syntax. A single token node can be parsed from beginning to end in a context-free manner. The rule for `.` is `<token node>.<member>`. The rule for `..` is `<token node>..<token node>`. Loose operators all have the same syntactic rule: `<token node><space><loose op><space><token node>`. The second aspect of this pull request is the beginning of support for a signature syntax. Before implementing signatures, a necessary prerequisite is for the core syntax to support multi-line programs. That work establishes a few things: - `;` and newlines are handled in the core grammar, and both count as "separators" - line comments begin with `#` and continue until the end of the line In this commit, multi-token productions in the core grammar can use separators interchangably with spaces. However, I think we will ultimately want a different rule preventing separators from occurring before an infix operator, so that the end of a line is always unambiguous. This would avoid gratuitous differences between modules and repl usage. We already effectively have this rule, because otherwise `x<newline> | y` would be a single pipeline, but of course that wouldn't work.
2019-12-04 22:14:52 +01:00
Signature::new(self.name()).desc(self.usage()).filter()
2019-05-28 08:45:18 +02:00
}
fn usage(&self) -> &str;
2019-08-14 19:02:39 +02:00
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
2019-08-24 21:36:19 +02:00
) -> Result<OutputStream, ShellError>;
2019-09-04 03:50:23 +02:00
fn is_binary(&self) -> bool {
false
}
}
pub trait PerItemCommand: Send + Sync {
fn name(&self) -> &str;
2019-08-14 19:02:39 +02:00
fn signature(&self) -> Signature {
Add Range and start Signature support This commit contains two improvements: - Support for a Range syntax (and a corresponding Range value) - Work towards a signature syntax Implementing the Range syntax resulted in cleaning up how operators in the core syntax works. There are now two kinds of infix operators - tight operators (`.` and `..`) - loose operators Tight operators may not be interspersed (`$it.left..$it.right` is a syntax error). Loose operators require whitespace on both sides of the operator, and can be arbitrarily interspersed. Precedence is left to right in the core syntax. Note that delimited syntax (like `( ... )` or `[ ... ]`) is a single token node in the core syntax. A single token node can be parsed from beginning to end in a context-free manner. The rule for `.` is `<token node>.<member>`. The rule for `..` is `<token node>..<token node>`. Loose operators all have the same syntactic rule: `<token node><space><loose op><space><token node>`. The second aspect of this pull request is the beginning of support for a signature syntax. Before implementing signatures, a necessary prerequisite is for the core syntax to support multi-line programs. That work establishes a few things: - `;` and newlines are handled in the core grammar, and both count as "separators" - line comments begin with `#` and continue until the end of the line In this commit, multi-token productions in the core grammar can use separators interchangably with spaces. However, I think we will ultimately want a different rule preventing separators from occurring before an infix operator, so that the end of a line is always unambiguous. This would avoid gratuitous differences between modules and repl usage. We already effectively have this rule, because otherwise `x<newline> | y` would be a single pipeline, but of course that wouldn't work.
2019-12-04 22:14:52 +01:00
Signature::new(self.name()).desc(self.usage()).filter()
2019-08-14 19:02:39 +02:00
}
fn usage(&self) -> &str;
fn run(
&self,
call_info: &CallInfo,
registry: &CommandRegistry,
raw_args: &RawCommandArgs,
input: Value,
) -> Result<OutputStream, ShellError>;
2019-09-04 03:50:23 +02:00
fn is_binary(&self) -> bool {
false
}
2019-08-14 19:02:39 +02:00
}
2019-08-02 21:15:07 +02:00
pub enum Command {
2019-08-15 07:02:02 +02:00
WholeStream(Arc<dyn WholeStreamCommand>),
2019-08-14 19:02:39 +02:00
PerItem(Arc<dyn PerItemCommand>),
2019-08-02 21:15:07 +02:00
}
2019-06-07 08:34:42 +02:00
impl PrettyDebugWithSource for Command {
fn pretty_debug(&self, source: &str) -> DebugDocBuilder {
match self {
Command::WholeStream(command) => b::typed(
"whole stream command",
b::description(command.name())
+ b::space()
+ b::equals()
+ b::space()
+ command.signature().pretty_debug(source),
),
Command::PerItem(command) => b::typed(
"per item command",
b::description(command.name())
+ b::space()
+ b::equals()
+ b::space()
+ command.signature().pretty_debug(source),
),
}
}
}
Overhaul the expansion system The main thrust of this (very large) commit is an overhaul of the expansion system. The parsing pipeline is: - Lightly parse the source file for atoms, basic delimiters and pipeline structure into a token tree - Expand the token tree into a HIR (high-level intermediate representation) based upon the baseline syntax rules for expressions and the syntactic shape of commands. Somewhat non-traditionally, nu doesn't have an AST at all. It goes directly from the token tree, which doesn't represent many important distinctions (like the difference between `hello` and `5KB`) directly into a high-level representation that doesn't have a direct correspondence to the source code. At a high level, nu commands work like macros, in the sense that the syntactic shape of the invocation of a command depends on the definition of a command. However, commands do not have the ability to perform unrestricted expansions of the token tree. Instead, they describe their arguments in terms of syntactic shapes, and the expander expands the token tree into HIR based upon that definition. For example, the `where` command says that it takes a block as its first required argument, and the description of the block syntactic shape expands the syntax `cpu > 10` into HIR that represents `{ $it.cpu > 10 }`. This commit overhauls that system so that the syntactic shapes are described in terms of a few new traits (`ExpandSyntax` and `ExpandExpression` are the primary ones) that are more composable than the previous system. The first big win of this new system is the addition of the `ColumnPath` shape, which looks like `cpu."max ghz"` or `package.version`. Previously, while a variable path could look like `$it.cpu."max ghz"`, the tail of a variable path could not be easily reused in other contexts. Now, that tail is its own syntactic shape, and it can be used as part of a command's signature. This cleans up commands like `inc`, `add` and `edit` as well as shorthand blocks, which can now look like `| where cpu."max ghz" > 10`
2019-09-18 00:26:27 +02:00
impl std::fmt::Debug for Command {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Command::WholeStream(command) => write!(f, "WholeStream({})", command.name()),
Command::PerItem(command) => write!(f, "PerItem({})", command.name()),
}
}
}
2019-08-02 21:15:07 +02:00
impl Command {
pub fn name(&self) -> &str {
match self {
2019-08-15 07:02:02 +02:00
Command::WholeStream(command) => command.name(),
2019-08-14 19:02:39 +02:00
Command::PerItem(command) => command.name(),
2019-08-02 21:15:07 +02:00
}
}
pub fn signature(&self) -> Signature {
match self {
2019-08-15 07:02:02 +02:00
Command::WholeStream(command) => command.signature(),
2019-08-14 19:02:39 +02:00
Command::PerItem(command) => command.signature(),
2019-08-02 21:15:07 +02:00
}
}
pub fn usage(&self) -> &str {
match self {
Command::WholeStream(command) => command.usage(),
Command::PerItem(command) => command.usage(),
}
}
pub fn run(&self, args: CommandArgs, registry: &CommandRegistry) -> OutputStream {
Add --help for commands (#1226) * WIP --help works for PerItemCommands. * De-linting * Add more comments (#1228) * Add some more docs * More docs * More docs * More docs (#1229) * Add some more docs * More docs * More docs * Add more docs * External commands: wrap values that contain spaces in quotes (#1214) (#1220) * External commands: wrap values that contain spaces in quotes (#1214) * Add fn's argument_contains_whitespace & add_quotes (#1214) * Fix formatting with cargo fmt * Don't wrap argument in quotes when $it is already quoted (#1214) * Implement --help for internal commands * Externals now spawn independently. (#1230) This commit changes the way we shell out externals when using the `"$it"` argument. Also pipes per row to an external's stdin if no `"$it"` argument is present for external commands. Further separation of logic (preparing the external's command arguments, getting the data for piping, emitting values, spawning processes) will give us a better idea for lower level details regarding external commands until we can find the right abstractions for making them more generic and unify within the pipeline calling logic of Nu internal's and external's. * Poll externals quicker. (#1231) * WIP --help works for PerItemCommands. * De-linting * Implement --help for internal commands * Make having --help the default * Update test to include new default switch Co-authored-by: Jonathan Turner <jonathandturner@users.noreply.github.com> Co-authored-by: Koenraad Verheyden <mail@koenraadverheyden.com> Co-authored-by: Andrés N. Robalino <andres@androbtech.com>
2020-01-17 23:46:18 +01:00
if args.call_info.switch_present("help") {
get_help(self.name(), self.usage(), self.signature()).into()
} else {
match self {
Command::WholeStream(command) => match command.run(args, registry) {
Ok(stream) => stream,
Err(err) => OutputStream::one(Err(err)),
},
Command::PerItem(command) => {
self.run_helper(command.clone(), args, registry.clone())
}
}
2019-06-07 08:34:42 +02:00
}
}
2019-08-14 19:02:39 +02:00
fn run_helper(
&self,
command: Arc<dyn PerItemCommand>,
args: CommandArgs,
registry: CommandRegistry,
) -> OutputStream {
2019-08-14 19:02:39 +02:00
let raw_args = RawCommandArgs {
host: args.host,
ctrl_c: args.ctrl_c,
2019-08-14 19:02:39 +02:00
shell_manager: args.shell_manager,
call_info: args.call_info,
};
2019-08-15 07:02:02 +02:00
let out = args
.input
.values
.map(move |x| {
let call_info = raw_args
.clone()
.call_info
2019-12-24 02:26:47 +01:00
.evaluate(&registry, &Scope::it_value(x.clone()));
match call_info {
Ok(call_info) => match command.run(&call_info, &registry, &raw_args, x) {
Ok(o) => o,
Err(e) => VecDeque::from(vec![ReturnValue::Err(e)]).to_output_stream(),
},
Err(e) => VecDeque::from(vec![ReturnValue::Err(e)]).to_output_stream(),
2019-10-28 19:40:34 +01:00
}
})
.flatten();
out.to_output_stream()
2019-08-14 19:02:39 +02:00
}
2019-09-04 03:50:23 +02:00
pub fn is_binary(&self) -> bool {
match self {
Command::WholeStream(command) => command.is_binary(),
Command::PerItem(command) => command.is_binary(),
}
}
2019-06-07 08:34:42 +02:00
}
2019-07-24 00:22:11 +02:00
pub struct FnFilterCommand {
2019-05-28 08:45:18 +02:00
name: String,
2019-07-24 00:22:11 +02:00
func: fn(EvaluatedFilterCommandArgs) -> Result<OutputStream, ShellError>,
}
2019-05-22 09:12:03 +02:00
2019-08-15 07:02:02 +02:00
impl WholeStreamCommand for FnFilterCommand {
2019-07-24 00:22:11 +02:00
fn name(&self) -> &str {
&self.name
}
fn usage(&self) -> &str {
"usage"
}
2019-07-24 00:22:11 +02:00
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
2019-07-24 00:22:11 +02:00
) -> Result<OutputStream, ShellError> {
let CommandArgs {
host,
ctrl_c,
2019-08-09 06:51:21 +02:00
shell_manager,
2019-07-24 00:22:11 +02:00
call_info,
input,
} = args;
let host: Arc<parking_lot::Mutex<dyn Host>> = host.clone();
let registry: CommandRegistry = registry.clone();
2019-07-24 00:22:11 +02:00
let func = self.func;
let result = input.values.map(move |it| {
let registry = registry.clone();
2019-09-02 08:11:05 +02:00
let call_info = match call_info.clone().evaluate(&registry, &Scope::it_value(it)) {
2019-07-24 00:22:11 +02:00
Err(err) => return OutputStream::from(vec![Err(err)]).values,
Ok(args) => args,
};
let args = EvaluatedFilterCommandArgs::new(
host.clone(),
ctrl_c.clone(),
shell_manager.clone(),
call_info,
);
2019-07-24 00:22:11 +02:00
match func(args) {
Err(err) => OutputStream::from(vec![Err(err)]).values,
2019-07-24 00:22:11 +02:00
Ok(stream) => stream.values,
}
});
let result = result.flatten();
let result: BoxStream<ReturnValue> = result.boxed();
Ok(result.into())
}
}
2019-08-15 07:02:02 +02:00
pub fn whole_stream_command(command: impl WholeStreamCommand + 'static) -> Arc<Command> {
Arc::new(Command::WholeStream(Arc::new(command)))
2019-07-24 00:22:11 +02:00
}
2019-08-14 19:02:39 +02:00
pub fn per_item_command(command: impl PerItemCommand + 'static) -> Arc<Command> {
Arc::new(Command::PerItem(Arc::new(command)))
}