nushell/crates/nu-command/src/filesystem/open.rs

218 lines
7.1 KiB
Rust
Raw Normal View History

use crate::filesystem::util::BufferedReader;
use nu_engine::{eval_block, get_full_help, CallExt};
2021-12-24 19:24:55 +00:00
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Category, Example, IntoPipelineData, PipelineData, RawStream, ShellError, Signature, Spanned,
SyntaxShape, Value,
2021-12-24 19:24:55 +00:00
};
use std::io::BufReader;
#[cfg(feature = "database")]
use crate::database::SQLiteDatabase;
2021-12-24 19:24:55 +00:00
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
#[derive(Clone)]
pub struct Open;
impl Command for Open {
fn name(&self) -> &str {
"open"
}
fn usage(&self) -> &str {
"Load a file into a cell, converting to table if possible (avoid by appending '--raw')."
2021-12-24 19:24:55 +00:00
}
fn search_terms(&self) -> Vec<&str> {
vec!["open", "load", "read", "load_file", "read_file"]
}
2021-12-24 19:24:55 +00:00
fn signature(&self) -> nu_protocol::Signature {
Signature::build("open")
.optional("filename", SyntaxShape::Filepath, "the filename to use")
2021-12-25 22:13:43 +00:00
.switch("raw", "open file as raw binary", Some('r'))
2021-12-24 19:24:55 +00:00
.category(Category::FileSystem)
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
2021-12-24 19:24:55 +00:00
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
let raw = call.has_flag("raw");
let call_span = call.head;
let ctrlc = engine_state.ctrlc.clone();
let path = call.opt::<Spanned<String>>(engine_state, stack, 0)?;
let path = {
if let Some(path_val) = path {
Some(Spanned {
item: match strip_ansi_escapes::strip(&path_val.item) {
Ok(item) => String::from_utf8(item).unwrap_or(path_val.item),
Err(_) => path_val.item,
},
span: path_val.span,
})
} else {
path
}
};
let path = if let Some(path) = path {
path
} else {
// Collect a filename from the input
match input {
PipelineData::Value(Value::Nothing { .. }, ..) => {
return Ok(Value::String {
val: get_full_help(
&Open.signature(),
&Open.examples(),
engine_state,
stack,
),
span: call.head,
}
.into_pipeline_data())
}
PipelineData::Value(val, ..) => val.as_spanned_string()?,
_ => {
return Ok(Value::String {
val: get_full_help(
&Open.signature(),
&Open.examples(),
engine_state,
stack,
),
span: call.head,
}
.into_pipeline_data())
}
}
};
2021-12-24 19:24:55 +00:00
let arg_span = path.span;
let path_no_whitespace = &path.item.trim_end_matches(|x| matches!(x, '\x09'..='\x0d'));
let path = Path::new(path_no_whitespace);
2021-12-24 19:24:55 +00:00
if permission_denied(&path) {
#[cfg(unix)]
let error_msg = match path.metadata() {
Ok(md) => format!(
"The permissions of {:o} does not allow access for this user",
md.permissions().mode() & 0o0777
),
Err(e) => e.to_string(),
};
2021-12-24 19:24:55 +00:00
#[cfg(not(unix))]
let error_msg = String::from("Permission denied");
Err(ShellError::GenericError(
"Permission denied".into(),
error_msg,
Some(arg_span),
None,
Vec::new(),
2021-12-24 19:24:55 +00:00
))
} else {
#[cfg(feature = "database")]
if !raw {
let res = SQLiteDatabase::try_from_path(path, arg_span)
.map(|db| db.into_value(call.head).into_pipeline_data());
if res.is_ok() {
return res;
}
}
let file = match std::fs::File::open(path) {
2021-12-24 19:24:55 +00:00
Ok(file) => file,
Err(err) => {
return Err(ShellError::GenericError(
"Permission denied".into(),
err.to_string(),
Some(arg_span),
None,
Vec::new(),
2021-12-24 19:24:55 +00:00
));
}
};
let buf_reader = BufReader::new(file);
let output = PipelineData::ExternalStream {
stdout: Some(RawStream::new(
Box::new(BufferedReader { input: buf_reader }),
ctrlc,
call_span,
)),
stderr: None,
exit_code: None,
span: call_span,
metadata: None,
};
2021-12-24 19:24:55 +00:00
let ext = if raw {
None
} else {
path.extension()
.map(|name| name.to_string_lossy().to_string())
};
if let Some(ext) = ext {
Overlays (#5375) * WIP: Start laying overlays * Rename Overlay->Module; Start adding overlay * Revamp adding overlay * Add overlay add tests; Disable debug print * Fix overlay add; Add overlay remove * Add overlay remove tests * Add missing overlay remove file * Add overlay list command * (WIP?) Enable overlays for env vars * Move OverlayFrames to ScopeFrames * (WIP) Move everything to overlays only ScopeFrame contains nothing but overlays now * Fix predecls * Fix wrong overlay id translation and aliases * Fix broken env lookup logic * Remove TODOs * Add overlay add + remove for environment * Add a few overlay tests; Fix overlay add name * Some cleanup; Fix overlay add/remove names * Clippy * Fmt * Remove walls of comments * List overlays from stack; Add debugging flag Currently, the engine state ordering is somehow broken. * Fix (?) overlay list test * Fix tests on Windows * Fix activated overlay ordering * Check for active overlays equality in overlay list This removes the -p flag: Either both parser and engine will have the same overlays, or the command will fail. * Add merging on overlay remove * Change help message and comment * Add some remove-merge/discard tests * (WIP) Track removed overlays properly * Clippy; Fmt * Fix getting last overlay; Fix predecls in overlays * Remove merging; Fix re-add overwriting stuff Also some error message tweaks. * Fix overlay error in the engine * Update variable_completions.rs * Adds flags and optional arguments to view-source (#5446) * added flags and optional arguments to view-source * removed redundant code * removed redundant code * fmt * fix bug in shell_integration (#5450) * fix bug in shell_integration * add some comments * enable cd to work with directory abbreviations (#5452) * enable cd to work with abbreviations * add abbreviation example * fix tests * make it configurable * make cd recornize symblic link (#5454) * implement seq char command to generate single character sequence (#5453) * add tmp code * add seq char command * Add split number flag in `split row` (#5434) Signed-off-by: Yuheng Su <gipsyh.icu@gmail.com> * Add two more overlay tests * Add ModuleId to OverlayFrame * Fix env conversion accidentally activating overlay It activated overlay from permanent state prematurely which would cause `overlay add` to misbehave. * Remove unused parameter; Add overlay list test * Remove added traces * Add overlay commands examples * Modify TODO * Fix $nu.scope iteration * Disallow removing default overlay * Refactor some parser errors * Remove last overlay if no argument * Diversify overlay examples * Make it possible to update overlay's module In case the origin module updates, the overlay add loads the new module, makes it overlay's origin and applies the changes. Before, it was impossible to update the overlay if the module changed. Co-authored-by: JT <547158+jntrnr@users.noreply.github.com> Co-authored-by: pwygab <88221256+merelymyself@users.noreply.github.com> Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com> Co-authored-by: WindSoilder <WindSoilder@outlook.com> Co-authored-by: Yuheng Su <gipsyh.icu@gmail.com>
2022-05-07 19:39:22 +00:00
match engine_state.find_decl(format!("from {}", ext).as_bytes(), &[]) {
Some(converter_id) => {
let decl = engine_state.get_decl(converter_id);
if let Some(block_id) = decl.get_block_id() {
let block = engine_state.get_block(block_id);
eval_block(engine_state, stack, block, output, false, false)
} else {
decl.run(engine_state, stack, &Call::new(arg_span), output)
}
}
2021-12-24 19:24:55 +00:00
None => Ok(output),
}
} else {
Ok(output)
}
}
}
fn examples(&self) -> Vec<nu_protocol::Example> {
vec![
Example {
description: "Open a file, with structure (based on file extension or SQLite database header)",
example: "open myfile.json",
result: None,
},
Example {
description: "Open a file, as raw bytes",
example: "open myfile.json --raw",
result: None,
},
Example {
description: "Open a file, using the input to get filename",
example: "echo 'myfile.txt' | open",
result: None,
},
Example {
description: "Open a file, and decode it by the specified encoding",
example: "open myfile.txt --raw | decode utf-8",
result: None,
},
]
}
2021-12-24 19:24:55 +00:00
}
fn permission_denied(dir: impl AsRef<Path>) -> bool {
match dir.as_ref().read_dir() {
Err(e) => matches!(e.kind(), std::io::ErrorKind::PermissionDenied),
Ok(_) => false,
}
}