diff --git a/crates/nu-command/src/core_commands/history.rs b/crates/nu-command/src/core_commands/history.rs new file mode 100644 index 000000000..659384067 --- /dev/null +++ b/crates/nu-command/src/core_commands/history.rs @@ -0,0 +1,65 @@ +use nu_protocol::ast::Call; +use nu_protocol::engine::{Command, EngineState, Stack}; +use nu_protocol::{ + Category, IntoInterruptiblePipelineData, PipelineData, ShellError, Signature, Value, +}; + +#[derive(Clone)] +pub struct History; + +impl Command for History { + fn name(&self) -> &str { + "history" + } + + fn usage(&self) -> &str { + "Get the command history" + } + + fn signature(&self) -> nu_protocol::Signature { + Signature::build("history") + .switch("clear", "Clears out the history entries", Some('c')) + .category(Category::Core) + } + + fn run( + &self, + engine_state: &EngineState, + _stack: &mut Stack, + call: &Call, + _input: PipelineData, + ) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> { + let head = call.head; + if let Some(config_path) = nu_path::config_dir() { + let clear = call.has_flag("clear"); + let ctrlc = engine_state.ctrlc.clone(); + + let mut history_path = config_path; + history_path.push("nushell"); + history_path.push("history.txt"); + + if clear { + let _ = std::fs::remove_file(history_path); + Ok(PipelineData::new(head)) + } else { + let contents = std::fs::read_to_string(history_path); + + if let Ok(contents) = contents { + Ok(contents + .lines() + .map(move |x| Value::String { + val: x.to_string(), + span: head, + }) + .collect::<Vec<_>>() + .into_iter() + .into_pipeline_data(ctrlc)) + } else { + Err(ShellError::FileNotFound(head)) + } + } + } else { + Err(ShellError::FileNotFound(head)) + } + } +} diff --git a/crates/nu-command/src/core_commands/mod.rs b/crates/nu-command/src/core_commands/mod.rs index 3c9068022..dc58df2f7 100644 --- a/crates/nu-command/src/core_commands/mod.rs +++ b/crates/nu-command/src/core_commands/mod.rs @@ -10,6 +10,7 @@ mod export_env; mod for_; mod help; mod hide; +mod history; mod if_; mod let_; mod module; @@ -29,6 +30,7 @@ pub use export_env::ExportEnv; pub use for_::For; pub use help::Help; pub use hide::Hide; +pub use history::History; pub use if_::If; pub use let_::Let; pub use module::Module; diff --git a/crates/nu-command/src/default_context.rs b/crates/nu-command/src/default_context.rs index 744650d6a..6f3d2f63d 100644 --- a/crates/nu-command/src/default_context.rs +++ b/crates/nu-command/src/default_context.rs @@ -35,6 +35,7 @@ pub fn create_default_context() -> EngineState { For, Help, Hide, + History, If, Let, Module,