Remove all unused code

This commit is contained in:
Dirkjan Ochtman 2019-08-26 21:10:05 +02:00
parent 3514c77aac
commit 0167c826f2
35 changed files with 167 additions and 961 deletions

View File

@ -286,14 +286,6 @@ pub async fn cli() -> Result<(), Box<dyn Error>> {
LineResult::Break => {
break;
}
LineResult::FatalError(_, err) => {
context
.host
.lock()
.unwrap()
.stdout(&format!("A surprising fatal error occurred.\n{:?}", err));
}
}
ctrlcbreak = false;
}
@ -307,9 +299,6 @@ enum LineResult {
Error(String, ShellError),
CtrlC,
Break,
#[allow(unused)]
FatalError(String, ShellError),
}
impl std::ops::Try for LineResult {
@ -322,7 +311,6 @@ impl std::ops::Try for LineResult {
LineResult::Error(string, err) => Err((string, err)),
LineResult::Break => Ok(None),
LineResult::CtrlC => Ok(None),
LineResult::FatalError(string, err) => Err((string, err)),
}
}
fn from_error(v: (String, ShellError)) -> Self {
@ -382,20 +370,6 @@ async fn process_line(readline: Result<String, ReadlineError>, ctx: &mut Context
input = match (item, next) {
(None, _) => break,
(Some(ClassifiedCommand::Expr(_)), _) => {
return LineResult::Error(
line.clone(),
ShellError::unimplemented("Expression-only commands"),
)
}
(_, Some(ClassifiedCommand::Expr(_))) => {
return LineResult::Error(
line.clone(),
ShellError::unimplemented("Expression-only commands"),
)
}
(
Some(ClassifiedCommand::Internal(left)),
Some(ClassifiedCommand::External(_)),

View File

@ -1,7 +1,6 @@
#[macro_use]
crate mod macros;
crate mod args;
crate mod autoview;
crate mod cd;
crate mod classified;
@ -35,8 +34,8 @@ crate mod pick;
crate mod plugin;
crate mod prev;
crate mod ps;
crate mod reverse;
crate mod reject;
crate mod reverse;
crate mod rm;
crate mod save;
crate mod shells;

View File

@ -1,19 +0,0 @@
use crate::object::Value;
#[allow(unused)]
#[derive(Debug)]
pub enum LogLevel {
Trace,
Debug,
Info,
Warn,
Error,
Fatal,
}
#[allow(unused)]
#[derive(Debug)]
pub struct LogItem {
level: LogLevel,
value: Value,
}

View File

@ -1,5 +1,5 @@
use crate::commands::Command;
use crate::parser::{hir, TokenNode};
use crate::parser::hir;
use crate::prelude::*;
use bytes::{BufMut, BytesMut};
use futures::stream::StreamExt;
@ -78,23 +78,10 @@ crate struct ClassifiedPipeline {
}
crate enum ClassifiedCommand {
#[allow(unused)]
Expr(TokenNode),
Internal(InternalCommand),
External(ExternalCommand),
}
impl ClassifiedCommand {
#[allow(unused)]
pub fn span(&self) -> Span {
match self {
ClassifiedCommand::Expr(token) => token.span(),
ClassifiedCommand::Internal(internal) => internal.name_span.into(),
ClassifiedCommand::External(external) => external.name_span.into(),
}
}
}
crate struct InternalCommand {
crate command: Arc<Command>,
crate name_span: Span,
@ -219,7 +206,6 @@ impl InternalCommand {
crate struct ExternalCommand {
crate name: String,
#[allow(unused)]
crate name_span: Span,
crate args: Vec<Tagged<String>>,
}

View File

@ -10,7 +10,6 @@ use getset::Getters;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::ops::Deref;
use std::path::PathBuf;
use uuid::Uuid;
#[derive(Deserialize, Serialize, Debug, Clone)]
@ -219,12 +218,6 @@ pub struct RunnablePerItemContext {
pub name: Span,
}
impl RunnablePerItemContext {
pub fn cwd(&self) -> PathBuf {
PathBuf::from(self.shell_manager.path())
}
}
pub struct RunnableContext {
pub input: InputStream,
pub shell_manager: ShellManager,
@ -235,11 +228,6 @@ pub struct RunnableContext {
}
impl RunnableContext {
#[allow(unused)]
pub fn cwd(&self) -> PathBuf {
PathBuf::from(self.shell_manager.path())
}
pub fn expect_command(&self, name: &str) -> Arc<Command> {
self.commands
.get_command(name)
@ -333,39 +321,6 @@ impl EvaluatedWholeStreamCommandArgs {
}
}
#[derive(Getters)]
#[get = "pub"]
pub struct EvaluatedFilterCommandArgs {
args: EvaluatedCommandArgs,
#[allow(unused)]
input: Tagged<Value>,
}
impl Deref for EvaluatedFilterCommandArgs {
type Target = EvaluatedCommandArgs;
fn deref(&self) -> &Self::Target {
&self.args
}
}
impl EvaluatedFilterCommandArgs {
pub fn new(
host: Arc<Mutex<dyn Host>>,
shell_manager: ShellManager,
call_info: CallInfo,
input: Tagged<Value>,
) -> EvaluatedFilterCommandArgs {
EvaluatedFilterCommandArgs {
args: EvaluatedCommandArgs {
host,
shell_manager,
call_info,
},
input,
}
}
}
#[derive(Getters, new)]
#[get = "crate"]
pub struct EvaluatedCommandArgs {
@ -404,7 +359,6 @@ impl EvaluatedCommandArgs {
}
}
#[allow(unused)]
pub fn has(&self, name: &str) -> bool {
self.call_info.args.has(name)
}
@ -579,60 +533,6 @@ impl Command {
}
}
#[allow(unused)]
pub struct FnFilterCommand {
name: String,
func: fn(EvaluatedFilterCommandArgs) -> Result<OutputStream, ShellError>,
}
impl WholeStreamCommand for FnFilterCommand {
fn name(&self) -> &str {
&self.name
}
fn run(
&self,
args: CommandArgs,
registry: &registry::CommandRegistry,
) -> Result<OutputStream, ShellError> {
let CommandArgs {
host,
shell_manager,
call_info,
input,
} = args;
let host: Arc<Mutex<dyn Host>> = host.clone();
let shell_manager = shell_manager.clone();
let registry: registry::CommandRegistry = registry.clone();
let func = self.func;
let result = input.values.map(move |it| {
let registry = registry.clone();
let call_info = match call_info
.clone()
.evaluate(&registry, &Scope::it_value(it.clone()))
{
Err(err) => return OutputStream::from(vec![Err(err)]).values,
Ok(args) => args,
};
let args =
EvaluatedFilterCommandArgs::new(host.clone(), shell_manager.clone(), call_info, it);
match func(args) {
Err(err) => return OutputStream::from(vec![Err(err)]).values,
Ok(stream) => stream.values,
}
});
let result = result.flatten();
let result: BoxStream<ReturnValue> = result.boxed();
Ok(result.into())
}
}
pub fn whole_stream_command(command: impl WholeStreamCommand + 'static) -> Arc<Command> {
Arc::new(Command::WholeStream(Arc::new(command)))
}
@ -640,14 +540,3 @@ pub fn whole_stream_command(command: impl WholeStreamCommand + 'static) -> Arc<C
pub fn per_item_command(command: impl PerItemCommand + 'static) -> Arc<Command> {
Arc::new(Command::PerItem(Arc::new(command)))
}
#[allow(unused)]
pub fn filter(
name: &str,
func: fn(EvaluatedFilterCommandArgs) -> Result<OutputStream, ShellError>,
) -> Arc<Command> {
Arc::new(Command::WholeStream(Arc::new(FnFilterCommand {
name: name.to_string(),
func,
})))
}

View File

@ -2,7 +2,7 @@ use crate::commands::WholeStreamCommand;
use crate::object::base::OF64;
use crate::object::{Primitive, TaggedDictBuilder, Value};
use crate::prelude::*;
use bson::{decode_document, Bson, spec::BinarySubtype};
use bson::{decode_document, spec::BinarySubtype, Bson};
pub struct FromBSON;
@ -47,71 +47,72 @@ fn convert_bson_value_to_nu_value(v: &Bson, tag: impl Into<Tag>) -> Tagged<Value
Bson::Boolean(b) => Value::Primitive(Primitive::Boolean(*b)).tagged(tag),
Bson::Null => Value::Primitive(Primitive::String(String::from(""))).tagged(tag),
Bson::RegExp(r, opts) => {
let mut collected = TaggedDictBuilder::new(tag);
collected.insert_tagged(
"$regex".to_string(),
Value::Primitive(Primitive::String(String::from(r))).tagged(tag),
);
collected.insert_tagged(
"$options".to_string(),
Value::Primitive(Primitive::String(String::from(opts))).tagged(tag),
);
collected.into_tagged_value()
let mut collected = TaggedDictBuilder::new(tag);
collected.insert_tagged(
"$regex".to_string(),
Value::Primitive(Primitive::String(String::from(r))).tagged(tag),
);
collected.insert_tagged(
"$options".to_string(),
Value::Primitive(Primitive::String(String::from(opts))).tagged(tag),
);
collected.into_tagged_value()
}
Bson::I32(n) => Value::Primitive(Primitive::Int(*n as i64)).tagged(tag),
Bson::I64(n) => Value::Primitive(Primitive::Int(*n as i64)).tagged(tag),
Bson::JavaScriptCode(js) => {
let mut collected = TaggedDictBuilder::new(tag);
collected.insert_tagged(
"$javascript".to_string(),
Value::Primitive(Primitive::String(String::from(js))).tagged(tag),
);
collected.into_tagged_value()
let mut collected = TaggedDictBuilder::new(tag);
collected.insert_tagged(
"$javascript".to_string(),
Value::Primitive(Primitive::String(String::from(js))).tagged(tag),
);
collected.into_tagged_value()
}
Bson::JavaScriptCodeWithScope(js, doc) => {
let mut collected = TaggedDictBuilder::new(tag);
collected.insert_tagged(
"$javascript".to_string(),
Value::Primitive(Primitive::String(String::from(js))).tagged(tag),
);
collected.insert_tagged(
"$scope".to_string(),
convert_bson_value_to_nu_value(&Bson::Document(doc.to_owned()), tag),
);
collected.into_tagged_value()
let mut collected = TaggedDictBuilder::new(tag);
collected.insert_tagged(
"$javascript".to_string(),
Value::Primitive(Primitive::String(String::from(js))).tagged(tag),
);
collected.insert_tagged(
"$scope".to_string(),
convert_bson_value_to_nu_value(&Bson::Document(doc.to_owned()), tag),
);
collected.into_tagged_value()
}
Bson::TimeStamp(ts) => {
let mut collected = TaggedDictBuilder::new(tag);
collected.insert_tagged(
"$timestamp".to_string(),
Value::Primitive(Primitive::Int(*ts as i64)).tagged(tag),
);
collected.into_tagged_value()
let mut collected = TaggedDictBuilder::new(tag);
collected.insert_tagged(
"$timestamp".to_string(),
Value::Primitive(Primitive::Int(*ts as i64)).tagged(tag),
);
collected.into_tagged_value()
}
Bson::Binary(bst, bytes) => {
let mut collected = TaggedDictBuilder::new(tag);
collected.insert_tagged(
"$binary_subtype".to_string(),
match bst {
BinarySubtype::UserDefined(u) => Value::Primitive(Primitive::Int(*u as i64)),
_ => Value::Primitive(Primitive::String(binary_subtype_to_string(*bst))),
}.tagged(tag)
);
collected.insert_tagged(
"$binary".to_string(),
Value::Binary(bytes.to_owned()).tagged(tag),
);
collected.into_tagged_value()
let mut collected = TaggedDictBuilder::new(tag);
collected.insert_tagged(
"$binary_subtype".to_string(),
match bst {
BinarySubtype::UserDefined(u) => Value::Primitive(Primitive::Int(*u as i64)),
_ => Value::Primitive(Primitive::String(binary_subtype_to_string(*bst))),
}
.tagged(tag),
);
collected.insert_tagged(
"$binary".to_string(),
Value::Binary(bytes.to_owned()).tagged(tag),
);
collected.into_tagged_value()
}
Bson::ObjectId(obj_id) => Value::Primitive(Primitive::String(obj_id.to_hex())).tagged(tag),
Bson::UtcDatetime(dt) => Value::Primitive(Primitive::Date(*dt)).tagged(tag),
Bson::Symbol(s) => {
let mut collected = TaggedDictBuilder::new(tag);
collected.insert_tagged(
"$symbol".to_string(),
Value::Primitive(Primitive::String(String::from(s))).tagged(tag),
);
collected.into_tagged_value()
let mut collected = TaggedDictBuilder::new(tag);
collected.insert_tagged(
"$symbol".to_string(),
Value::Primitive(Primitive::String(String::from(s))).tagged(tag),
);
collected.into_tagged_value()
}
}
}
@ -125,7 +126,8 @@ fn binary_subtype_to_string(bst: BinarySubtype) -> String {
BinarySubtype::Uuid => "uuid",
BinarySubtype::Md5 => "md5",
_ => unreachable!(),
}.to_string()
}
.to_string()
}
#[derive(Debug)]

View File

@ -44,7 +44,7 @@ fn last(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, S
"Value is too low",
"expected a positive integer",
args.expect_nth(0)?.span(),
))
));
}
let stream = async_stream_block! {

View File

@ -1,11 +1,3 @@
#[doc(hidden)]
#[allow(unused)]
macro_rules! named_type {
($name:ident) => {
$crate::parser::registry::NamedType::$($name)*
}
}
#[macro_export]
macro_rules! command {
(
@ -63,7 +55,6 @@ macro_rules! command {
named: {
use $crate::parser::registry::NamedType;
#[allow(unused_mut)]
let mut named: indexmap::IndexMap<String, NamedType> = indexmap::IndexMap::new();
$(

View File

@ -426,14 +426,16 @@ pub fn parse_string_as_value(
name_span: Span,
) -> Result<Tagged<Value>, ShellError> {
match extension {
Some(x) if x == "csv" => crate::commands::from_csv::from_csv_string_to_value(
contents,
false,
contents_tag,
)
.map_err(move |_| {
ShellError::labeled_error("Could not open as CSV", "could not open as CSV", name_span)
}),
Some(x) if x == "csv" => {
crate::commands::from_csv::from_csv_string_to_value(contents, false, contents_tag)
.map_err(move |_| {
ShellError::labeled_error(
"Could not open as CSV",
"could not open as CSV",
name_span,
)
})
}
Some(x) if x == "toml" => {
crate::commands::from_toml::from_toml_string_to_value(contents, contents_tag).map_err(
move |_| {
@ -507,9 +509,9 @@ pub fn parse_binary_as_value(
crate::commands::from_bson::from_bson_bytes_to_value(contents, contents_tag).map_err(
move |_| {
ShellError::labeled_error(
"Could not open as BSON",
"could not open as BSON",
name_span,
"Could not open as BSON",
"could not open as BSON",
name_span,
)
},
)

View File

@ -46,9 +46,7 @@ fn sort_by(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream
.collect::<Vec<Option<Tagged<Value>>>>()
};
if reverse {
vec.sort_by_cached_key(|item| {
std::cmp::Reverse(calc_key(item))
});
vec.sort_by_cached_key(|item| std::cmp::Reverse(calc_key(item)));
} else {
vec.sort_by_cached_key(calc_key);
}

View File

@ -1,4 +1,3 @@
#[allow(unused)]
use crate::prelude::*;
use ansi_term::Color;
@ -349,24 +348,6 @@ pub struct ShellDiagnostic {
crate diagnostic: Diagnostic<Span>,
}
impl ShellDiagnostic {
#[allow(unused)]
crate fn simple_diagnostic(
span: impl Into<Span>,
source: impl Into<String>,
) -> ShellDiagnostic {
use language_reporting::*;
let span = span.into();
let source = source.into();
let diagnostic =
Diagnostic::new(Severity::Error, "Parse error").with_label(Label::new_primary(span));
ShellDiagnostic { diagnostic }
}
}
impl PartialEq for ShellDiagnostic {
fn eq(&self, _other: &ShellDiagnostic) -> bool {
false

View File

@ -1,14 +1,8 @@
crate mod entries;
crate mod generic;
crate mod list;
crate mod table;
crate mod vtable;
use crate::prelude::*;
crate use entries::EntriesView;
#[allow(unused)]
crate use generic::GenericView;
crate use table::TableView;
crate use vtable::VTableView;

View File

@ -1,47 +0,0 @@
use crate::format::RenderView;
use crate::prelude::*;
use derive_new::new;
// An entries list is printed like this:
//
// name : ...
// name2 : ...
// another_name : ...
#[derive(new)]
pub struct EntriesView {
entries: Vec<(String, String)>,
}
impl EntriesView {
crate fn from_value(value: &Value) -> EntriesView {
let descs = value.data_descriptors();
let mut entries = vec![];
for desc in descs {
let value = value.get_data(&desc);
let formatted_value = value.borrow().format_leaf(None);
entries.push((desc.clone(), formatted_value))
}
EntriesView::new(entries)
}
}
impl RenderView for EntriesView {
fn render_view(&self, _host: &mut dyn Host) -> Result<(), ShellError> {
if self.entries.len() == 0 {
return Ok(());
}
let max_name_size: usize = self.entries.iter().map(|(n, _)| n.len()).max().unwrap();
for (name, value) in &self.entries {
println!("{:width$} : {}", name, value, width = max_name_size)
}
Ok(())
}
}

View File

@ -1,45 +0,0 @@
use crate::format::{EntriesView, RenderView, TableView};
use crate::object::Value;
use crate::prelude::*;
use derive_new::new;
// A list is printed one line at a time with an optional separator between groups
#[derive(new)]
pub struct GenericView<'value> {
value: &'value Value,
}
impl RenderView for GenericView<'value> {
fn render_view(&self, host: &mut dyn Host) -> Result<(), ShellError> {
match self.value {
Value::Primitive(p) => Ok(host.stdout(&p.format(None))),
Value::List(l) => {
let view = TableView::from_list(l);
if let Some(view) = view {
view.render_view(host)?;
}
Ok(())
}
o @ Value::Object(_) => {
let view = EntriesView::from_value(o);
view.render_view(host)?;
Ok(())
}
b @ Value::Block(_) => {
let printed = b.format_leaf(None);
let view = EntriesView::from_value(&Value::string(printed));
view.render_view(host)?;
Ok(())
}
Value::Binary(_) => {
host.stdout("<Binary>");
Ok(())
}
}
}
}

View File

@ -1,22 +0,0 @@
use crate::format::RenderView;
use crate::prelude::*;
use derive_new::new;
// A list is printed one line at a time with an optional separator between groups
#[allow(unused)]
#[derive(new)]
pub struct ListView {
list: Vec<Vec<String>>,
sep: String,
}
impl RenderView for ListView {
fn render_view(&self, host: &mut dyn Host) -> Result<(), ShellError> {
for output in &self.list {
let string: String = output.iter().map(|l| format!("{}\n", l)).collect();
host.stdout(&format!("{}{}", string, self.sep));
}
Ok(())
}
}

View File

@ -7,15 +7,13 @@ pub fn current_branch() -> Option<String> {
Ok(repo) => {
let r = repo.head();
match r {
Ok(r) => {
match r.shorthand() {
Some(s) => Some(s.to_string()),
None => None,
}
Ok(r) => match r.shorthand() {
Some(s) => Some(s.to_string()),
None => None,
},
_ => None
_ => None,
}
},
_ => None
}
_ => None,
}
}

View File

@ -7,7 +7,6 @@ crate mod meta;
crate mod process;
crate mod types;
#[allow(unused)]
crate use base::{Block, Primitive, Switch, Value};
crate use base::{Primitive, Value};
crate use dict::{Dictionary, TaggedDictBuilder};
crate use files::dir_entry_dict;

View File

@ -35,7 +35,6 @@ impl From<f64> for OF64 {
pub enum Primitive {
Nothing,
Int(i64),
#[allow(unused)]
Float(OF64),
Bytes(u64),
String(String),
@ -122,10 +121,8 @@ impl Primitive {
pub fn style(&self) -> &'static str {
match self {
Primitive::Bytes(0) => "c", // centre 'missing' indicator
Primitive::Int(_) |
Primitive::Bytes(_) |
Primitive::Float(_) => "r",
_ => ""
Primitive::Int(_) | Primitive::Bytes(_) | Primitive::Float(_) => "r",
_ => "",
}
}
}
@ -174,7 +171,6 @@ pub enum Value {
#[serde(with = "serde_bytes")]
Binary(Vec<u8>),
List(Vec<Tagged<Value>>),
#[allow(unused)]
Block(Block),
}
@ -251,16 +247,6 @@ pub enum Switch {
Absent,
}
impl Switch {
#[allow(unused)]
pub fn is_present(&self) -> bool {
match self {
Switch::Present => true,
Switch::Absent => false,
}
}
}
impl std::convert::TryFrom<Option<&'a Tagged<Value>>> for Switch {
type Error = ShellError;
@ -332,14 +318,6 @@ impl Value {
}
}
#[allow(unused)]
crate fn get_data_by_index(&'a self, idx: usize) -> Option<&Tagged<Value>> {
match self {
Value::List(l) => l.iter().nth(idx),
_ => None,
}
}
pub fn get_data_by_path(&'a self, tag: Tag, path: &str) -> Option<Tagged<&Value>> {
let mut current = self;
for p in path.split(".") {
@ -472,11 +450,10 @@ impl Value {
crate fn style_leaf(&self) -> &'static str {
match self {
Value::Primitive(p) => p.style(),
_ => ""
_ => "",
}
}
#[allow(unused)]
crate fn compare(&self, operator: &Operator, other: &Value) -> Result<bool, (String, String)> {
match operator {
_ => {
@ -503,24 +480,6 @@ impl Value {
}
}
#[allow(unused)]
crate fn is_string(&self, expected: &str) -> bool {
match self {
Value::Primitive(Primitive::String(s)) if s == expected => true,
other => false,
}
}
// crate fn as_pair(&self) -> Result<(Tagged<Value>, Tagged<Value>), ShellError> {
// match self {
// Value::List(list) if list.len() == 2 => Ok((list[0].clone(), list[1].clone())),
// other => Err(ShellError::string(format!(
// "Expected pair, got {:?}",
// other
// ))),
// }
// }
crate fn as_string(&self) -> Result<String, ShellError> {
match self {
Value::Primitive(Primitive::String(s)) => Ok(s.clone()),
@ -579,7 +538,6 @@ impl Value {
Value::Primitive(Primitive::Date(s.into()))
}
#[allow(unused)]
pub fn date_from_str(s: &str) -> Result<Value, ShellError> {
let date = DateTime::parse_from_rfc3339(s)
.map_err(|err| ShellError::string(&format!("Date parse error: {}", err)))?;
@ -624,87 +582,6 @@ crate fn reject_fields(obj: &Value, fields: &[String], tag: impl Into<Tag>) -> T
out.into_tagged_value()
}
#[allow(unused)]
crate fn find(obj: &Value, field: &str, op: &Operator, rhs: &Value) -> bool {
let descs = obj.data_descriptors();
match descs.iter().find(|d| *d == field) {
None => false,
Some(desc) => {
let v = obj.get_data(desc).borrow().clone();
match v {
Value::Primitive(Primitive::Boolean(b)) => match (op, rhs) {
(Operator::Equal, Value::Primitive(Primitive::Boolean(b2))) => b == *b2,
(Operator::NotEqual, Value::Primitive(Primitive::Boolean(b2))) => b != *b2,
_ => false,
},
Value::Primitive(Primitive::Bytes(i)) => match (op, rhs) {
(Operator::LessThan, Value::Primitive(Primitive::Int(i2))) => i < (*i2 as u64),
(Operator::GreaterThan, Value::Primitive(Primitive::Int(i2))) => {
i > (*i2 as u64)
}
(Operator::LessThanOrEqual, Value::Primitive(Primitive::Int(i2))) => {
i <= (*i2 as u64)
}
(Operator::GreaterThanOrEqual, Value::Primitive(Primitive::Int(i2))) => {
i >= (*i2 as u64)
}
(Operator::Equal, Value::Primitive(Primitive::Int(i2))) => i == (*i2 as u64),
(Operator::NotEqual, Value::Primitive(Primitive::Int(i2))) => i != (*i2 as u64),
_ => false,
},
Value::Primitive(Primitive::Int(i)) => match (op, rhs) {
(Operator::LessThan, Value::Primitive(Primitive::Int(i2))) => i < *i2,
(Operator::GreaterThan, Value::Primitive(Primitive::Int(i2))) => i > *i2,
(Operator::LessThanOrEqual, Value::Primitive(Primitive::Int(i2))) => i <= *i2,
(Operator::GreaterThanOrEqual, Value::Primitive(Primitive::Int(i2))) => {
i >= *i2
}
(Operator::Equal, Value::Primitive(Primitive::Int(i2))) => i == *i2,
(Operator::NotEqual, Value::Primitive(Primitive::Int(i2))) => i != *i2,
_ => false,
},
Value::Primitive(Primitive::Float(i)) => match (op, rhs) {
(Operator::LessThan, Value::Primitive(Primitive::Float(i2))) => i < *i2,
(Operator::GreaterThan, Value::Primitive(Primitive::Float(i2))) => i > *i2,
(Operator::LessThanOrEqual, Value::Primitive(Primitive::Float(i2))) => i <= *i2,
(Operator::GreaterThanOrEqual, Value::Primitive(Primitive::Float(i2))) => {
i >= *i2
}
(Operator::Equal, Value::Primitive(Primitive::Float(i2))) => i == *i2,
(Operator::NotEqual, Value::Primitive(Primitive::Float(i2))) => i != *i2,
(Operator::LessThan, Value::Primitive(Primitive::Int(i2))) => {
(i.into_inner()) < *i2 as f64
}
(Operator::GreaterThan, Value::Primitive(Primitive::Int(i2))) => {
i.into_inner() > *i2 as f64
}
(Operator::LessThanOrEqual, Value::Primitive(Primitive::Int(i2))) => {
i.into_inner() <= *i2 as f64
}
(Operator::GreaterThanOrEqual, Value::Primitive(Primitive::Int(i2))) => {
i.into_inner() >= *i2 as f64
}
(Operator::Equal, Value::Primitive(Primitive::Int(i2))) => {
i.into_inner() == *i2 as f64
}
(Operator::NotEqual, Value::Primitive(Primitive::Int(i2))) => {
i.into_inner() != *i2 as f64
}
_ => false,
},
Value::Primitive(Primitive::String(s)) => match (op, rhs) {
(Operator::Equal, Value::Primitive(Primitive::String(s2))) => s == *s2,
(Operator::NotEqual, Value::Primitive(Primitive::String(s2))) => s != *s2,
_ => false,
},
_ => false,
}
}
}
}
enum CompareValues {
Ints(i64, i64),
Floats(OF64, OF64),

View File

@ -82,8 +82,6 @@ pub enum RawExpression {
List(Vec<Expression>),
Path(Box<Path>),
ExternalCommand(ExternalCommand),
#[allow(unused)]
Boolean(bool),
}

View File

@ -29,7 +29,6 @@ pub fn baseline_parse_tokens(
Ok(exprs)
}
#[allow(unused)]
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
pub enum SyntaxType {
Any,

View File

@ -20,7 +20,6 @@ impl ToDebug for Operator {
}
impl Operator {
#[allow(unused)]
pub fn print(&self) -> String {
self.as_str().to_string()
}

View File

@ -1,8 +1,5 @@
#![allow(unused)]
use crate::parser::parse::{
call_node::*, flag::*, operator::*, pipeline::*, token_tree::*, token_tree_builder::*,
tokens::*, unit::*,
call_node::*, pipeline::*, token_tree::*, token_tree_builder::*, unit::*,
};
use crate::{Span, Tagged};
use nom;
@ -14,10 +11,9 @@ use nom::multi::*;
use nom::sequence::*;
use log::trace;
use nom::dbg;
use nom::*;
use nom::{AsBytes, FindSubstring, IResult, InputLength, InputTake, Slice};
use nom5_locate::{position, LocatedSpan};
use nom::{IResult, InputLength};
use nom5_locate::LocatedSpan;
use std::fmt::Debug;
use std::str::FromStr;
@ -243,14 +239,13 @@ pub fn raw_unit(input: NomSpan) -> IResult<NomSpan, Tagged<Unit>> {
pub fn size(input: NomSpan) -> IResult<NomSpan, TokenNode> {
trace_step(input, "size", move |input| {
let mut is_size = false;
let start = input.offset;
let (input, int) = raw_integer(input)?;
if let Ok((input, Some(size))) = opt(raw_unit)(input) {
let end = input.offset;
// Check to make sure there is no trailing parseable characters
if let Ok((input, Some(extra))) = opt(bare)(input) {
if let Ok((input, Some(_))) = opt(bare)(input) {
return Err(nom::Err::Error((input, nom::error::ErrorKind::Char)));
}
@ -262,11 +257,11 @@ pub fn size(input: NomSpan) -> IResult<NomSpan, TokenNode> {
let end = input.offset;
// Check to make sure there is no trailing parseable characters
if let Ok((input, Some(extra))) = opt(bare)(input) {
if let Ok((input, Some(_))) = opt(bare)(input) {
return Err(nom::Err::Error((input, nom::error::ErrorKind::Char)));
}
Ok((input, TokenTreeBuilder::spanned_int((*int), (start, end))))
Ok((input, TokenTreeBuilder::spanned_int(*int, (start, end))))
}
})
}
@ -289,17 +284,6 @@ pub fn token_list(input: NomSpan) -> IResult<NomSpan, Vec<TokenNode>> {
})
}
pub fn spaced_token_list(input: NomSpan) -> IResult<NomSpan, Vec<TokenNode>> {
trace_step(input, "spaced_token_list", move |input| {
let (input, sp_left) = opt(space1)(input)?;
let (input, first) = node(input)?;
let (input, list) = many0(pair(space1, node))(input)?;
let (input, sp_right) = opt(space1)(input)?;
Ok((input, make_token_list(sp_left, first, list, sp_right)))
})
}
fn make_token_list(
sp_left: Option<NomSpan>,
first: TokenNode,
@ -329,7 +313,7 @@ fn make_token_list(
pub fn whitespace(input: NomSpan) -> IResult<NomSpan, TokenNode> {
trace_step(input, "whitespace", move |input| {
let left = input.offset;
let (input, ws1) = space1(input)?;
let (input, _) = space1(input)?;
let right = input.offset;
Ok((input, TokenTreeBuilder::spanned_ws((left, right))))
@ -469,7 +453,7 @@ pub fn pipeline(input: NomSpan) -> IResult<NomSpan, TokenNode> {
)?;
let (input, tail) = opt(space1)(input)?;
let (input, newline) = opt(multispace1)(input)?;
let (input, _) = opt(multispace1)(input)?;
if input.input_len() != 0 {
return Err(Err::Error(error_position!(

View File

@ -9,7 +9,6 @@ use std::fmt;
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub enum TokenNode {
Token(Token),
#[allow(unused)]
Call(Tagged<CallNode>),
Delimited(Tagged<DelimitedNode>),
Pipeline(Tagged<Pipeline>),
@ -17,7 +16,6 @@ pub enum TokenNode {
Flag(Tagged<Flag>),
Member(Span),
Whitespace(Span),
#[allow(unused)]
Error(Tagged<Box<ShellError>>),
Path(Tagged<PathNode>),
}

View File

@ -1,4 +1,3 @@
#[allow(unused)]
use crate::prelude::*;
use crate::parser::parse::flag::{Flag, FlagKind};
@ -12,82 +11,9 @@ use crate::Span;
use derive_new::new;
#[derive(new)]
pub struct TokenTreeBuilder {
#[new(default)]
pos: usize,
}
pub struct TokenTreeBuilder {}
#[allow(unused)]
pub type CurriedNode<T> = Box<dyn FnOnce(&mut TokenTreeBuilder) -> T + 'static>;
pub type CurriedToken = Box<dyn FnOnce(&mut TokenTreeBuilder) -> TokenNode + 'static>;
pub type CurriedCall = Box<dyn FnOnce(&mut TokenTreeBuilder) -> Tagged<CallNode> + 'static>;
#[allow(unused)]
impl TokenTreeBuilder {
pub fn build(block: impl FnOnce(&mut Self) -> TokenNode) -> TokenNode {
let mut builder = TokenTreeBuilder::new();
block(&mut builder)
}
pub fn pipeline(input: Vec<(Option<&str>, CurriedCall, Option<&str>)>) -> CurriedToken {
let input: Vec<(Option<String>, CurriedCall, Option<String>)> = input
.into_iter()
.map(|(pre, call, post)| {
(
pre.map(|s| s.to_string()),
call,
post.map(|s| s.to_string()),
)
})
.collect();
Box::new(move |b| {
let start = b.pos;
let mut out: Vec<PipelineElement> = vec![];
let mut input = input.into_iter().peekable();
let (pre, call, post) = input
.next()
.expect("A pipeline must contain at least one element");
let pre_span = pre.map(|pre| b.consume(&pre));
let call = call(b);
let post_span = post.map(|post| b.consume(&post));
let pipe = input.peek().map(|_| Span::from(b.consume("|")));
out.push(PipelineElement::new(
pre_span.map(Span::from),
call,
post_span.map(Span::from),
pipe,
));
loop {
match input.next() {
None => break,
Some((pre, call, post)) => {
let pre_span = pre.map(|pre| b.consume(&pre));
let call = call(b);
let post_span = post.map(|post| b.consume(&post));
let pipe = input.peek().map(|_| Span::from(b.consume("|")));
out.push(PipelineElement::new(
pre_span.map(Span::from),
call,
post_span.map(Span::from),
pipe,
));
}
}
}
let end = b.pos;
TokenTreeBuilder::spanned_pipeline((out, None), (start, end))
})
}
pub fn spanned_pipeline(
input: (Vec<PipelineElement>, Option<Span>),
span: impl Into<Span>,
@ -98,35 +24,10 @@ impl TokenTreeBuilder {
))
}
pub fn op(input: impl Into<Operator>) -> CurriedToken {
let input = input.into();
Box::new(move |b| {
let (start, end) = b.consume(input.as_str());
b.pos = end;
TokenTreeBuilder::spanned_op(input, (start, end))
})
}
pub fn spanned_op(input: impl Into<Operator>, span: impl Into<Span>) -> TokenNode {
TokenNode::Operator(Tagged::from_simple_spanned_item(input.into(), span.into()))
}
pub fn string(input: impl Into<String>) -> CurriedToken {
let input = input.into();
Box::new(move |b| {
let (start, _) = b.consume("\"");
let (inner_start, inner_end) = b.consume(&input);
let (_, end) = b.consume("\"");
b.pos = end;
TokenTreeBuilder::spanned_string((inner_start, inner_end), (start, end))
})
}
pub fn spanned_string(input: impl Into<Span>, span: impl Into<Span>) -> TokenNode {
TokenNode::Token(Tagged::from_simple_spanned_item(
RawToken::String(input.into()),
@ -134,17 +35,6 @@ impl TokenTreeBuilder {
))
}
pub fn bare(input: impl Into<String>) -> CurriedToken {
let input = input.into();
Box::new(move |b| {
let (start, end) = b.consume(&input);
b.pos = end;
TokenTreeBuilder::spanned_bare((start, end))
})
}
pub fn spanned_bare(input: impl Into<Span>) -> TokenNode {
TokenNode::Token(Tagged::from_simple_spanned_item(
RawToken::Bare,
@ -159,17 +49,6 @@ impl TokenTreeBuilder {
))
}
pub fn int(input: impl Into<i64>) -> CurriedToken {
let int = input.into();
Box::new(move |b| {
let (start, end) = b.consume(&int.to_string());
b.pos = end;
TokenTreeBuilder::spanned_int(int, (start, end))
})
}
pub fn spanned_int(input: impl Into<i64>, span: impl Into<Span>) -> TokenNode {
TokenNode::Token(Token::from_simple_spanned_item(
RawToken::Integer(input.into()),
@ -177,19 +56,6 @@ impl TokenTreeBuilder {
))
}
pub fn size(int: impl Into<i64>, unit: impl Into<Unit>) -> CurriedToken {
let int = int.into();
let unit = unit.into();
Box::new(move |b| {
let (start, _) = b.consume(&int.to_string());
let (_, end) = b.consume(unit.as_str());
b.pos = end;
TokenTreeBuilder::spanned_size((int, unit), (start, end))
})
}
pub fn spanned_size(
input: (impl Into<i64>, impl Into<Unit>),
span: impl Into<Span>,
@ -202,25 +68,6 @@ impl TokenTreeBuilder {
))
}
pub fn path(head: CurriedToken, tail: Vec<CurriedToken>) -> CurriedToken {
Box::new(move |b| {
let start = b.pos;
let head = head(b);
let mut output = vec![];
for item in tail {
b.consume(".");
output.push(item(b));
}
let end = b.pos;
TokenTreeBuilder::spanned_path((head, output), (start, end))
})
}
pub fn spanned_path(input: (TokenNode, Vec<TokenNode>), span: impl Into<Span>) -> TokenNode {
TokenNode::Path(Tagged::from_simple_spanned_item(
PathNode::new(Box::new(input.0), input.1),
@ -228,17 +75,6 @@ impl TokenTreeBuilder {
))
}
pub fn var(input: impl Into<String>) -> CurriedToken {
let input = input.into();
Box::new(move |b| {
let (start, _) = b.consume("$");
let (inner_start, end) = b.consume(&input);
TokenTreeBuilder::spanned_var((inner_start, end), (start, end))
})
}
pub fn spanned_var(input: impl Into<Span>, span: impl Into<Span>) -> TokenNode {
TokenNode::Token(Tagged::from_simple_spanned_item(
RawToken::Variable(input.into()),
@ -246,17 +82,6 @@ impl TokenTreeBuilder {
))
}
pub fn flag(input: impl Into<String>) -> CurriedToken {
let input = input.into();
Box::new(move |b| {
let (start, _) = b.consume("--");
let (inner_start, end) = b.consume(&input);
TokenTreeBuilder::spanned_flag((inner_start, end), (start, end))
})
}
pub fn spanned_flag(input: impl Into<Span>, span: impl Into<Span>) -> TokenNode {
TokenNode::Flag(Tagged::from_simple_spanned_item(
Flag::new(FlagKind::Longhand, input.into()),
@ -264,17 +89,6 @@ impl TokenTreeBuilder {
))
}
pub fn shorthand(input: impl Into<String>) -> CurriedToken {
let input = input.into();
Box::new(move |b| {
let (start, _) = b.consume("-");
let (inner_start, end) = b.consume(&input);
TokenTreeBuilder::spanned_shorthand((inner_start, end), (start, end))
})
}
pub fn spanned_shorthand(input: impl Into<Span>, span: impl Into<Span>) -> TokenNode {
TokenNode::Flag(Tagged::from_simple_spanned_item(
Flag::new(FlagKind::Shorthand, input.into()),
@ -282,36 +96,10 @@ impl TokenTreeBuilder {
))
}
pub fn member(input: impl Into<String>) -> CurriedToken {
let input = input.into();
Box::new(move |b| {
let (start, end) = b.consume(&input);
TokenTreeBuilder::spanned_member((start, end))
})
}
pub fn spanned_member(span: impl Into<Span>) -> TokenNode {
TokenNode::Member(span.into())
}
pub fn call(head: CurriedToken, input: Vec<CurriedToken>) -> CurriedCall {
Box::new(move |b| {
let start = b.pos;
let head_node = head(b);
let mut nodes = vec![head_node];
for item in input {
nodes.push(item(b));
}
let end = b.pos;
TokenTreeBuilder::spanned_call(nodes, (start, end))
})
}
pub fn spanned_call(input: Vec<TokenNode>, span: impl Into<Span>) -> Tagged<CallNode> {
if input.len() == 0 {
panic!("BUG: spanned call (TODO)")
@ -325,20 +113,6 @@ impl TokenTreeBuilder {
Tagged::from_simple_spanned_item(CallNode::new(Box::new(head), tail), span)
}
pub fn parens(input: Vec<CurriedToken>) -> CurriedToken {
Box::new(move |b| {
let (start, _) = b.consume("(");
let mut output = vec![];
for item in input {
output.push(item(b));
}
let (_, end) = b.consume(")");
TokenTreeBuilder::spanned_parens(output, (start, end))
})
}
pub fn spanned_parens(input: impl Into<Vec<TokenNode>>, span: impl Into<Span>) -> TokenNode {
TokenNode::Delimited(Tagged::from_simple_spanned_item(
DelimitedNode::new(Delimiter::Paren, input.into()),
@ -346,20 +120,6 @@ impl TokenTreeBuilder {
))
}
pub fn square(input: Vec<CurriedToken>) -> CurriedToken {
Box::new(move |b| {
let (start, _) = b.consume("[");
let mut output = vec![];
for item in input {
output.push(item(b));
}
let (_, end) = b.consume("]");
TokenTreeBuilder::spanned_square(output, (start, end))
})
}
pub fn spanned_square(input: impl Into<Vec<TokenNode>>, span: impl Into<Span>) -> TokenNode {
TokenNode::Delimited(Tagged::from_simple_spanned_item(
DelimitedNode::new(Delimiter::Square, input.into()),
@ -367,20 +127,6 @@ impl TokenTreeBuilder {
))
}
pub fn braced(input: Vec<CurriedToken>) -> CurriedToken {
Box::new(move |b| {
let (start, _) = b.consume("{ ");
let mut output = vec![];
for item in input {
output.push(item(b));
}
let (_, end) = b.consume(" }");
TokenTreeBuilder::spanned_brace(output, (start, end))
})
}
pub fn spanned_brace(input: impl Into<Vec<TokenNode>>, span: impl Into<Span>) -> TokenNode {
TokenNode::Delimited(Tagged::from_simple_spanned_item(
DelimitedNode::new(Delimiter::Brace, input.into()),
@ -388,31 +134,9 @@ impl TokenTreeBuilder {
))
}
pub fn sp() -> CurriedToken {
Box::new(|b| {
let (start, end) = b.consume(" ");
TokenNode::Whitespace(Span::from((start, end)))
})
}
pub fn ws(input: impl Into<String>) -> CurriedToken {
let input = input.into();
Box::new(move |b| {
let (start, end) = b.consume(&input);
TokenTreeBuilder::spanned_ws((start, end))
})
}
pub fn spanned_ws(span: impl Into<Span>) -> TokenNode {
let span = span.into();
TokenNode::Whitespace(span.into())
}
fn consume(&mut self, input: &str) -> (usize, usize) {
let start = self.pos;
self.pos += input.len();
(start, self.pos)
}
}

View File

@ -9,7 +9,6 @@ use log::trace;
use serde::{Deserialize, Serialize};
use std::fmt;
#[allow(unused)]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum NamedType {
Switch,
@ -17,7 +16,6 @@ pub enum NamedType {
Optional(SyntaxType),
}
#[allow(unused)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PositionalType {
Mandatory(String, SyntaxType),
@ -45,15 +43,6 @@ impl PositionalType {
PositionalType::Optional(name.to_string(), SyntaxType::Any)
}
#[allow(unused)]
crate fn to_coerce_hint(&self) -> Option<SyntaxType> {
match self {
PositionalType::Mandatory(_, SyntaxType::Block)
| PositionalType::Optional(_, SyntaxType::Block) => Some(SyntaxType::Block),
_ => None,
}
}
crate fn name(&self) -> &str {
match self {
PositionalType::Mandatory(s, _) => s,
@ -289,10 +278,7 @@ impl Signature {
Ok(args)
}
#[allow(unused)]
crate fn signature(&self) -> String {
format!("TODO")
}
// TODO: signature() -> String
}
crate fn evaluate_args(

View File

@ -7,20 +7,16 @@ use std::io;
pub trait Plugin {
fn config(&mut self) -> Result<Signature, ShellError>;
#[allow(unused)]
fn begin_filter(&mut self, call_info: CallInfo) -> Result<Vec<ReturnValue>, ShellError> {
fn begin_filter(&mut self, _: CallInfo) -> Result<Vec<ReturnValue>, ShellError> {
Ok(vec![])
}
#[allow(unused)]
fn filter(&mut self, input: Tagged<Value>) -> Result<Vec<ReturnValue>, ShellError> {
fn filter(&mut self, _: Tagged<Value>) -> Result<Vec<ReturnValue>, ShellError> {
Ok(vec![])
}
#[allow(unused)]
fn end_filter(&mut self) -> Result<Vec<ReturnValue>, ShellError> {
Ok(vec![])
}
#[allow(unused)]
fn sink(&mut self, call_info: CallInfo, input: Vec<Tagged<Value>>) {}
fn sink(&mut self, _: CallInfo, _: Vec<Tagged<Value>>) {}
fn quit(&mut self) {}
}

View File

@ -341,8 +341,7 @@ pub fn view_contents(
let cursor = cursor();
let _ = cursor.show();
#[allow(unused)]
let screen = RawScreen::disable_raw_mode();
let _ = RawScreen::disable_raw_mode();
Ok(())
}
@ -446,8 +445,7 @@ pub fn view_contents_interactive(
let cursor = cursor();
let _ = cursor.show();
#[allow(unused)]
let screen = RawScreen::disable_raw_mode();
let _ = RawScreen::disable_raw_mode();
Ok(())
}

View File

@ -196,8 +196,7 @@ fn scroll_view_lines_if_needed(draw_commands: Vec<DrawCommand>, use_color_buffer
}
let _ = cursor.show();
#[allow(unused)]
let screen = RawScreen::disable_raw_mode();
let _ = RawScreen::disable_raw_mode();
}
}

View File

@ -58,8 +58,7 @@ crate use crate::Text;
crate use futures::stream::BoxStream;
crate use futures::{FutureExt, Stream, StreamExt};
crate use futures_async_stream::async_stream_block;
#[allow(unused)]
crate use serde::{Deserialize, Serialize};
crate use serde::Deserialize;
crate use std::collections::VecDeque;
crate use std::future::Future;
crate use std::sync::{Arc, Mutex};

View File

@ -105,7 +105,10 @@ impl FileStructure {
self.root = path.to_path_buf();
}
pub fn paths_applying_with<F>(&mut self, to: F) -> Result<Vec<(PathBuf, PathBuf)>, Box<dyn std::error::Error>>
pub fn paths_applying_with<F>(
&mut self,
to: F,
) -> Result<Vec<(PathBuf, PathBuf)>, Box<dyn std::error::Error>>
where
F: Fn((PathBuf, usize)) -> Result<(PathBuf, PathBuf), Box<dyn std::error::Error>>,
{
@ -175,7 +178,8 @@ mod tests {
fn prepares_and_decorates_source_files_for_copying() {
let mut res = FileStructure::new();
res.walk_decorate(fixtures().as_path()).expect("Can not decorate files traversal.");
res.walk_decorate(fixtures().as_path())
.expect("Can not decorate files traversal.");
assert_eq!(
res.resources,

View File

@ -25,7 +25,7 @@ fn accepts_and_creates_directories() {
let full_path = format!("{}/{}", Playground::root(), sandbox);
nu!(_output, cwd(&full_path), "mkdir dir_1 dir_2 dir_3");
assert!(h::files_exist_at(
vec![Path::new("dir_1"), Path::new("dir_2"), Path::new("dir_3")],
PathBuf::from(&full_path)

View File

@ -8,15 +8,13 @@ use std::path::{Path, PathBuf};
#[test]
fn moves_a_file() {
let sandbox = Playground::setup_for("mv_test_1")
.with_files(vec![
EmptyFile("andres.txt"),
])
.with_files(vec![EmptyFile("andres.txt")])
.mkdir("expected")
.test_dir_name();
let full_path = format!("{}/{}", Playground::root(), sandbox);
let original = format!("{}/{}", full_path, "andres.txt");
let expected = format!("{}/{}", full_path, "expected/yehuda.txt");
let expected = format!("{}/{}", full_path, "expected/yehuda.txt");
nu!(
_output,
@ -31,21 +29,14 @@ fn moves_a_file() {
#[test]
fn overwrites_if_moving_to_existing_file() {
let sandbox = Playground::setup_for("mv_test_2")
.with_files(vec![
EmptyFile("andres.txt"),
EmptyFile("jonathan.txt"),
])
.with_files(vec![EmptyFile("andres.txt"), EmptyFile("jonathan.txt")])
.test_dir_name();
let full_path = format!("{}/{}", Playground::root(), sandbox);
let original = format!("{}/{}", full_path, "andres.txt");
let expected = format!("{}/{}", full_path, "jonathan.txt");
let expected = format!("{}/{}", full_path, "jonathan.txt");
nu!(
_output,
cwd(&full_path),
"mv andres.txt jonathan.txt"
);
nu!(_output, cwd(&full_path), "mv andres.txt jonathan.txt");
assert!(!h::file_exists_at(PathBuf::from(original)));
assert!(h::file_exists_at(PathBuf::from(expected)));
@ -58,14 +49,10 @@ fn moves_a_directory() {
.test_dir_name();
let full_path = format!("{}/{}", Playground::root(), sandbox);
let original_dir = format!("{}/{}", full_path, "empty_dir");
let expected = format!("{}/{}", full_path, "renamed_dir");
let original_dir = format!("{}/{}", full_path, "empty_dir");
let expected = format!("{}/{}", full_path, "renamed_dir");
nu!(
_output,
cwd(&full_path),
"mv empty_dir renamed_dir"
);
nu!(_output, cwd(&full_path), "mv empty_dir renamed_dir");
assert!(!h::dir_exists_at(PathBuf::from(original_dir)));
assert!(h::dir_exists_at(PathBuf::from(expected)));
@ -74,22 +61,15 @@ fn moves_a_directory() {
#[test]
fn moves_the_file_inside_directory_if_path_to_move_is_existing_directory() {
let sandbox = Playground::setup_for("mv_test_4")
.with_files(vec![
EmptyFile("jonathan.txt"),
])
.with_files(vec![EmptyFile("jonathan.txt")])
.mkdir("expected")
.test_dir_name();
let full_path = format!("{}/{}", Playground::root(), sandbox);
let original_dir = format!("{}/{}", full_path, "jonathan.txt");
let expected = format!("{}/{}", full_path, "expected/jonathan.txt");
nu!(
_output,
cwd(&full_path),
"mv jonathan.txt expected"
);
let original_dir = format!("{}/{}", full_path, "jonathan.txt");
let expected = format!("{}/{}", full_path, "expected/jonathan.txt");
nu!(_output, cwd(&full_path), "mv jonathan.txt expected");
assert!(!h::file_exists_at(PathBuf::from(original_dir)));
assert!(h::file_exists_at(PathBuf::from(expected)));
@ -99,22 +79,15 @@ fn moves_the_file_inside_directory_if_path_to_move_is_existing_directory() {
fn moves_the_directory_inside_directory_if_path_to_move_is_existing_directory() {
let sandbox = Playground::setup_for("mv_test_5")
.within("contributors")
.with_files(vec![
EmptyFile("jonathan.txt"),
])
.with_files(vec![EmptyFile("jonathan.txt")])
.mkdir("expected")
.test_dir_name();
let full_path = format!("{}/{}", Playground::root(), sandbox);
let original_dir = format!("{}/{}", full_path, "contributors");
let expected = format!("{}/{}", full_path, "expected/contributors");
nu!(
_output,
cwd(&full_path),
"mv contributors expected"
);
let original_dir = format!("{}/{}", full_path, "contributors");
let expected = format!("{}/{}", full_path, "expected/contributors");
nu!(_output, cwd(&full_path), "mv contributors expected");
assert!(!h::dir_exists_at(PathBuf::from(original_dir)));
assert!(h::file_exists_at(PathBuf::from(expected)));
@ -124,14 +97,12 @@ fn moves_the_directory_inside_directory_if_path_to_move_is_existing_directory()
fn moves_the_directory_inside_directory_if_path_to_move_is_nonexistent_directory() {
let sandbox = Playground::setup_for("mv_test_6")
.within("contributors")
.with_files(vec![
EmptyFile("jonathan.txt"),
])
.with_files(vec![EmptyFile("jonathan.txt")])
.mkdir("expected")
.test_dir_name();
let full_path = format!("{}/{}", Playground::root(), sandbox);
let original_dir = format!("{}/{}", full_path, "contributors");
let original_dir = format!("{}/{}", full_path, "contributors");
nu!(
_output,
@ -139,7 +110,10 @@ fn moves_the_directory_inside_directory_if_path_to_move_is_nonexistent_directory
"mv contributors expected/this_dir_exists_now/los_tres_amigos"
);
let expected = format!("{}/{}", full_path, "expected/this_dir_exists_now/los_tres_amigos");
let expected = format!(
"{}/{}",
full_path, "expected/this_dir_exists_now/los_tres_amigos"
);
assert!(!h::dir_exists_at(PathBuf::from(original_dir)));
assert!(h::file_exists_at(PathBuf::from(expected)));
@ -168,11 +142,7 @@ fn moves_using_path_with_wildcard() {
let work_dir = format!("{}/{}", full_path, "work_dir");
let expected_copies_path = format!("{}/{}", full_path, "expected");
nu!(
_output,
cwd(&work_dir),
"mv ../originals/*.ini ../expected"
);
nu!(_output, cwd(&work_dir), "mv ../originals/*.ini ../expected");
assert!(h::files_exist_at(
vec![
@ -185,7 +155,6 @@ fn moves_using_path_with_wildcard() {
));
}
#[test]
fn moves_using_a_glob() {
let sandbox = Playground::setup_for("mv_test_8")
@ -204,11 +173,7 @@ fn moves_using_a_glob() {
let work_dir = format!("{}/{}", full_path, "work_dir");
let expected_copies_path = format!("{}/{}", full_path, "expected");
nu!(
_output,
cwd(&work_dir),
"mv ../meals/* ../expected"
);
nu!(_output, cwd(&work_dir), "mv ../meals/* ../expected");
assert!(h::dir_exists_at(PathBuf::from(meal_dir)));
assert!(h::files_exist_at(
@ -219,4 +184,4 @@ fn moves_using_a_glob() {
],
PathBuf::from(&expected_copies_path)
));
}
}

View File

@ -111,4 +111,4 @@ fn errors_if_file_not_found() {
);
assert!(output.contains("File could not be opened"));
}
}

View File

@ -90,7 +90,7 @@ fn rm_removes_deeply_nested_directories_with_wildcard_and_recursive_flag() {
.test_dir_name();
let full_path = format!("{}/{}", Playground::root(), sandbox);
nu!(
_output,
cwd("tests/fixtures/nuplayground/rm_wildcard_test_2"),
@ -98,10 +98,7 @@ fn rm_removes_deeply_nested_directories_with_wildcard_and_recursive_flag() {
);
assert!(!h::files_exist_at(
vec![
Path::new("src/parser/parse"),
Path::new("src/parser/hir"),
],
vec![Path::new("src/parser/parse"), Path::new("src/parser/hir"),],
PathBuf::from(&full_path)
));
}
@ -150,7 +147,11 @@ fn rm_errors_if_attempting_to_delete_a_directory_with_content_without_recursive_
let full_path = format!("{}/{}", Playground::root(), sandbox);
nu_error!(output, cwd(&Playground::root()), "rm rm_prevent_directory_removal_without_flag_test");
nu_error!(
output,
cwd(&Playground::root()),
"rm rm_prevent_directory_removal_without_flag_test"
);
assert!(h::file_exists_at(PathBuf::from(full_path)));
assert!(output.contains("is a directory"));
@ -168,4 +169,4 @@ fn rm_errors_if_attempting_to_delete_two_dot_as_argument() {
nu_error!(output, cwd(&Playground::root()), "rm ..");
assert!(output.contains("may not be removed"));
}
}

View File

@ -16,14 +16,15 @@ fn can_only_apply_one() {
#[test]
fn by_one_with_field_passed() {
Playground::setup_for("plugin_inc_by_one_with_field_passed_test")
.with_files(vec![FileWithContent(
Playground::setup_for("plugin_inc_by_one_with_field_passed_test").with_files(vec![
FileWithContent(
"sample.toml",
r#"
[package]
edition = "2018"
"#,
)]);
),
]);
nu!(
output,
@ -36,35 +37,34 @@ fn by_one_with_field_passed() {
#[test]
fn by_one_with_no_field_passed() {
Playground::setup_for("plugin_inc_by_one_with_no_field_passed_test")
.with_files(vec![FileWithContent(
Playground::setup_for("plugin_inc_by_one_with_no_field_passed_test").with_files(vec![
FileWithContent(
"sample.toml",
r#"
[package]
contributors = "2"
"#,
)]);
),
]);
nu!(
output,
cwd("tests/fixtures/nuplayground/plugin_inc_by_one_with_no_field_passed_test"),
"open sample.toml | get package.contributors | inc | echo $it"
);
assert_eq!(output, "3");
}
#[test]
fn semversion_major_inc() {
Playground::setup_for("plugin_inc_major_semversion_test")
.with_files(vec![FileWithContent(
"sample.toml",
r#"
Playground::setup_for("plugin_inc_major_semversion_test").with_files(vec![FileWithContent(
"sample.toml",
r#"
[package]
version = "0.1.3"
"#,
)]);
)]);
nu!(
output,
@ -77,14 +77,13 @@ fn semversion_major_inc() {
#[test]
fn semversion_minor_inc() {
Playground::setup_for("plugin_inc_minor_semversion_test")
.with_files(vec![FileWithContent(
"sample.toml",
r#"
Playground::setup_for("plugin_inc_minor_semversion_test").with_files(vec![FileWithContent(
"sample.toml",
r#"
[package]
version = "0.1.3"
"#,
)]);
)]);
nu!(
output,
@ -97,14 +96,13 @@ fn semversion_minor_inc() {
#[test]
fn semversion_patch_inc() {
Playground::setup_for("plugin_inc_patch_semversion_test")
.with_files(vec![FileWithContent(
"sample.toml",
r#"
Playground::setup_for("plugin_inc_patch_semversion_test").with_files(vec![FileWithContent(
"sample.toml",
r#"
[package]
version = "0.1.3"
"#,
)]);
)]);
nu!(
output,
@ -117,14 +115,15 @@ fn semversion_patch_inc() {
#[test]
fn semversion_without_passing_field() {
Playground::setup_for("plugin_inc_semversion_without_passing_field_test")
.with_files(vec![FileWithContent(
Playground::setup_for("plugin_inc_semversion_without_passing_field_test").with_files(vec![
FileWithContent(
"sample.toml",
r#"
[package]
version = "0.1.3"
"#,
)]);
),
]);
nu!(
output,
@ -133,4 +132,4 @@ fn semversion_without_passing_field() {
);
assert_eq!(output, "0.1.4");
}
}