Extend 'Shell' with open and save capabilities (#2165)

* Extend 'Shell' with open and save capabilities

* clippy fix
This commit is contained in:
Jonathan Turner
2020-07-13 21:07:44 +12:00
committed by GitHub
parent 7a207a673b
commit 07594222c0
7 changed files with 138 additions and 29 deletions

View File

@@ -1,17 +1,14 @@
use crate::commands::classified::maybe_text_codec::{MaybeTextCodec, StringOrBinary};
use crate::commands::classified::maybe_text_codec::StringOrBinary;
use crate::commands::constants::BAT_LANGUAGES;
use crate::commands::WholeStreamCommand;
use crate::prelude::*;
use futures_codec::FramedRead;
use encoding_rs::{Encoding, UTF_8};
use futures_util::StreamExt;
use log::debug;
use nu_errors::ShellError;
use nu_protocol::{CommandAction, ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value};
use nu_source::{AnchorLocation, Span, Tagged};
use std::path::PathBuf;
extern crate encoding_rs;
use crate::commands::constants::BAT_LANGUAGES;
use encoding_rs::*;
use futures::prelude::*;
use log::debug;
use std::fs::File;
pub struct Open;
@@ -103,6 +100,7 @@ pub fn get_encoding(opt: Option<Tagged<String>>) -> Result<&'static Encoding, Sh
async fn open(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
let cwd = PathBuf::from(args.shell_manager.path());
let registry = registry.clone();
let shell_manager = args.shell_manager.clone();
let (
OpenArgs {
@@ -159,17 +157,8 @@ async fn open(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStr
} else {
Some(get_encoding(encoding)?)
};
let f = File::open(&path).map_err(|e| {
ShellError::labeled_error(
format!("Error opening file: {:?}", e),
"Error opening file",
path.span(),
)
})?;
let async_reader = futures::io::AllowStdIo::new(f);
let sob_stream = FramedRead::new(async_reader, MaybeTextCodec::new(with_encoding))
.map_err(|e| ShellError::unexpected(format!("AsyncRead failed in open function: {:?}", e)))
.into_stream();
let sob_stream = shell_manager.open(&path.item, path.tag.span, with_encoding)?;
let final_stream = sob_stream.map(move |x| {
// The tag that will used when returning a Value

View File

@@ -170,7 +170,7 @@ async fn save(
let host = raw_args.host.clone();
let ctrl_c = raw_args.ctrl_c.clone();
let current_errors = raw_args.current_errors.clone();
let shell_manager = raw_args.shell_manager.clone();
let mut shell_manager = raw_args.shell_manager.clone();
let head = raw_args.call_info.args.head.clone();
let (
@@ -219,7 +219,7 @@ async fn save(
host,
ctrl_c,
current_errors,
shell_manager,
shell_manager: shell_manager.clone(),
call_info: UnevaluatedCallInfo {
args: nu_protocol::hir::Call {
head,
@@ -252,14 +252,7 @@ async fn save(
};
match content {
Ok(save_data) => match std::fs::write(full_path, save_data) {
Ok(_) => Ok(OutputStream::empty()),
Err(e) => Err(ShellError::labeled_error(
e.to_string(),
"IO error while saving",
name,
)),
},
Ok(save_data) => shell_manager.save(&full_path, &save_data, name.span),
Err(e) => Err(e),
}
}