Begin directory contrib docs and split commands (#3650)

* Begin directory contrib docs and split commands

* Fix unused import warning
This commit is contained in:
JT 2021-06-19 12:06:44 +12:00 committed by GitHub
parent 4140834e4c
commit a74d05061d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
261 changed files with 794 additions and 808 deletions

5
Cargo.lock generated
View File

@ -1,5 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "Inflector"
version = "0.11.4"
@ -3327,8 +3329,6 @@ dependencies = [
"htmlescape",
"ical",
"indexmap",
"itertools",
"lazy_static 1.4.0",
"log 0.4.14",
"meval",
"nu-ansi-term",
@ -3565,6 +3565,7 @@ dependencies = [
"hamcrest2",
"indexmap",
"itertools",
"lazy_static 1.4.0",
"log 0.4.14",
"nu-ansi-term",
"nu-data",

13
crates/README.md Normal file
View File

@ -0,0 +1,13 @@
# Nushell core libraries and plugins
These sub-crates form both the foundation for Nu and a set of plugins which extend Nu with additional functionality.
Foundational libraries are split into two kinds of crates:
* Core crates - those crates that work together to build the Nushell language engine
* Support crates - a set of crates that support the engine with additional features like JSON support, ANSI support, and more.
Plugins are likewise also split into two types:
* Core plugins - plugins that provide part of the default experience of Nu, including access to the system properties, processes, and web-connectivity features.
* Extra plugins - these plugins run a wide range of differnt capabilities like working with different file types, charting, viewing binary data, and more.

View File

@ -11,37 +11,37 @@ version = "0.32.1"
doctest = false
[dependencies]
nu-completion = { version = "0.32.1", path = "../nu-completion" }
nu-command = { version = "0.32.1", path = "../nu-command" }
nu-data = { version = "0.32.1", path = "../nu-data" }
nu-engine = { version = "0.32.1", path = "../nu-engine" }
nu-errors = { version = "0.32.1", path = "../nu-errors" }
nu-json = { version = "0.32.1", path = "../nu-json" }
nu-parser = { version = "0.32.1", path = "../nu-parser" }
nu-plugin = { version = "0.32.1", path = "../nu-plugin" }
nu-protocol = { version = "0.32.1", path = "../nu-protocol" }
nu-source = { version = "0.32.1", path = "../nu-source" }
nu-stream = { version = "0.32.1", path = "../nu-stream" }
nu-table = { version = "0.32.1", path = "../nu-table" }
nu-test-support = { version = "0.32.1", path = "../nu-test-support" }
nu-value-ext = { version = "0.32.1", path = "../nu-value-ext" }
nu-ansi-term = { version = "0.32.1", path = "../nu-ansi-term" }
nu-pretty-hex = { version = "0.32.1", path = "../nu-pretty-hex" }
nu-completion = { version="0.32.1", path="../nu-completion" }
nu-command = { version="0.32.1", path="../nu-command" }
nu-data = { version="0.32.1", path="../nu-data" }
nu-engine = { version="0.32.1", path="../nu-engine" }
nu-errors = { version="0.32.1", path="../nu-errors" }
nu-json = { version="0.32.1", path="../nu-json" }
nu-parser = { version="0.32.1", path="../nu-parser" }
nu-plugin = { version="0.32.1", path="../nu-plugin" }
nu-protocol = { version="0.32.1", path="../nu-protocol" }
nu-source = { version="0.32.1", path="../nu-source" }
nu-stream = { version="0.32.1", path="../nu-stream" }
nu-table = { version="0.32.1", path="../nu-table" }
nu-test-support = { version="0.32.1", path="../nu-test-support" }
nu-value-ext = { version="0.32.1", path="../nu-value-ext" }
nu-ansi-term = { version="0.32.1", path="../nu-ansi-term" }
nu-pretty-hex = { version="0.32.1", path="../nu-pretty-hex" }
Inflector = "0.11"
arboard = { version = "1.1.0", optional = true }
arboard = { version="1.1.0", optional=true }
async-recursion = "0.3.2"
async-trait = "0.1.42"
base64 = "0.13.0"
bigdecimal = { version = "0.2.0", features = ["serde"] }
bigdecimal = { version="0.2.0", features=["serde"] }
byte-unit = "4.0.9"
bytes = "1.0.1"
calamine = "0.17.0"
chrono = { version = "0.4.19", features = ["serde"] }
chrono = { version="0.4.19", features=["serde"] }
chrono-tz = "0.5.3"
codespan-reporting = "0.11.0"
csv = "1.1.5"
ctrlc = { version = "3.1.7", optional = true }
ctrlc = { version="3.1.7", optional=true }
derive-new = "0.5.8"
directories-next = "2.0.0"
dirs-next = "2.0.0"
@ -51,25 +51,23 @@ eml-parser = "0.1.0"
encoding_rs = "0.8.28"
filesize = "0.2.0"
fs_extra = "1.2.0"
futures = { version = "0.3.12", features = ["compat", "io-compat"] }
futures = { version="0.3.12", features=["compat", "io-compat"] }
futures-util = "0.3.12"
futures_codec = "0.4.1"
getset = "0.1.1"
glob = "0.3.0"
htmlescape = "0.3.1"
ical = "0.7.0"
indexmap = { version = "1.6.1", features = ["serde-1"] }
itertools = "0.10.0"
lazy_static = "1.*"
indexmap = { version="1.6.1", features=["serde-1"] }
log = "0.4.14"
pretty_env_logger = "0.4.0"
meval = "0.2.0"
num-bigint = { version = "0.3.1", features = ["serde"] }
num-format = { version = "0.4.0", features = ["with-num-bigint"] }
num-bigint = { version="0.3.1", features=["serde"] }
num-format = { version="0.4.0", features=["with-num-bigint"] }
num-traits = "0.2.14"
parking_lot = "0.11.1"
pin-utils = "0.1.0"
ptree = { version = "0.3.1", optional = true }
ptree = { version="0.3.1", optional=true }
query_interface = "0.3.5"
quick-xml = "0.21.0"
rand = "0.8.3"
@ -77,8 +75,8 @@ rayon = "1.5.0"
regex = "1.4.3"
roxmltree = "0.14.0"
rust-embed = "5.9.0"
rustyline = { version = "8.1.0", optional = true }
serde = { version = "1.0.123", features = ["derive"] }
rustyline = { version="8.1.0", optional=true }
serde = { version="1.0.123", features=["derive"] }
serde_bytes = "0.11.5"
serde_ini = "0.2.0"
serde_json = "1.0.61"
@ -90,18 +88,18 @@ strip-ansi-escapes = "0.1.0"
sxd-document = "0.3.2"
sxd-xpath = "0.4.2"
tempfile = "3.2.0"
term = { version = "0.7.0", optional = true }
term = { version="0.7.0", optional=true }
term_size = "0.3.2"
termcolor = "1.1.2"
titlecase = "1.1.0"
toml = "0.5.8"
trash = { version = "1.3.0", optional = true }
trash = { version="1.3.0", optional=true }
unicode-segmentation = "1.7.1"
url = "2.1.1"
uuid_crate = { package = "uuid", version = "0.8.2", features = ["v4"], optional = true }
which = { version = "4.0.2", optional = true }
zip = { version = "0.5.9", optional = true }
shadow-rs = { version = "0.5", default-features = false, optional = true }
uuid_crate = { package="uuid", version="0.8.2", features=["v4"], optional=true }
which = { version="4.0.2", optional=true }
zip = { version="0.5.9", optional=true }
shadow-rs = { version="0.5", default-features=false, optional=true }
[target.'cfg(unix)'.dependencies]
umask = "1.0.0"

4
crates/nu-cli/README.md Normal file
View File

@ -0,0 +1,4 @@
* nu-cli
This crate provides the fundamental needs when creating the Nushell interactive REPL. In it, you'll find features for interacting with the line editor (the piece which writes the prompt and takes input from the user), keybindings, handlers for the commandline arguments passed to the REPL as it starts up, and more.

View File

@ -5,7 +5,7 @@ mod options_parser;
pub use options::{CliOptions, NuScript, Options};
use options_parser::{NuParser, OptionsParser};
use nu_command::{commands::nu::Nu, utils::test_bins as binaries};
use nu_command::{commands::NuSignature as Nu, utils::test_bins as binaries};
use nu_engine::{get_full_help, EvaluationContext};
use nu_errors::ShellError;
use nu_protocol::hir::{Call, Expression, SpannedExpression, Synthetic};
@ -58,7 +58,7 @@ impl App {
if self.version() {
let context = self.parser.context();
let stream = nu_command::commands::version::version(nu_engine::CommandArgs {
let stream = nu_command::commands::version(nu_engine::CommandArgs {
context: context.clone(),
call_info: nu_engine::UnevaluatedCallInfo {
args: Call::new(

View File

@ -1,6 +1,6 @@
use super::Options;
use nu_command::commands::nu::{self, Nu};
use nu_command::commands::{loglevels, testbins, NuSignature as Nu};
use nu_command::commands::{Autoview, Pivot, Table, Version as NuVersion};
use nu_engine::{whole_stream_command, EvaluationContext};
use nu_errors::ShellError;
@ -72,7 +72,7 @@ impl OptionsParser for NuParser {
.map(|v| match k.as_ref() {
"testbin" => {
if let Ok(name) = v.as_string() {
if nu::testbins().iter().any(|n| name == *n) {
if testbins().iter().any(|n| name == *n) {
Some(v)
} else {
Some(
@ -90,7 +90,7 @@ impl OptionsParser for NuParser {
}
"loglevel" => {
if let Ok(name) = v.as_string() {
if nu::loglevels().iter().any(|n| name == *n) {
if loglevels().iter().any(|n| name == *n) {
Some(v)
} else {
Some(

View File

@ -1,5 +1,3 @@
use super::Nu;
use crate::line_editor::configure_ctrl_c;
use nu_ansi_term::Color;
use nu_engine::{maybe_print_errors, run_block, script::run_script_standalone, EvaluationContext};
@ -150,7 +148,7 @@ pub fn cli(
if !skip_welcome_message {
println!(
"Welcome to Nushell {} (type 'help' for more info)",
Nu::version()
nu_command::commands::core_version()
);
}

View File

@ -1,6 +0,0 @@
use crate::prelude::*;
use nu_errors::ShellError;
pub(crate) trait RenderView {
fn render_view(&self, host: &mut dyn Host) -> Result<(), ShellError>;
}

View File

@ -1,8 +1,3 @@
#![recursion_limit = "2048"]
#[macro_use]
mod prelude;
#[cfg(test)]
extern crate quickcheck;
#[cfg(test)]
@ -11,12 +6,11 @@ extern crate quickcheck_macros;
mod app;
mod cli;
mod format;
#[cfg(feature = "rustyline-support")]
mod keybinding;
mod line_editor;
#[cfg(feature = "rustyline-support")]
mod shell;
pub mod types;
#[cfg(feature = "rustyline-support")]
pub use crate::cli::cli;
@ -25,8 +19,7 @@ pub use crate::app::App;
pub use crate::cli::{parse_and_eval, register_plugins, run_script_file};
pub use nu_command::{
commands::default_context::create_default_context, commands::nu as Nu,
commands::Version as NuVersion,
commands::NuSignature as Nu, commands::Version as NuVersion, create_default_context,
};
pub use nu_data::config;
pub use nu_data::dict::TaggedListBuilder;

View File

@ -1,8 +1,9 @@
use nu_engine::EvaluationContext;
use nu_errors::ShellError;
use std::error::Error;
#[allow(unused_imports)]
use crate::prelude::*;
use std::sync::atomic::Ordering;
#[allow(unused_imports)]
use nu_engine::script::LineResult;
@ -31,7 +32,7 @@ pub fn convert_rustyline_result_to_string(input: Result<String, ReadlineError>)
Err(ReadlineError::Interrupted) => LineResult::CtrlC,
Err(ReadlineError::Eof) => LineResult::CtrlD,
Err(err) => {
outln!("Error: {:?}", err);
eprintln!("Error: {:?}", err);
LineResult::Break
}
}

View File

@ -1,42 +0,0 @@
#[macro_export]
macro_rules! return_err {
($expr:expr) => {
match $expr {
Err(_) => return,
Ok(expr) => expr,
};
};
}
#[macro_export]
macro_rules! trace_out_stream {
(target: $target:tt, $desc:tt = $expr:expr) => {{
if log::log_enabled!(target: $target, log::Level::Trace) {
let objects = $expr.inspect(move |o| {
trace!(
target: $target,
"{} = {}",
$desc,
match o {
Err(err) => format!("{:?}", err),
Ok(value) => value.display(),
}
);
});
nu_stream::OutputStream::new(objects)
} else {
$expr
}
}};
}
pub(crate) use nu_engine::Host;
#[allow(unused_imports)]
pub(crate) use nu_errors::ShellError;
#[allow(unused_imports)]
pub(crate) use nu_protocol::outln;
#[allow(unused_imports)]
pub(crate) use nu_value_ext::ValueExt;
#[allow(unused_imports)]
pub(crate) use std::sync::atomic::Ordering;

View File

@ -1,7 +1,212 @@
#![allow(clippy::module_inception)]
use nu_ansi_term::Color;
use nu_completion::NuCompleter;
use nu_engine::{DefaultPalette, EvaluationContext, Painter};
use nu_source::{Tag, Tagged};
use std::borrow::Cow::{self, Owned};
#[cfg(feature = "rustyline-support")]
pub(crate) mod helper;
pub struct Helper {
completer: NuCompleter,
hinter: Option<rustyline::hint::HistoryHinter>,
context: EvaluationContext,
pub colored_prompt: String,
validator: NuValidator,
}
#[cfg(feature = "rustyline-support")]
pub(crate) use helper::Helper;
impl Helper {
pub(crate) fn new(
context: EvaluationContext,
hinter: Option<rustyline::hint::HistoryHinter>,
) -> Helper {
Helper {
completer: NuCompleter {},
hinter,
context,
colored_prompt: String::new(),
validator: NuValidator {},
}
}
}
struct CompletionContext<'a>(&'a EvaluationContext);
impl<'a> nu_completion::CompletionContext for CompletionContext<'a> {
fn signature_registry(&self) -> &dyn nu_parser::ParserScope {
&self.0.scope
}
}
pub struct CompletionSuggestion(nu_completion::Suggestion);
impl rustyline::completion::Candidate for CompletionSuggestion {
fn display(&self) -> &str {
&self.0.display
}
fn replacement(&self) -> &str {
&self.0.replacement
}
}
impl rustyline::completion::Completer for Helper {
type Candidate = CompletionSuggestion;
fn complete(
&self,
line: &str,
pos: usize,
_ctx: &rustyline::Context<'_>,
) -> Result<(usize, Vec<Self::Candidate>), rustyline::error::ReadlineError> {
let ctx = CompletionContext(&self.context);
let (position, suggestions) = self.completer.complete(line, pos, &ctx);
let suggestions = suggestions.into_iter().map(CompletionSuggestion).collect();
Ok((position, suggestions))
}
fn update(&self, line: &mut rustyline::line_buffer::LineBuffer, start: usize, elected: &str) {
let end = line.pos();
line.replace(start..end, elected)
}
}
impl rustyline::hint::Hinter for Helper {
type Hint = String;
fn hint(&self, line: &str, pos: usize, ctx: &rustyline::Context<'_>) -> Option<String> {
self.hinter.as_ref().and_then(|h| h.hint(line, pos, ctx))
}
}
impl rustyline::highlight::Highlighter for Helper {
fn highlight_prompt<'b, 's: 'b, 'p: 'b>(
&'s self,
prompt: &'p str,
default: bool,
) -> Cow<'b, str> {
use std::borrow::Cow::Borrowed;
if default {
Borrowed(&self.colored_prompt)
} else {
Borrowed(prompt)
}
}
fn highlight_hint<'h>(&self, hint: &'h str) -> Cow<'h, str> {
Owned(Color::DarkGray.prefix().to_string() + hint + nu_ansi_term::ansi::RESET)
}
fn highlight<'l>(&self, line: &'l str, _pos: usize) -> Cow<'l, str> {
let cfg = &self.context.configs().lock();
if let Some(palette) = &cfg.syntax_config {
Painter::paint_string(line, &self.context.scope, palette)
} else {
Painter::paint_string(line, &self.context.scope, &DefaultPalette {})
}
}
fn highlight_char(&self, _line: &str, _pos: usize) -> bool {
true
}
}
impl rustyline::validate::Validator for Helper {
fn validate(
&self,
ctx: &mut rustyline::validate::ValidationContext,
) -> rustyline::Result<rustyline::validate::ValidationResult> {
self.validator.validate(ctx)
}
fn validate_while_typing(&self) -> bool {
self.validator.validate_while_typing()
}
}
struct NuValidator {}
impl rustyline::validate::Validator for NuValidator {
fn validate(
&self,
ctx: &mut rustyline::validate::ValidationContext,
) -> rustyline::Result<rustyline::validate::ValidationResult> {
let src = ctx.input();
let (tokens, err) = nu_parser::lex(src, 0);
if let Some(err) = err {
if let nu_errors::ParseErrorReason::Eof { .. } = err.reason() {
return Ok(rustyline::validate::ValidationResult::Incomplete);
}
}
let (_, err) = nu_parser::parse_block(tokens);
if let Some(err) = err {
if let nu_errors::ParseErrorReason::Eof { .. } = err.reason() {
return Ok(rustyline::validate::ValidationResult::Incomplete);
}
}
Ok(rustyline::validate::ValidationResult::Valid(None))
}
}
#[allow(unused)]
fn vec_tag<T>(input: Vec<Tagged<T>>) -> Option<Tag> {
let mut iter = input.iter();
let first = iter.next()?.tag.clone();
let last = iter.last();
Some(match last {
None => first,
Some(last) => first.until(&last.tag),
})
}
impl rustyline::Helper for Helper {}
#[cfg(test)]
mod tests {
use super::*;
use nu_engine::EvaluationContext;
use rustyline::completion::Completer;
use rustyline::line_buffer::LineBuffer;
#[ignore]
#[test]
fn closing_quote_should_replaced() {
let text = "cd \"folder with spaces\\subdirectory\\\"";
let replacement = "\"folder with spaces\\subdirectory\\subsubdirectory\\\"";
let mut buffer = LineBuffer::with_capacity(256);
buffer.insert_str(0, text);
buffer.set_pos(text.len() - 1);
let helper = Helper::new(EvaluationContext::basic(), None);
helper.update(&mut buffer, "cd ".len(), replacement);
assert_eq!(
buffer.as_str(),
"cd \"folder with spaces\\subdirectory\\subsubdirectory\\\""
);
}
#[ignore]
#[test]
fn replacement_with_cursor_in_text() {
let text = "cd \"folder with spaces\\subdirectory\\\"";
let replacement = "\"folder with spaces\\subdirectory\\subsubdirectory\\\"";
let mut buffer = LineBuffer::with_capacity(256);
buffer.insert_str(0, text);
buffer.set_pos(text.len() - 30);
let helper = Helper::new(EvaluationContext::basic(), None);
helper.update(&mut buffer, "cd ".len(), replacement);
assert_eq!(
buffer.as_str(),
"cd \"folder with spaces\\subdirectory\\subsubdirectory\\\""
);
}
}

View File

@ -1,212 +0,0 @@
use nu_ansi_term::Color;
use nu_completion::NuCompleter;
use nu_engine::{DefaultPalette, EvaluationContext, Painter};
use nu_source::{Tag, Tagged};
use std::borrow::Cow::{self, Owned};
pub struct Helper {
completer: NuCompleter,
hinter: Option<rustyline::hint::HistoryHinter>,
context: EvaluationContext,
pub colored_prompt: String,
validator: NuValidator,
}
impl Helper {
pub(crate) fn new(
context: EvaluationContext,
hinter: Option<rustyline::hint::HistoryHinter>,
) -> Helper {
Helper {
completer: NuCompleter {},
hinter,
context,
colored_prompt: String::new(),
validator: NuValidator {},
}
}
}
struct CompletionContext<'a>(&'a EvaluationContext);
impl<'a> nu_completion::CompletionContext for CompletionContext<'a> {
fn signature_registry(&self) -> &dyn nu_parser::ParserScope {
&self.0.scope
}
}
pub struct CompletionSuggestion(nu_completion::Suggestion);
impl rustyline::completion::Candidate for CompletionSuggestion {
fn display(&self) -> &str {
&self.0.display
}
fn replacement(&self) -> &str {
&self.0.replacement
}
}
impl rustyline::completion::Completer for Helper {
type Candidate = CompletionSuggestion;
fn complete(
&self,
line: &str,
pos: usize,
_ctx: &rustyline::Context<'_>,
) -> Result<(usize, Vec<Self::Candidate>), rustyline::error::ReadlineError> {
let ctx = CompletionContext(&self.context);
let (position, suggestions) = self.completer.complete(line, pos, &ctx);
let suggestions = suggestions.into_iter().map(CompletionSuggestion).collect();
Ok((position, suggestions))
}
fn update(&self, line: &mut rustyline::line_buffer::LineBuffer, start: usize, elected: &str) {
let end = line.pos();
line.replace(start..end, elected)
}
}
impl rustyline::hint::Hinter for Helper {
type Hint = String;
fn hint(&self, line: &str, pos: usize, ctx: &rustyline::Context<'_>) -> Option<String> {
self.hinter.as_ref().and_then(|h| h.hint(line, pos, ctx))
}
}
impl rustyline::highlight::Highlighter for Helper {
fn highlight_prompt<'b, 's: 'b, 'p: 'b>(
&'s self,
prompt: &'p str,
default: bool,
) -> Cow<'b, str> {
use std::borrow::Cow::Borrowed;
if default {
Borrowed(&self.colored_prompt)
} else {
Borrowed(prompt)
}
}
fn highlight_hint<'h>(&self, hint: &'h str) -> Cow<'h, str> {
Owned(Color::DarkGray.prefix().to_string() + hint + nu_ansi_term::ansi::RESET)
}
fn highlight<'l>(&self, line: &'l str, _pos: usize) -> Cow<'l, str> {
let cfg = &self.context.configs().lock();
if let Some(palette) = &cfg.syntax_config {
Painter::paint_string(line, &self.context.scope, palette)
} else {
Painter::paint_string(line, &self.context.scope, &DefaultPalette {})
}
}
fn highlight_char(&self, _line: &str, _pos: usize) -> bool {
true
}
}
impl rustyline::validate::Validator for Helper {
fn validate(
&self,
ctx: &mut rustyline::validate::ValidationContext,
) -> rustyline::Result<rustyline::validate::ValidationResult> {
self.validator.validate(ctx)
}
fn validate_while_typing(&self) -> bool {
self.validator.validate_while_typing()
}
}
struct NuValidator {}
impl rustyline::validate::Validator for NuValidator {
fn validate(
&self,
ctx: &mut rustyline::validate::ValidationContext,
) -> rustyline::Result<rustyline::validate::ValidationResult> {
let src = ctx.input();
let (tokens, err) = nu_parser::lex(src, 0);
if let Some(err) = err {
if let nu_errors::ParseErrorReason::Eof { .. } = err.reason() {
return Ok(rustyline::validate::ValidationResult::Incomplete);
}
}
let (_, err) = nu_parser::parse_block(tokens);
if let Some(err) = err {
if let nu_errors::ParseErrorReason::Eof { .. } = err.reason() {
return Ok(rustyline::validate::ValidationResult::Incomplete);
}
}
Ok(rustyline::validate::ValidationResult::Valid(None))
}
}
#[allow(unused)]
fn vec_tag<T>(input: Vec<Tagged<T>>) -> Option<Tag> {
let mut iter = input.iter();
let first = iter.next()?.tag.clone();
let last = iter.last();
Some(match last {
None => first,
Some(last) => first.until(&last.tag),
})
}
impl rustyline::Helper for Helper {}
#[cfg(test)]
mod tests {
use super::*;
use nu_engine::EvaluationContext;
use rustyline::completion::Completer;
use rustyline::line_buffer::LineBuffer;
#[ignore]
#[test]
fn closing_quote_should_replaced() {
let text = "cd \"folder with spaces\\subdirectory\\\"";
let replacement = "\"folder with spaces\\subdirectory\\subsubdirectory\\\"";
let mut buffer = LineBuffer::with_capacity(256);
buffer.insert_str(0, text);
buffer.set_pos(text.len() - 1);
let helper = Helper::new(EvaluationContext::basic(), None);
helper.update(&mut buffer, "cd ".len(), replacement);
assert_eq!(
buffer.as_str(),
"cd \"folder with spaces\\subdirectory\\subsubdirectory\\\""
);
}
#[ignore]
#[test]
fn replacement_with_cursor_in_text() {
let text = "cd \"folder with spaces\\subdirectory\\\"";
let replacement = "\"folder with spaces\\subdirectory\\subsubdirectory\\\"";
let mut buffer = LineBuffer::with_capacity(256);
buffer.insert_str(0, text);
buffer.set_pos(text.len() - 30);
let helper = Helper::new(EvaluationContext::basic(), None);
helper.update(&mut buffer, "cd ".len(), replacement);
assert_eq!(
buffer.as_str(),
"cd \"folder with spaces\\subdirectory\\subsubdirectory\\\""
);
}
}

View File

@ -0,0 +1,7 @@
# nu-command
The Nu command crate contains the full set of internal commands, that is, the commands that can be form the set of built-in commands in a Nushell engine.
The default set of commands that Nushell ships with can be found in the [default context](src/default_context.rs).
The commands themselves live in the [commands module](src/commands/).

View File

@ -1,390 +0,0 @@
mod from_delimited_data;
mod to_delimited_data;
pub(crate) mod alias;
pub(crate) mod all;
pub(crate) mod ansi;
pub(crate) mod any;
pub(crate) mod append;
pub(crate) mod args;
pub mod autoenv;
pub(crate) mod autoenv_trust;
pub(crate) mod autoenv_untrust;
pub(crate) mod autoview;
pub(crate) mod benchmark;
pub(crate) mod build_string;
pub(crate) mod cal;
pub(crate) mod cd;
pub(crate) mod char_;
pub(crate) mod chart;
pub(crate) mod classified;
#[cfg(feature = "clipboard-cli")]
pub(crate) mod clip;
pub(crate) mod compact;
pub(crate) mod config;
pub(crate) mod constants;
pub(crate) mod cp;
#[cfg(feature = "dataframe")]
pub(crate) mod dataframe;
pub(crate) mod date;
pub(crate) mod debug;
pub(crate) mod def;
pub(crate) mod default;
pub mod default_context;
pub(crate) mod describe;
pub(crate) mod do_;
pub(crate) mod drop;
pub(crate) mod du;
pub(crate) mod each;
pub(crate) mod echo;
pub(crate) mod empty;
pub(crate) mod enter;
pub(crate) mod every;
pub(crate) mod exec;
pub(crate) mod exit;
pub(crate) mod first;
pub(crate) mod flatten;
pub(crate) mod for_in;
pub(crate) mod format;
pub(crate) mod from;
pub(crate) mod from_csv;
pub(crate) mod from_eml;
pub(crate) mod from_ics;
pub(crate) mod from_ini;
pub(crate) mod from_json;
pub(crate) mod from_ods;
pub(crate) mod from_ssv;
pub(crate) mod from_toml;
pub(crate) mod from_tsv;
pub(crate) mod from_url;
pub(crate) mod from_vcf;
pub(crate) mod from_xlsx;
pub(crate) mod from_xml;
pub(crate) mod from_yaml;
pub(crate) mod get;
pub(crate) mod group_by;
pub(crate) mod group_by_date;
pub(crate) mod hash_;
pub(crate) mod headers;
pub(crate) mod help;
pub(crate) mod histogram;
pub(crate) mod history;
pub(crate) mod if_;
pub(crate) mod ignore;
pub(crate) mod insert;
pub(crate) mod into;
pub(crate) mod keep;
pub(crate) mod last;
pub(crate) mod length;
pub(crate) mod let_;
pub(crate) mod let_env;
pub(crate) mod lines;
pub(crate) mod load_env;
pub(crate) mod ls;
pub(crate) mod math;
pub(crate) mod merge;
pub(crate) mod mkdir;
pub(crate) mod move_;
pub(crate) mod next;
pub(crate) mod nth;
pub mod nu;
pub(crate) mod open;
pub(crate) mod parse;
pub(crate) mod path;
pub(crate) mod pivot;
pub(crate) mod prepend;
pub(crate) mod prev;
pub(crate) mod pwd;
pub(crate) mod random;
pub(crate) mod range;
pub(crate) mod reduce;
pub(crate) mod reject;
pub(crate) mod rename;
pub(crate) mod reverse;
pub(crate) mod rm;
pub(crate) mod roll;
pub(crate) mod rotate;
pub(crate) mod run_external;
pub(crate) mod save;
pub(crate) mod select;
pub(crate) mod seq;
pub(crate) mod seq_dates;
pub(crate) mod shells;
pub(crate) mod shuffle;
pub(crate) mod size;
pub(crate) mod skip;
pub(crate) mod sleep;
pub(crate) mod sort_by;
pub(crate) mod source;
pub(crate) mod split;
pub(crate) mod split_by;
pub(crate) mod str_;
pub(crate) mod table;
pub(crate) mod tags;
pub(crate) mod termsize;
pub(crate) mod to;
pub(crate) mod to_csv;
pub(crate) mod to_html;
pub(crate) mod to_json;
pub(crate) mod to_md;
pub(crate) mod to_toml;
pub(crate) mod to_tsv;
pub(crate) mod to_url;
pub(crate) mod to_xml;
pub(crate) mod to_yaml;
pub(crate) mod uniq;
pub(crate) mod update;
pub(crate) mod url_;
pub mod version;
pub(crate) mod where_;
pub(crate) mod which_;
pub(crate) mod with_env;
pub(crate) mod wrap;
pub use autoview::Autoview;
pub(crate) use cd::Cd;
pub(crate) use alias::Alias;
pub(crate) use ansi::Ansi;
pub(crate) use ansi::AnsiGradient;
pub(crate) use ansi::AnsiStrip;
pub(crate) use append::Command as Append;
pub(crate) use autoenv::Autoenv;
pub(crate) use autoenv_trust::AutoenvTrust;
pub(crate) use autoenv_untrust::AutoenvUnTrust;
pub(crate) use benchmark::Benchmark;
pub(crate) use build_string::BuildString;
pub(crate) use cal::Cal;
pub(crate) use char_::Char;
pub(crate) use chart::Chart;
pub(crate) use compact::Compact;
pub(crate) use config::{
Config, ConfigClear, ConfigGet, ConfigPath, ConfigRemove, ConfigSet, ConfigSetInto,
};
pub(crate) use cp::Cpy;
pub(crate) use date::{Date, DateFormat, DateListTimeZone, DateNow, DateToTable, DateToTimeZone};
pub(crate) use debug::Debug;
pub(crate) use def::Def;
pub(crate) use default::Default;
pub(crate) use describe::Describe;
pub(crate) use do_::Do;
pub(crate) use drop::{Drop, DropColumn};
pub(crate) use du::Du;
pub(crate) use each::Each;
pub(crate) use each::EachGroup;
pub(crate) use each::EachWindow;
pub(crate) use echo::Echo;
pub(crate) use empty::Command as Empty;
pub(crate) use for_in::ForIn;
pub(crate) use if_::If;
pub(crate) use into::Into;
pub(crate) use into::IntoBinary;
pub(crate) use into::IntoInt;
pub(crate) use into::IntoString;
pub(crate) use nu::NuPlugin;
pub(crate) use update::Command as Update;
pub(crate) mod kill;
pub(crate) use kill::Kill;
pub(crate) mod clear;
pub(crate) use clear::Clear;
pub(crate) mod touch;
pub(crate) use all::Command as All;
pub(crate) use any::Command as Any;
#[cfg(feature = "dataframe")]
pub(crate) use dataframe::{
DataFrame, DataFrameAggregate, DataFrameColumn, DataFrameDTypes, DataFrameDrop,
DataFrameDropDuplicates, DataFrameDropNulls, DataFrameDummies, DataFrameFilter, DataFrameGet,
DataFrameGroupBy, DataFrameHead, DataFrameJoin, DataFrameList, DataFrameLoad, DataFrameMelt,
DataFramePivot, DataFrameSample, DataFrameSelect, DataFrameSeriesRename, DataFrameShow,
DataFrameSlice, DataFrameSort, DataFrameTail, DataFrameToCsv, DataFrameToDF,
DataFrameToParquet, DataFrameToSeries, DataFrameWhere, DataFrameWithColumn,
};
pub(crate) use enter::Enter;
pub(crate) use every::Every;
pub(crate) use exec::Exec;
pub(crate) use exit::Exit;
pub(crate) use first::First;
pub(crate) use flatten::Command as Flatten;
pub(crate) use format::{FileSize, Format};
pub(crate) use from::From;
pub(crate) use from_csv::FromCsv;
pub(crate) use from_eml::FromEml;
pub(crate) use from_ics::FromIcs;
pub(crate) use from_ini::FromIni;
pub(crate) use from_json::FromJson;
pub(crate) use from_ods::FromOds;
pub(crate) use from_ssv::FromSsv;
pub(crate) use from_toml::FromToml;
pub(crate) use from_tsv::FromTsv;
pub(crate) use from_url::FromUrl;
pub(crate) use from_vcf::FromVcf;
pub(crate) use from_xlsx::FromXlsx;
pub(crate) use from_xml::FromXml;
pub(crate) use from_yaml::FromYaml;
pub(crate) use from_yaml::FromYml;
pub(crate) use get::Command as Get;
pub(crate) use group_by::Command as GroupBy;
pub(crate) use group_by_date::GroupByDate;
pub(crate) use hash_::{Hash, HashBase64, HashMd5};
pub(crate) use headers::Headers;
pub(crate) use help::Help;
pub(crate) use histogram::Histogram;
pub(crate) use history::History;
pub(crate) use ignore::Ignore;
pub(crate) use insert::Command as Insert;
pub(crate) use keep::{Keep, KeepUntil, KeepWhile};
pub(crate) use last::Last;
pub(crate) use length::Length;
pub(crate) use let_::Let;
pub(crate) use let_env::LetEnv;
pub(crate) use lines::Lines;
pub(crate) use load_env::LoadEnv;
pub(crate) use ls::Ls;
pub(crate) use math::{
Math, MathAbs, MathAverage, MathCeil, MathEval, MathFloor, MathMaximum, MathMedian,
MathMinimum, MathMode, MathProduct, MathRound, MathSqrt, MathStddev, MathSummation,
MathVariance,
};
pub(crate) use merge::Merge;
pub(crate) use mkdir::Mkdir;
pub(crate) use move_::{Move, Mv};
pub(crate) use next::Next;
pub(crate) use nth::Nth;
pub(crate) use open::Open;
pub(crate) use parse::Parse;
pub(crate) use path::{
PathBasename, PathCommand, PathDirname, PathExists, PathExpand, PathJoin, PathParse,
PathRelativeTo, PathSplit, PathType,
};
pub use pivot::Pivot;
pub(crate) use prepend::Prepend;
pub(crate) use prev::Previous;
pub(crate) use pwd::Pwd;
#[cfg(feature = "uuid_crate")]
pub(crate) use random::RandomUUID;
pub(crate) use random::{
Random, RandomBool, RandomChars, RandomDecimal, RandomDice, RandomInteger,
};
pub(crate) use range::Range;
pub(crate) use reduce::Reduce;
pub(crate) use reject::Reject;
pub(crate) use rename::Rename;
pub(crate) use reverse::Reverse;
pub(crate) use rm::Remove;
pub(crate) use roll::{Roll, RollColumn, RollUp};
pub(crate) use rotate::{Rotate, RotateCounterClockwise};
pub(crate) use run_external::RunExternalCommand;
pub(crate) use save::Save;
pub(crate) use select::Command as Select;
pub(crate) use seq::Seq;
pub(crate) use seq_dates::SeqDates;
pub(crate) use shells::Shells;
pub(crate) use shuffle::Shuffle;
pub(crate) use size::Size;
pub(crate) use skip::{Skip, SkipUntil, SkipWhile};
pub(crate) use sleep::Sleep;
pub(crate) use sort_by::SortBy;
pub(crate) use source::Source;
pub(crate) use split::{Split, SplitChars, SplitColumn, SplitRow};
pub(crate) use split_by::SplitBy;
pub(crate) use str_::{
Str, StrCamelCase, StrCapitalize, StrCollect, StrContains, StrDowncase, StrEndsWith,
StrFindReplace, StrIndexOf, StrKebabCase, StrLPad, StrLength, StrPascalCase, StrRPad,
StrReverse, StrScreamingSnakeCase, StrSnakeCase, StrStartsWith, StrSubstring, StrToDatetime,
StrToDecimal, StrToInteger, StrTrim, StrTrimLeft, StrTrimRight, StrUpcase,
};
pub use table::Table;
pub(crate) use tags::Tags;
pub(crate) use termsize::TermSize;
pub(crate) use to::To;
pub(crate) use to_csv::ToCsv;
pub(crate) use to_html::ToHtml;
pub(crate) use to_json::ToJson;
pub(crate) use to_md::Command as ToMarkdown;
pub(crate) use to_toml::ToToml;
pub(crate) use to_tsv::ToTsv;
pub(crate) use to_url::ToUrl;
pub(crate) use to_xml::ToXml;
pub(crate) use to_yaml::ToYaml;
pub(crate) use touch::Touch;
pub(crate) use uniq::Uniq;
pub(crate) use url_::{UrlCommand, UrlHost, UrlPath, UrlQuery, UrlScheme};
pub use version::Version;
pub(crate) use where_::Command as Where;
pub(crate) use which_::Which;
pub(crate) use with_env::WithEnv;
pub(crate) use wrap::Wrap;
#[cfg(test)]
mod tests {
use super::*;
use crate::examples::{test_anchors, test_examples};
use nu_engine::{whole_stream_command, Command};
use nu_errors::ShellError;
fn full_tests() -> Vec<Command> {
vec![
whole_stream_command(Append),
whole_stream_command(GroupBy),
whole_stream_command(Insert),
whole_stream_command(Move),
whole_stream_command(Update),
whole_stream_command(Empty),
// whole_stream_command(Select),
// whole_stream_command(Get),
// Str Command Suite
whole_stream_command(Str),
whole_stream_command(StrToDecimal),
whole_stream_command(StrToInteger),
whole_stream_command(StrDowncase),
whole_stream_command(StrUpcase),
whole_stream_command(StrCapitalize),
whole_stream_command(StrFindReplace),
whole_stream_command(StrSubstring),
whole_stream_command(StrToDatetime),
whole_stream_command(StrContains),
whole_stream_command(StrIndexOf),
whole_stream_command(StrTrim),
whole_stream_command(StrTrimLeft),
whole_stream_command(StrTrimRight),
whole_stream_command(StrStartsWith),
whole_stream_command(StrEndsWith),
//whole_stream_command(StrCollect),
whole_stream_command(StrLength),
whole_stream_command(StrLPad),
whole_stream_command(StrReverse),
whole_stream_command(StrRPad),
whole_stream_command(StrCamelCase),
whole_stream_command(StrPascalCase),
whole_stream_command(StrKebabCase),
whole_stream_command(StrSnakeCase),
whole_stream_command(StrScreamingSnakeCase),
whole_stream_command(ToMarkdown),
]
}
fn only_examples() -> Vec<Command> {
let mut commands = full_tests();
commands.extend(vec![whole_stream_command(Flatten)]);
commands
}
#[test]
fn examples_work_as_expected() -> Result<(), ShellError> {
for cmd in only_examples() {
println!("cmd: {}", cmd.name());
test_examples(cmd)?;
}
Ok(())
}
#[test]
fn tracks_metadata() -> Result<(), ShellError> {
for cmd in full_tests() {
test_anchors(cmd)?;
}
Ok(())
}
}

View File

@ -149,8 +149,13 @@ pub fn histogram(args: CommandArgs) -> Result<ActionStream, ShellError> {
"{}%",
// Some(2) < the number of digits
// true < group the digits
crate::commands::into::string::action(&percentage, &name, Some(2), true)?
.as_string()?
crate::commands::conversions::into::string::action(
&percentage,
&name,
Some(2),
true
)?
.as_string()?
);
fact.insert_untagged("percentage", UntaggedValue::string(fmt_percentage));

View File

@ -0,0 +1,5 @@
mod chart;
mod histogram;
pub use chart::Chart;
pub use histogram::Histogram;

View File

@ -43,7 +43,7 @@ pub fn get(args: CommandArgs) -> Result<OutputStream, ShellError> {
let result = if let Some(global_cfg) = &ctx.configs().lock().global_config {
let result = UntaggedValue::row(global_cfg.vars.clone()).into_value(&name);
let value = crate::commands::get::get_column_path(&column_path, &result)?;
let value = crate::commands::filters::get::get_column_path(&column_path, &result)?;
Ok(match value {
Value {
value: UntaggedValue::Table(list),

View File

@ -0,0 +1,3 @@
pub(crate) mod into;
pub use into::*;

View File

@ -0,0 +1,35 @@
mod alias;
mod debug;
mod def;
mod describe;
mod do_;
pub(crate) mod echo;
mod help;
mod history;
mod if_;
mod ignore;
mod let_;
mod nu_plugin;
mod nu_signature;
mod source;
mod tags;
mod version;
pub use self::nu_plugin::SubCommand as NuPlugin;
pub use self::nu_signature::{
loglevels, testbins, version as core_version, Command as NuSignature,
};
pub use alias::Alias;
pub use debug::Debug;
pub use def::Def;
pub use describe::Describe;
pub use do_::Do;
pub use echo::Echo;
pub use help::Help;
pub use history::History;
pub use if_::If;
pub use ignore::Ignore;
pub use let_::Let;
pub use source::Source;
pub use tags::Tags;
pub use version::{version, Version};

View File

@ -47,3 +47,23 @@ impl WholeStreamCommand for Command {
"Nu - A new type of shell."
}
}
pub fn version() -> &'static str {
env!("CARGO_PKG_VERSION")
}
pub fn testbins() -> Vec<String> {
vec![
"echo_env", "cococo", "iecho", "fail", "nonu", "chop", "repeater", "meow",
]
.into_iter()
.map(String::from)
.collect()
}
pub fn loglevels() -> Vec<String> {
vec!["error", "warn", "info", "debug", "trace"]
.into_iter()
.map(String::from)
.collect()
}

View File

@ -43,7 +43,7 @@ pub fn version(args: CommandArgs) -> Result<OutputStream, ShellError> {
indexmap.insert(
"version".to_string(),
UntaggedValue::string(super::nu::version()).into_value(&tag),
UntaggedValue::string(super::nu_signature::version()).into_value(&tag),
);
let branch: Option<&str> = Some(shadow::BRANCH).filter(|x| !x.is_empty());

View File

@ -6,9 +6,9 @@ use nu_protocol::SyntaxShape;
use nu_protocol::{Primitive, ReturnSuccess, Signature, UntaggedValue, Value};
use std::io::Read;
use std::{fs, path::PathBuf};
pub struct AutoenvUnTrust;
pub struct AutoenvUntrust;
impl WholeStreamCommand for AutoenvUnTrust {
impl WholeStreamCommand for AutoenvUntrust {
fn name(&self) -> &str {
"autoenv untrust"
}

View File

@ -0,0 +1,13 @@
mod autoenv;
mod autoenv_trust;
mod autoenv_untrust;
mod let_env;
mod load_env;
mod with_env;
pub use autoenv::Autoenv;
pub use autoenv_trust::AutoenvTrust;
pub use autoenv_untrust::AutoenvUntrust;
pub use let_env::LetEnv;
pub use load_env::LoadEnv;
pub use with_env::WithEnv;

View File

@ -0,0 +1,19 @@
mod cd;
mod cp;
mod ls;
mod mkdir;
mod mv;
pub(crate) mod open;
mod rm;
mod save;
mod touch;
pub use cd::Cd;
pub use cp::Cpy;
pub use ls::Ls;
pub use mkdir::Mkdir;
pub use mv::Mv;
pub use open::Open;
pub use rm::Remove;
pub use save::Save;
pub use touch::Touch;

View File

@ -1,4 +1,4 @@
use crate::commands::constants::BAT_LANGUAGES;
use crate::commands::viewers::BAT_LANGUAGES;
use crate::prelude::*;
use encoding_rs::{Encoding, UTF_8};

View File

@ -1,4 +1,4 @@
use crate::commands::each::process_row;
use crate::commands::filters::each::process_row;
use crate::prelude::*;
use nu_engine::WholeStreamCommand;
use nu_errors::ShellError;

View File

@ -1,4 +1,4 @@
use crate::commands::each::group::run_block_on_vec;
use crate::commands::filters::each::group::run_block_on_vec;
use crate::prelude::*;
use nu_engine::WholeStreamCommand;
//use itertools::Itertools;

View File

@ -144,7 +144,7 @@ pub fn group_by(args: CommandArgs) -> Result<OutputStream, ShellError> {
let run = block.clone();
let context = context.clone();
match crate::commands::each::process_row(
match crate::commands::filters::each::process_row(
run,
context,
value.clone(),

View File

@ -0,0 +1,79 @@
mod all;
mod any;
mod append;
mod compact;
mod default;
mod drop;
mod each;
mod empty;
mod every;
mod first;
mod flatten;
pub(crate) mod get;
mod group_by;
mod group_by_date;
mod headers;
mod insert;
mod keep;
mod last;
mod length;
mod merge;
mod move_;
mod nth;
mod pivot;
mod prepend;
mod range;
mod reduce;
mod reject;
mod rename;
mod reverse;
mod roll;
mod rotate;
mod select;
mod shuffle;
mod skip;
pub(crate) mod sort_by;
mod uniq;
mod update;
mod where_;
mod wrap;
pub use all::Command as All;
pub use any::Command as Any;
pub use append::Command as Append;
pub use compact::Compact;
pub use default::Default;
pub use drop::*;
pub use each::*;
pub use empty::Command as Empty;
pub use every::Every;
pub use first::First;
pub use flatten::Command as Flatten;
pub use get::Command as Get;
pub use group_by::Command as GroupBy;
pub use group_by_date::GroupByDate;
pub use headers::Headers;
pub use insert::Command as Insert;
pub use keep::*;
pub use last::Last;
pub use length::Length;
pub use merge::Merge;
pub use move_::Command as MoveColumn;
pub use nth::Nth;
pub use pivot::Pivot;
pub use prepend::Prepend;
pub use range::Range;
pub use reduce::Reduce;
pub use reject::Reject;
pub use rename::Rename;
pub use reverse::Reverse;
pub use roll::{Roll, RollColumn, RollUp};
pub use rotate::{Rotate, RotateCounterClockwise};
pub use select::Command as Select;
pub use shuffle::Shuffle;
pub use skip::{Skip, SkipUntil, SkipWhile};
pub use sort_by::SortBy;
pub use uniq::Uniq;
pub use update::Command as Update;
pub use where_::Command as Where;
pub use wrap::Wrap;

View File

@ -1,4 +1,4 @@
use crate::commands::each;
use super::each;
use crate::prelude::*;
use nu_engine::run_block;
use nu_engine::WholeStreamCommand;

Some files were not shown because too many files have changed in this diff Show More