nushell/src/cli.rs

611 lines
20 KiB
Rust
Raw Normal View History

2019-06-07 18:30:50 +02:00
use crate::commands::autoview;
2019-05-24 09:29:16 +02:00
use crate::commands::classified::{
2019-05-26 08:54:41 +02:00
ClassifiedCommand, ClassifiedInputStream, ClassifiedPipeline, ExternalCommand, InternalCommand,
StreamNext,
2019-05-24 09:29:16 +02:00
};
2019-07-04 05:06:43 +02:00
use crate::commands::plugin::JsonRpc;
2019-08-09 09:54:21 +02:00
use crate::commands::plugin::{PluginCommand, PluginSink};
2019-08-15 07:02:02 +02:00
use crate::commands::whole_stream_command;
2019-05-23 06:30:43 +02:00
use crate::context::Context;
use crate::data::Value;
pub(crate) use crate::errors::ShellError;
2019-07-03 19:37:09 +02:00
use crate::git::current_branch;
2019-08-02 21:15:07 +02:00
use crate::parser::registry::Signature;
use crate::parser::{hir, CallNode, Pipeline, PipelineElement, TokenNode};
2019-07-03 19:37:09 +02:00
use crate::prelude::*;
2019-05-23 06:30:43 +02:00
2019-06-22 05:43:37 +02:00
use log::{debug, trace};
2019-05-23 06:30:43 +02:00
use rustyline::error::ReadlineError;
2019-08-30 20:27:15 +02:00
use rustyline::{self, config::Configurer, config::EditMode, ColorMode, Config, Editor};
2019-07-03 19:37:09 +02:00
use std::env;
2019-05-23 06:30:43 +02:00
use std::error::Error;
2019-07-03 19:37:09 +02:00
use std::io::{BufRead, BufReader, Write};
2019-05-24 09:29:16 +02:00
use std::iter::Iterator;
2019-06-07 02:31:22 +02:00
use std::sync::atomic::{AtomicBool, Ordering};
2019-05-23 06:30:43 +02:00
#[derive(Debug)]
pub enum MaybeOwned<'a, T> {
Owned(T),
Borrowed(&'a T),
}
impl<T> MaybeOwned<'_, T> {
2019-07-04 07:11:56 +02:00
pub fn borrow(&self) -> &T {
2019-05-23 06:30:43 +02:00
match self {
MaybeOwned::Owned(v) => v,
MaybeOwned::Borrowed(v) => v,
}
}
}
2019-07-04 05:06:43 +02:00
fn load_plugin(path: &std::path::Path, context: &mut Context) -> Result<(), ShellError> {
let mut child = std::process::Command::new(path)
2019-07-03 19:37:09 +02:00
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.spawn()
.expect("Failed to spawn child process");
let stdin = child.stdin.as_mut().expect("Failed to open stdin");
let stdout = child.stdout.as_mut().expect("Failed to open stdout");
let mut reader = BufReader::new(stdout);
let request = JsonRpc::new("config", Vec::<Value>::new());
let request_raw = serde_json::to_string(&request)?;
2019-07-03 19:37:09 +02:00
stdin.write(format!("{}\n", request_raw).as_bytes())?;
let path = dunce::canonicalize(path)?;
2019-07-03 19:37:09 +02:00
let mut input = String::new();
2019-08-31 23:19:59 +02:00
let result = match reader.read_line(&mut input) {
Add support for ~ expansion This ended up being a bit of a yak shave. The basic idea in this commit is to expand `~` in paths, but only in paths. The way this is accomplished is by doing the expansion inside of the code that parses literal syntax for `SyntaxType::Path`. As a quick refresher: every command is entitled to expand its arguments in a custom way. While this could in theory be used for general-purpose macros, today the expansion facility is limited to syntactic hints. For example, the syntax `where cpu > 0` expands under the hood to `where { $it.cpu > 0 }`. This happens because the first argument to `where` is defined as a `SyntaxType::Block`, and the parser coerces binary expressions whose left-hand-side looks like a member into a block when the command is expecting one. This is mildly more magical than what most programming languages would do, but we believe that it makes sense to allow commands to fine-tune the syntax because of the domain nushell is in (command-line shells). The syntactic expansions supported by this facility are relatively limited. For example, we don't allow `$it` to become a bare word, simply because the command asks for a string in the relevant position. That would quickly become more confusing than it's worth. This PR adds a new `SyntaxType` rule: `SyntaxType::Path`. When a command declares a parameter as a `SyntaxType::Path`, string literals and bare words passed as an argument to that parameter are processed using the path expansion rules. Right now, that only means that `~` is expanded into the home directory, but additional rules are possible in the future. By restricting this expansion to a syntactic expansion when passed as an argument to a command expecting a path, we avoid making `~` a generally reserved character. This will also allow us to give good tab completion for paths with `~` characters in them when a command is expecting a path. In order to accomplish the above, this commit changes the parsing functions to take a `Context` instead of just a `CommandRegistry`. From the perspective of macro expansion, you can think of the `CommandRegistry` as a dictionary of in-scope macros, and the `Context` as the compile-time state used in expansion. This could gain additional functionality over time as we find more uses for the expansion system.
2019-08-26 21:21:03 +02:00
Ok(count) => {
trace!("processing response ({} bytes)", count);
2019-09-14 19:48:24 +02:00
trace!("response: {}", input);
Add support for ~ expansion This ended up being a bit of a yak shave. The basic idea in this commit is to expand `~` in paths, but only in paths. The way this is accomplished is by doing the expansion inside of the code that parses literal syntax for `SyntaxType::Path`. As a quick refresher: every command is entitled to expand its arguments in a custom way. While this could in theory be used for general-purpose macros, today the expansion facility is limited to syntactic hints. For example, the syntax `where cpu > 0` expands under the hood to `where { $it.cpu > 0 }`. This happens because the first argument to `where` is defined as a `SyntaxType::Block`, and the parser coerces binary expressions whose left-hand-side looks like a member into a block when the command is expecting one. This is mildly more magical than what most programming languages would do, but we believe that it makes sense to allow commands to fine-tune the syntax because of the domain nushell is in (command-line shells). The syntactic expansions supported by this facility are relatively limited. For example, we don't allow `$it` to become a bare word, simply because the command asks for a string in the relevant position. That would quickly become more confusing than it's worth. This PR adds a new `SyntaxType` rule: `SyntaxType::Path`. When a command declares a parameter as a `SyntaxType::Path`, string literals and bare words passed as an argument to that parameter are processed using the path expansion rules. Right now, that only means that `~` is expanded into the home directory, but additional rules are possible in the future. By restricting this expansion to a syntactic expansion when passed as an argument to a command expecting a path, we avoid making `~` a generally reserved character. This will also allow us to give good tab completion for paths with `~` characters in them when a command is expecting a path. In order to accomplish the above, this commit changes the parsing functions to take a `Context` instead of just a `CommandRegistry`. From the perspective of macro expansion, you can think of the `CommandRegistry` as a dictionary of in-scope macros, and the `Context` as the compile-time state used in expansion. This could gain additional functionality over time as we find more uses for the expansion system.
2019-08-26 21:21:03 +02:00
2019-08-02 21:15:07 +02:00
let response = serde_json::from_str::<JsonRpc<Result<Signature, ShellError>>>(&input);
2019-07-03 19:37:09 +02:00
match response {
Ok(jrpc) => match jrpc.params {
Ok(params) => {
2019-07-04 05:06:43 +02:00
let fname = path.to_string_lossy();
Add support for ~ expansion This ended up being a bit of a yak shave. The basic idea in this commit is to expand `~` in paths, but only in paths. The way this is accomplished is by doing the expansion inside of the code that parses literal syntax for `SyntaxType::Path`. As a quick refresher: every command is entitled to expand its arguments in a custom way. While this could in theory be used for general-purpose macros, today the expansion facility is limited to syntactic hints. For example, the syntax `where cpu > 0` expands under the hood to `where { $it.cpu > 0 }`. This happens because the first argument to `where` is defined as a `SyntaxType::Block`, and the parser coerces binary expressions whose left-hand-side looks like a member into a block when the command is expecting one. This is mildly more magical than what most programming languages would do, but we believe that it makes sense to allow commands to fine-tune the syntax because of the domain nushell is in (command-line shells). The syntactic expansions supported by this facility are relatively limited. For example, we don't allow `$it` to become a bare word, simply because the command asks for a string in the relevant position. That would quickly become more confusing than it's worth. This PR adds a new `SyntaxType` rule: `SyntaxType::Path`. When a command declares a parameter as a `SyntaxType::Path`, string literals and bare words passed as an argument to that parameter are processed using the path expansion rules. Right now, that only means that `~` is expanded into the home directory, but additional rules are possible in the future. By restricting this expansion to a syntactic expansion when passed as an argument to a command expecting a path, we avoid making `~` a generally reserved character. This will also allow us to give good tab completion for paths with `~` characters in them when a command is expecting a path. In order to accomplish the above, this commit changes the parsing functions to take a `Context` instead of just a `CommandRegistry`. From the perspective of macro expansion, you can think of the `CommandRegistry` as a dictionary of in-scope macros, and the `Context` as the compile-time state used in expansion. This could gain additional functionality over time as we find more uses for the expansion system.
2019-08-26 21:21:03 +02:00
trace!("processing {:?}", params);
2019-07-03 19:37:09 +02:00
if params.is_filter {
let fname = fname.to_string();
2019-07-16 09:08:35 +02:00
let name = params.name.clone();
2019-08-15 07:02:02 +02:00
context.add_commands(vec![whole_stream_command(PluginCommand::new(
2019-07-16 09:08:35 +02:00
name, fname, params,
))]);
2019-07-03 19:37:09 +02:00
Ok(())
} else {
2019-08-09 09:54:21 +02:00
let fname = fname.to_string();
let name = params.name.clone();
2019-08-15 07:02:02 +02:00
context.add_commands(vec![whole_stream_command(PluginSink::new(
2019-08-09 09:54:21 +02:00
name, fname, params,
))]);
2019-07-03 19:37:09 +02:00
Ok(())
}
}
Err(e) => Err(e),
},
Err(e) => Err(ShellError::string(format!("Error: {:?}", e))),
}
}
Err(e) => Err(ShellError::string(format!("Error: {:?}", e))),
2019-08-31 23:19:59 +02:00
};
let _ = child.wait();
2019-08-31 23:19:59 +02:00
result
2019-07-03 19:37:09 +02:00
}
2019-09-12 05:20:42 +02:00
fn search_paths() -> Vec<std::path::PathBuf> {
let mut search_paths = Vec::new();
2019-07-04 05:06:43 +02:00
2019-07-03 19:37:09 +02:00
match env::var_os("PATH") {
Some(paths) => {
2019-09-12 05:20:42 +02:00
search_paths = env::split_paths(&paths).collect::<Vec<_>>();
2019-07-03 19:37:09 +02:00
}
None => println!("PATH is not defined in the environment."),
}
#[cfg(debug_assertions)]
{
// Use our debug plugins in debug mode
let mut path = std::path::PathBuf::from(".");
path.push("target");
path.push("debug");
if path.exists() {
search_paths.push(path);
}
}
2019-07-03 19:37:09 +02:00
#[cfg(not(debug_assertions))]
{
// Use our release plugins in release mode
let mut path = std::path::PathBuf::from(".");
path.push("target");
path.push("release");
if path.exists() {
search_paths.push(path);
}
2019-09-12 05:20:42 +02:00
}
// permit Nu finding and picking up development plugins
// if there are any first.
search_paths.reverse();
2019-09-12 05:20:42 +02:00
search_paths
}
fn load_plugins(context: &mut Context) -> Result<(), ShellError> {
let opts = glob::MatchOptions {
case_sensitive: false,
require_literal_separator: false,
require_literal_leading_dot: false,
};
for path in search_paths() {
2019-09-12 05:34:47 +02:00
let mut pattern = path.to_path_buf();
pattern.push(std::path::Path::new("nu_plugin_[a-z]*"));
2019-09-12 05:20:42 +02:00
match glob::glob_with(&pattern.to_string_lossy(), opts) {
Err(_) => {}
Ok(binaries) => {
for bin in binaries.filter_map(Result::ok) {
if !bin.is_file() {
continue;
}
2019-09-12 05:34:47 +02:00
let bin_name = {
if let Some(name) = bin.file_name() {
match name.to_str() {
Some(raw) => raw,
None => continue,
}
} else {
continue;
}
};
2019-09-12 05:20:42 +02:00
let is_valid_name = {
#[cfg(windows)]
{
bin_name
.chars()
.all(|c| c.is_ascii_alphabetic() || c == '_' || c == '.')
}
#[cfg(not(windows))]
{
bin_name
.chars()
.all(|c| c.is_ascii_alphabetic() || c == '_')
}
};
2019-09-12 05:20:42 +02:00
let is_executable = {
#[cfg(windows)]
{
bin_name.ends_with(".exe") || bin_name.ends_with(".bat")
2019-09-12 05:20:42 +02:00
}
#[cfg(not(windows))]
{
true
}
};
if is_valid_name && is_executable {
2019-09-12 05:34:47 +02:00
trace!("Trying {:?}", bin.display());
2019-09-12 05:20:42 +02:00
load_plugin(&bin, context)?;
}
}
}
}
}
2019-07-03 19:37:09 +02:00
Ok(())
}
pub async fn cli() -> Result<(), Box<dyn Error>> {
2019-05-23 06:30:43 +02:00
let mut context = Context::basic()?;
{
use crate::commands::*;
context.add_commands(vec![
2019-09-07 17:49:15 +02:00
whole_stream_command(PWD),
whole_stream_command(LS),
whole_stream_command(CD),
whole_stream_command(Size),
whole_stream_command(Nth),
whole_stream_command(Next),
whole_stream_command(Previous),
whole_stream_command(Debug),
whole_stream_command(Lines),
whole_stream_command(Shells),
whole_stream_command(SplitColumn),
whole_stream_command(SplitRow),
whole_stream_command(Lines),
whole_stream_command(Reject),
2019-08-25 18:14:17 +02:00
whole_stream_command(Reverse),
whole_stream_command(Trim),
2019-08-26 16:16:34 +02:00
whole_stream_command(ToBSON),
whole_stream_command(ToCSV),
whole_stream_command(ToJSON),
2019-08-27 23:45:18 +02:00
whole_stream_command(ToSQLite),
2019-08-31 03:30:41 +02:00
whole_stream_command(ToDB),
whole_stream_command(ToTOML),
2019-08-29 11:02:16 +02:00
whole_stream_command(ToTSV),
whole_stream_command(ToYAML),
whole_stream_command(SortBy),
whole_stream_command(Tags),
whole_stream_command(First),
2019-08-24 20:32:48 +02:00
whole_stream_command(Last),
2019-09-16 09:52:58 +02:00
whole_stream_command(Env),
whole_stream_command(FromCSV),
2019-08-29 11:02:16 +02:00
whole_stream_command(FromTSV),
whole_stream_command(FromINI),
whole_stream_command(FromBSON),
whole_stream_command(FromJSON),
2019-08-31 03:30:41 +02:00
whole_stream_command(FromDB),
2019-08-27 23:45:18 +02:00
whole_stream_command(FromSQLite),
whole_stream_command(FromTOML),
whole_stream_command(FromXML),
whole_stream_command(FromYAML),
2019-08-29 05:53:45 +02:00
whole_stream_command(FromYML),
whole_stream_command(Pick),
2019-08-15 07:02:02 +02:00
whole_stream_command(Get),
per_item_command(Remove),
2019-09-03 08:04:46 +02:00
per_item_command(Fetch),
2019-08-15 07:02:02 +02:00
per_item_command(Open),
2019-08-30 20:27:15 +02:00
per_item_command(Post),
2019-08-14 19:02:39 +02:00
per_item_command(Where),
2019-09-08 01:43:53 +02:00
per_item_command(Echo),
2019-08-15 07:02:02 +02:00
whole_stream_command(Config),
whole_stream_command(SkipWhile),
2019-08-14 19:02:39 +02:00
per_item_command(Enter),
per_item_command(Help),
2019-08-15 07:02:02 +02:00
whole_stream_command(Exit),
whole_stream_command(Autoview),
per_item_command(Cpy),
whole_stream_command(Date),
per_item_command(Mkdir),
per_item_command(Move),
whole_stream_command(Save),
whole_stream_command(Table),
whole_stream_command(VTable),
2019-08-19 03:30:29 +02:00
whole_stream_command(Version),
2019-08-15 07:02:02 +02:00
whole_stream_command(Which),
2019-06-07 09:50:26 +02:00
]);
2019-08-23 05:29:08 +02:00
#[cfg(feature = "clipboard")]
{
context.add_commands(vec![whole_stream_command(
crate::commands::clip::clipboard::Clip,
)]);
}
2019-05-23 06:30:43 +02:00
}
2019-07-04 05:06:43 +02:00
let _ = load_plugins(&mut context);
2019-05-23 06:30:43 +02:00
2019-05-26 08:54:41 +02:00
let config = Config::builder().color_mode(ColorMode::Forced).build();
2019-08-07 19:49:11 +02:00
let mut rl: Editor<_> = Editor::with_config(config);
2019-05-26 08:54:41 +02:00
#[cfg(windows)]
{
let _ = ansi_term::enable_ansi_support();
}
2019-08-27 00:41:57 +02:00
// we are ok if history does not exist
2019-06-03 02:03:40 +02:00
let _ = rl.load_history("history.txt");
2019-05-26 08:54:41 +02:00
2019-06-07 02:31:22 +02:00
let ctrl_c = Arc::new(AtomicBool::new(false));
let cc = ctrl_c.clone();
ctrlc::set_handler(move || {
cc.store(true, Ordering::SeqCst);
})
.expect("Error setting Ctrl-C handler");
2019-06-15 20:36:17 +02:00
let mut ctrlcbreak = false;
2019-05-23 06:30:43 +02:00
loop {
2019-06-07 02:31:22 +02:00
if ctrl_c.load(Ordering::SeqCst) {
ctrl_c.store(false, Ordering::SeqCst);
continue;
}
2019-08-07 19:49:11 +02:00
let cwd = context.shell_manager.path();
rl.set_helper(Some(crate::shell::Helper::new(
context.shell_manager.clone(),
)));
let edit_mode = crate::data::config::config(Tag::unknown())?
.get("edit_mode")
.map(|s| match s.as_string().unwrap().as_ref() {
"vi" => EditMode::Vi,
"emacs" => EditMode::Emacs,
_ => EditMode::Emacs,
})
.unwrap_or(EditMode::Emacs);
rl.set_edit_mode(edit_mode);
2019-08-07 19:49:11 +02:00
2019-07-16 21:10:25 +02:00
let readline = rl.readline(&format!(
"{}{}> ",
cwd,
match current_branch() {
Some(s) => format!("({})", s),
None => "".to_string(),
}
));
2019-05-23 06:30:43 +02:00
match process_line(readline, &mut context).await {
2019-05-23 06:30:43 +02:00
LineResult::Success(line) => {
rl.add_history_entry(line.clone());
}
2019-06-15 20:36:17 +02:00
LineResult::CtrlC => {
if ctrlcbreak {
std::process::exit(0);
} else {
context.with_host(|host| host.stdout("CTRL-C pressed (again to quit)"));
2019-06-15 20:36:17 +02:00
ctrlcbreak = true;
continue;
}
}
2019-06-18 02:39:09 +02:00
LineResult::Error(mut line, err) => {
rl.add_history_entry(line.clone());
2019-06-24 02:55:31 +02:00
let diag = err.to_diagnostic();
context.with_host(|host| {
let writer = host.err_termcolor();
line.push_str(" ");
let files = crate::parser::Files::new(line);
let _ = std::panic::catch_unwind(move || {
let _ = language_reporting::emit(
&mut writer.lock(),
&files,
&diag,
&language_reporting::DefaultConfig,
);
});
})
2019-06-18 02:39:09 +02:00
}
2019-05-23 06:30:43 +02:00
LineResult::Break => {
break;
}
}
2019-06-15 20:36:17 +02:00
ctrlcbreak = false;
2019-05-23 06:30:43 +02:00
}
2019-08-27 00:41:57 +02:00
// we are ok if we can not save history
let _ = rl.save_history("history.txt");
2019-05-23 06:30:43 +02:00
Ok(())
}
enum LineResult {
Success(String),
2019-06-08 00:35:07 +02:00
Error(String, ShellError),
2019-06-15 20:36:17 +02:00
CtrlC,
2019-05-23 06:30:43 +02:00
Break,
}
async fn process_line(readline: Result<String, ReadlineError>, ctx: &mut Context) -> LineResult {
2019-05-23 06:30:43 +02:00
match &readline {
Ok(line) if line.trim() == "" => LineResult::Success(line.clone()),
Ok(line) => {
let result = match crate::parser::parse(&line, uuid::Uuid::nil()) {
2019-05-23 06:30:43 +02:00
Err(err) => {
2019-06-09 19:52:56 +02:00
return LineResult::Error(line.clone(), err);
2019-05-23 06:30:43 +02:00
}
Ok(val) => val,
};
2019-05-26 08:54:41 +02:00
debug!("=== Parsed ===");
debug!("{:#?}", result);
2019-05-24 09:29:16 +02:00
2019-08-29 03:12:10 +02:00
let mut pipeline = match classify_pipeline(&result, ctx, &Text::from(line)) {
Ok(pipeline) => pipeline,
Err(err) => return LineResult::Error(line.clone(), err),
};
2019-06-07 08:34:42 +02:00
match pipeline.commands.last() {
2019-06-07 09:54:52 +02:00
Some(ClassifiedCommand::External(_)) => {}
2019-08-02 21:15:07 +02:00
_ => pipeline
.commands
.push(ClassifiedCommand::Internal(InternalCommand {
2019-08-15 07:02:02 +02:00
command: whole_stream_command(autoview::Autoview),
name_tag: Tag::unknown(),
2019-08-02 21:15:07 +02:00
args: hir::Call::new(
Box::new(hir::Expression::synthetic_string("autoview")),
None,
None,
),
})),
2019-06-07 08:34:42 +02:00
}
2019-05-24 09:29:16 +02:00
let mut input = ClassifiedInputStream::new();
2019-05-26 08:54:41 +02:00
let mut iter = pipeline.commands.into_iter().peekable();
2019-05-24 09:29:16 +02:00
loop {
let item: Option<ClassifiedCommand> = iter.next();
let next: Option<&ClassifiedCommand> = iter.peek();
input = match (item, next) {
(None, _) => break,
2019-06-04 23:42:31 +02:00
(Some(ClassifiedCommand::Expr(_)), _) => {
2019-06-15 20:36:17 +02:00
return LineResult::Error(
line.clone(),
ShellError::unimplemented("Expression-only commands"),
)
2019-06-04 23:42:31 +02:00
}
(_, Some(ClassifiedCommand::Expr(_))) => {
2019-06-15 20:36:17 +02:00
return LineResult::Error(
line.clone(),
ShellError::unimplemented("Expression-only commands"),
)
2019-06-04 23:42:31 +02:00
}
2019-05-24 09:29:16 +02:00
(
Some(ClassifiedCommand::Internal(left)),
2019-06-07 08:34:42 +02:00
Some(ClassifiedCommand::External(_)),
2019-07-24 00:22:11 +02:00
) => match left.run(ctx, input, Text::from(line)).await {
2019-06-07 08:34:42 +02:00
Ok(val) => ClassifiedInputStream::from_input_stream(val),
2019-06-09 19:52:56 +02:00
Err(err) => return LineResult::Error(line.clone(), err),
2019-06-07 08:34:42 +02:00
},
2019-06-15 20:36:17 +02:00
(Some(ClassifiedCommand::Internal(left)), Some(_)) => {
2019-07-24 00:22:11 +02:00
match left.run(ctx, input, Text::from(line)).await {
2019-06-15 20:36:17 +02:00
Ok(val) => ClassifiedInputStream::from_input_stream(val),
Err(err) => return LineResult::Error(line.clone(), err),
}
}
2019-05-24 09:29:16 +02:00
(Some(ClassifiedCommand::Internal(left)), None) => {
2019-07-24 00:22:11 +02:00
match left.run(ctx, input, Text::from(line)).await {
2019-05-24 09:29:16 +02:00
Ok(val) => ClassifiedInputStream::from_input_stream(val),
2019-06-09 19:52:56 +02:00
Err(err) => return LineResult::Error(line.clone(), err),
2019-05-24 09:29:16 +02:00
}
}
(
Some(ClassifiedCommand::External(left)),
Some(ClassifiedCommand::External(_)),
) => match left.run(ctx, input, StreamNext::External).await {
2019-05-24 09:29:16 +02:00
Ok(val) => val,
2019-06-09 19:52:56 +02:00
Err(err) => return LineResult::Error(line.clone(), err),
2019-05-24 09:29:16 +02:00
},
2019-06-15 20:36:17 +02:00
(Some(ClassifiedCommand::External(left)), Some(_)) => {
match left.run(ctx, input, StreamNext::Internal).await {
Ok(val) => val,
Err(err) => return LineResult::Error(line.clone(), err),
}
}
2019-05-24 09:29:16 +02:00
(Some(ClassifiedCommand::External(left)), None) => {
match left.run(ctx, input, StreamNext::Last).await {
2019-05-24 09:29:16 +02:00
Ok(val) => val,
2019-06-09 19:52:56 +02:00
Err(err) => return LineResult::Error(line.clone(), err),
2019-05-24 09:29:16 +02:00
}
}
}
2019-05-23 06:30:43 +02:00
}
2019-06-09 19:52:56 +02:00
LineResult::Success(line.clone())
2019-05-23 06:30:43 +02:00
}
2019-06-15 20:36:17 +02:00
Err(ReadlineError::Interrupted) => LineResult::CtrlC,
2019-09-03 21:40:42 +02:00
Err(ReadlineError::Eof) => LineResult::Break,
2019-05-23 06:30:43 +02:00
Err(err) => {
println!("Error: {:?}", err);
LineResult::Break
}
}
}
2019-05-26 08:54:41 +02:00
fn classify_pipeline(
2019-06-22 05:43:37 +02:00
pipeline: &TokenNode,
2019-05-26 08:54:41 +02:00
context: &Context,
2019-06-22 22:46:16 +02:00
source: &Text,
2019-05-26 08:54:41 +02:00
) -> Result<ClassifiedPipeline, ShellError> {
2019-06-22 05:43:37 +02:00
let pipeline = pipeline.as_pipeline()?;
2019-06-23 19:35:43 +02:00
let Pipeline { parts, .. } = pipeline;
let commands: Result<Vec<_>, ShellError> = parts
2019-05-26 08:54:41 +02:00
.iter()
2019-06-22 22:46:16 +02:00
.map(|item| classify_command(&item, context, &source))
2019-05-26 08:54:41 +02:00
.collect();
Ok(ClassifiedPipeline {
commands: commands?,
})
}
2019-05-23 06:30:43 +02:00
fn classify_command(
2019-06-22 05:43:37 +02:00
command: &PipelineElement,
2019-05-23 06:30:43 +02:00
context: &Context,
2019-06-22 22:46:16 +02:00
source: &Text,
2019-05-23 06:30:43 +02:00
) -> Result<ClassifiedCommand, ShellError> {
2019-06-22 05:43:37 +02:00
let call = command.call();
2019-06-04 23:42:31 +02:00
2019-06-22 05:43:37 +02:00
match call {
// If the command starts with `^`, treat it as an external command no matter what
call if call.head().is_external() => {
let name_tag = call.head().expect_external();
let name = name_tag.slice(source);
Ok(external_command(call, source, name.tagged(name_tag)))
}
// Otherwise, if the command is a bare word, we'll need to triage it
2019-06-22 05:43:37 +02:00
call if call.head().is_bare() => {
let head = call.head();
let name = head.source(source);
match context.has_command(name) {
// if the command is in the registry, it's an internal command
true => {
2019-06-22 05:43:37 +02:00
let command = context.get_command(name);
2019-08-02 21:15:07 +02:00
let config = command.signature();
2019-07-12 21:22:08 +02:00
trace!(target: "nu::build_pipeline", "classifying {:?}", config);
2019-06-22 05:43:37 +02:00
Add support for ~ expansion This ended up being a bit of a yak shave. The basic idea in this commit is to expand `~` in paths, but only in paths. The way this is accomplished is by doing the expansion inside of the code that parses literal syntax for `SyntaxType::Path`. As a quick refresher: every command is entitled to expand its arguments in a custom way. While this could in theory be used for general-purpose macros, today the expansion facility is limited to syntactic hints. For example, the syntax `where cpu > 0` expands under the hood to `where { $it.cpu > 0 }`. This happens because the first argument to `where` is defined as a `SyntaxType::Block`, and the parser coerces binary expressions whose left-hand-side looks like a member into a block when the command is expecting one. This is mildly more magical than what most programming languages would do, but we believe that it makes sense to allow commands to fine-tune the syntax because of the domain nushell is in (command-line shells). The syntactic expansions supported by this facility are relatively limited. For example, we don't allow `$it` to become a bare word, simply because the command asks for a string in the relevant position. That would quickly become more confusing than it's worth. This PR adds a new `SyntaxType` rule: `SyntaxType::Path`. When a command declares a parameter as a `SyntaxType::Path`, string literals and bare words passed as an argument to that parameter are processed using the path expansion rules. Right now, that only means that `~` is expanded into the home directory, but additional rules are possible in the future. By restricting this expansion to a syntactic expansion when passed as an argument to a command expecting a path, we avoid making `~` a generally reserved character. This will also allow us to give good tab completion for paths with `~` characters in them when a command is expecting a path. In order to accomplish the above, this commit changes the parsing functions to take a `Context` instead of just a `CommandRegistry`. From the perspective of macro expansion, you can think of the `CommandRegistry` as a dictionary of in-scope macros, and the `Context` as the compile-time state used in expansion. This could gain additional functionality over time as we find more uses for the expansion system.
2019-08-26 21:21:03 +02:00
let args: hir::Call = config.parse_args(call, &context, source)?;
trace!(target: "nu::build_pipeline", "args :: {}", args.debug(source));
Ok(ClassifiedCommand::Internal(InternalCommand {
command,
name_tag: head.tag(),
args,
}))
2019-06-04 23:42:31 +02:00
}
// otherwise, it's an external command
false => Ok(external_command(call, source, name.tagged(head.tag()))),
2019-06-22 05:43:37 +02:00
}
2019-06-04 23:42:31 +02:00
}
2019-06-22 05:43:37 +02:00
// If the command is something else (like a number or a variable), that is currently unsupported.
// We might support `$somevar` as a curried command in the future.
call => Err(ShellError::invalid_command(call.head().tag())),
2019-05-23 06:30:43 +02:00
}
}
// Classify this command as an external command, which doesn't give special meaning
// to nu syntactic constructs, and passes all arguments to the external command as
// strings.
fn external_command(
call: &Tagged<CallNode>,
source: &Text,
name: Tagged<&str>,
) -> ClassifiedCommand {
let arg_list_strings: Vec<Tagged<String>> = match call.children() {
Some(args) => args
.iter()
.filter_map(|i| match i {
TokenNode::Whitespace(_) => None,
other => Some(other.as_external_arg(source).tagged(other.tag())),
})
.collect(),
None => vec![],
};
let (name, tag) = name.into_parts();
ClassifiedCommand::External(ExternalCommand {
name: name.to_string(),
name_tag: tag,
args: arg_list_strings,
})
}