Use get_history_path where appropriate

This commit is contained in:
Piotr Kufel 2024-07-26 18:15:33 -07:00
parent 07e7c8c81f
commit 9d24c5efd4
7 changed files with 106 additions and 101 deletions

View File

@ -5,6 +5,8 @@ use reedline::{
SqliteBackedHistory, SqliteBackedHistory,
}; };
use crate::config_files::get_history_path;
#[derive(Clone)] #[derive(Clone)]
pub struct History; pub struct History;
@ -44,22 +46,13 @@ impl Command for History {
}; };
// todo for sqlite history this command should be an alias to `open ~/.config/nushell/history.sqlite3 | get history` // todo for sqlite history this command should be an alias to `open ~/.config/nushell/history.sqlite3 | get history`
if let Some(config_path) = nu_path::config_dir() { let Some(history_path) = get_history_path(history.file_format) else {
return Err(ShellError::ConfigDirNotFound { span: Some(head) });
};
let clear = call.has_flag(engine_state, stack, "clear")?; let clear = call.has_flag(engine_state, stack, "clear")?;
let long = call.has_flag(engine_state, stack, "long")?; let long = call.has_flag(engine_state, stack, "long")?;
let signals = engine_state.signals().clone(); let signals = engine_state.signals().clone();
let mut history_path = config_path;
history_path.push("nushell");
match history.file_format {
HistoryFileFormat::Sqlite => {
history_path.push("history.sqlite3");
}
HistoryFileFormat::PlainText => {
history_path.push("history.txt");
}
}
if clear { if clear {
let _ = std::fs::remove_file(history_path); let _ = std::fs::remove_file(history_path);
// TODO: FIXME also clear the auxiliary files when using sqlite // TODO: FIXME also clear the auxiliary files when using sqlite
@ -67,7 +60,7 @@ impl Command for History {
} else { } else {
let history_reader: Option<Box<dyn ReedlineHistory>> = match history.file_format { let history_reader: Option<Box<dyn ReedlineHistory>> = match history.file_format {
HistoryFileFormat::Sqlite => { HistoryFileFormat::Sqlite => {
SqliteBackedHistory::with_file(history_path.clone().into(), None, None) SqliteBackedHistory::with_file(history_path.clone(), None, None)
.map(|inner| { .map(|inner| {
let boxed: Box<dyn ReedlineHistory> = Box::new(inner); let boxed: Box<dyn ReedlineHistory> = Box::new(inner);
boxed boxed
@ -75,17 +68,15 @@ impl Command for History {
.ok() .ok()
} }
HistoryFileFormat::PlainText => FileBackedHistory::with_file( HistoryFileFormat::PlainText => {
history.max_size as usize, FileBackedHistory::with_file(history.max_size as usize, history_path.clone())
history_path.clone().into(),
)
.map(|inner| { .map(|inner| {
let boxed: Box<dyn ReedlineHistory> = Box::new(inner); let boxed: Box<dyn ReedlineHistory> = Box::new(inner);
boxed boxed
}) })
.ok(), .ok()
}
}; };
match history.file_format { match history.file_format {
HistoryFileFormat::PlainText => Ok(history_reader HistoryFileFormat::PlainText => Ok(history_reader
.and_then(|h| { .and_then(|h| {
@ -114,9 +105,10 @@ impl Command for History {
.ok() .ok()
}) })
.map(move |entries| { .map(move |entries| {
entries.into_iter().enumerate().map(move |(idx, entry)| { entries
create_history_record(idx, entry, long, head) .into_iter()
}) .enumerate()
.map(move |(idx, entry)| create_history_record(idx, entry, long, head))
}) })
.ok_or(ShellError::FileNotFound { .ok_or(ShellError::FileNotFound {
file: history_path.display().to_string(), file: history_path.display().to_string(),
@ -125,9 +117,6 @@ impl Command for History {
.into_pipeline_data(head, signals)), .into_pipeline_data(head, signals)),
} }
} }
} else {
Err(ShellError::ConfigDirNotFound { span: Some(head) })
}
} }
fn examples(&self) -> Vec<Example> { fn examples(&self) -> Vec<Example> {

View File

@ -241,9 +241,8 @@ pub fn eval_config_contents(
} }
} }
pub(crate) fn get_history_path(storage_path: &str, mode: HistoryFileFormat) -> Option<PathBuf> { pub(crate) fn get_history_path(mode: HistoryFileFormat) -> Option<PathBuf> {
nu_path::config_dir().map(|mut history_path| { nu_path::nu_config_dir().map(|mut history_path| {
history_path.push(storage_path);
history_path.push(match mode { history_path.push(match mode {
HistoryFileFormat::PlainText => HISTORY_FILE_TXT, HistoryFileFormat::PlainText => HISTORY_FILE_TXT,
HistoryFileFormat::Sqlite => HISTORY_FILE_SQLITE, HistoryFileFormat::Sqlite => HISTORY_FILE_SQLITE,

View File

@ -52,7 +52,6 @@ use sysinfo::System;
pub fn evaluate_repl( pub fn evaluate_repl(
engine_state: &mut EngineState, engine_state: &mut EngineState,
stack: Stack, stack: Stack,
nushell_path: &str,
prerun_command: Option<Spanned<String>>, prerun_command: Option<Spanned<String>>,
load_std_lib: Option<Spanned<String>>, load_std_lib: Option<Spanned<String>>,
entire_start_time: Instant, entire_start_time: Instant,
@ -99,7 +98,7 @@ pub fn evaluate_repl(
unique_stack.add_env_var("LAST_EXIT_CODE".into(), Value::int(0, Span::unknown())); unique_stack.add_env_var("LAST_EXIT_CODE".into(), Value::int(0, Span::unknown()));
let mut line_editor = get_line_editor(engine_state, nushell_path, use_color)?; let mut line_editor = get_line_editor(engine_state, use_color)?;
let temp_file = temp_dir().join(format!("{}.nu", uuid::Uuid::new_v4())); let temp_file = temp_dir().join(format!("{}.nu", uuid::Uuid::new_v4()));
if let Some(s) = prerun_command { if let Some(s) = prerun_command {
@ -200,7 +199,7 @@ pub fn evaluate_repl(
} }
Err(_) => { Err(_) => {
// line_editor is lost in the error case so reconstruct a new one // line_editor is lost in the error case so reconstruct a new one
line_editor = get_line_editor(engine_state, nushell_path, use_color)?; line_editor = get_line_editor(engine_state, use_color)?;
} }
} }
} }
@ -208,11 +207,7 @@ pub fn evaluate_repl(
Ok(()) Ok(())
} }
fn get_line_editor( fn get_line_editor(engine_state: &mut EngineState, use_color: bool) -> Result<Reedline> {
engine_state: &mut EngineState,
nushell_path: &str,
use_color: bool,
) -> Result<Reedline> {
let mut start_time = std::time::Instant::now(); let mut start_time = std::time::Instant::now();
let mut line_editor = Reedline::create(); let mut line_editor = Reedline::create();
@ -223,7 +218,7 @@ fn get_line_editor(
if let Some(history) = engine_state.history_config() { if let Some(history) = engine_state.history_config() {
start_time = std::time::Instant::now(); start_time = std::time::Instant::now();
line_editor = setup_history(nushell_path, engine_state, line_editor, history)?; line_editor = setup_history(engine_state, line_editor, history)?;
perf!("setup history", start_time, use_color); perf!("setup history", start_time, use_color);
} }
@ -1037,7 +1032,6 @@ fn flush_engine_state_repl_buffer(engine_state: &mut EngineState, line_editor: &
/// Setup history management for Reedline /// Setup history management for Reedline
/// ///
fn setup_history( fn setup_history(
nushell_path: &str,
engine_state: &mut EngineState, engine_state: &mut EngineState,
line_editor: Reedline, line_editor: Reedline,
history: HistoryConfig, history: HistoryConfig,
@ -1049,7 +1043,7 @@ fn setup_history(
None None
}; };
if let Some(path) = crate::config_files::get_history_path(nushell_path, history.file_format) { if let Some(path) = crate::config_files::get_history_path(history.file_format) {
return update_line_editor_history( return update_line_editor_history(
engine_state, engine_state,
path, path,
@ -1317,8 +1311,7 @@ fn trailing_slash_looks_like_path() {
fn are_session_ids_in_sync() { fn are_session_ids_in_sync() {
let engine_state = &mut EngineState::new(); let engine_state = &mut EngineState::new();
let history = engine_state.history_config().unwrap(); let history = engine_state.history_config().unwrap();
let history_path = let history_path = crate::config_files::get_history_path(history.file_format).unwrap();
crate::config_files::get_history_path("nushell", history.file_format).unwrap();
let line_editor = reedline::Reedline::create(); let line_editor = reedline::Reedline::create();
let history_session_id = reedline::Reedline::create_history_session_id(); let history_session_id = reedline::Reedline::create_history_session_id();
let line_editor = update_line_editor_history( let line_editor = update_line_editor_history(

View File

@ -1,5 +1,10 @@
use crate::AbsolutePathBuf; use crate::AbsolutePathBuf;
#[deprecated(
note = "prefer using nu_config_dir() instead of config_dir() joined with NUSHELL_FOLDER"
)]
pub const NUSHELL_FOLDER: &str = "nushell";
pub fn home_dir() -> Option<AbsolutePathBuf> { pub fn home_dir() -> Option<AbsolutePathBuf> {
dirs::home_dir().and_then(|home| AbsolutePathBuf::try_from(home).ok()) dirs::home_dir().and_then(|home| AbsolutePathBuf::try_from(home).ok())
} }
@ -30,3 +35,12 @@ pub fn config_dir() -> Option<AbsolutePathBuf> {
.or_else(|| dirs::config_dir().and_then(|path| AbsolutePathBuf::try_from(path).ok())) .or_else(|| dirs::config_dir().and_then(|path| AbsolutePathBuf::try_from(path).ok()))
.map(|path| path.canonicalize().map(Into::into).unwrap_or(path)) .map(|path| path.canonicalize().map(Into::into).unwrap_or(path))
} }
/// Return the nushell config directory.
pub fn nu_config_dir() -> Option<AbsolutePathBuf> {
config_dir().map(|mut p| {
#[allow(deprecated)]
p.push(NUSHELL_FOLDER);
p
})
}

View File

@ -11,7 +11,10 @@ mod trailing_slash;
pub use components::components; pub use components::components;
pub use expansions::{canonicalize_with, expand_path_with, expand_to_real_path, locate_in_dirs}; pub use expansions::{canonicalize_with, expand_path_with, expand_to_real_path, locate_in_dirs};
pub use helpers::{cache_dir, config_dir, data_dir, home_dir}; pub use helpers::{cache_dir, config_dir, data_dir, home_dir, nu_config_dir};
pub use path::*; pub use path::*;
pub use tilde::expand_tilde; pub use tilde::expand_tilde;
pub use trailing_slash::{has_trailing_slash, strip_trailing_slash}; pub use trailing_slash::{has_trailing_slash, strip_trailing_slash};
#[allow(deprecated)]
pub use helpers::NUSHELL_FOLDER;

View File

@ -3,6 +3,8 @@ use log::warn;
use nu_cli::read_plugin_file; use nu_cli::read_plugin_file;
use nu_cli::{eval_config_contents, eval_source}; use nu_cli::{eval_config_contents, eval_source};
use nu_path::canonicalize_with; use nu_path::canonicalize_with;
#[allow(deprecated)]
use nu_path::NUSHELL_FOLDER;
use nu_protocol::{ use nu_protocol::{
engine::{EngineState, Stack, StateWorkingSet}, engine::{EngineState, Stack, StateWorkingSet},
report_error, report_error_new, Config, ParseError, PipelineData, Spanned, report_error, report_error_new, Config, ParseError, PipelineData, Spanned,
@ -17,7 +19,6 @@ use std::{
sync::Arc, sync::Arc,
}; };
pub(crate) const NUSHELL_FOLDER: &str = "nushell";
const CONFIG_FILE: &str = "config.nu"; const CONFIG_FILE: &str = "config.nu";
const ENV_FILE: &str = "env.nu"; const ENV_FILE: &str = "env.nu";
const LOGINSHELL_FILE: &str = "login.nu"; const LOGINSHELL_FILE: &str = "login.nu";
@ -50,6 +51,7 @@ pub(crate) fn read_config_file(
} }
} }
} else if let Some(mut config_path) = nu_path::config_dir() { } else if let Some(mut config_path) = nu_path::config_dir() {
#[allow(deprecated)]
config_path.push(NUSHELL_FOLDER); config_path.push(NUSHELL_FOLDER);
// Create config directory if it does not exist // Create config directory if it does not exist
@ -135,6 +137,7 @@ pub(crate) fn read_loginshell_file(engine_state: &mut EngineState, stack: &mut S
// read and execute loginshell file if exists // read and execute loginshell file if exists
if let Some(mut config_path) = nu_path::config_dir() { if let Some(mut config_path) = nu_path::config_dir() {
#[allow(deprecated)]
config_path.push(NUSHELL_FOLDER); config_path.push(NUSHELL_FOLDER);
config_path.push(LOGINSHELL_FILE); config_path.push(LOGINSHELL_FILE);
@ -268,6 +271,7 @@ pub(crate) fn setup_config(
); );
let result = catch_unwind(AssertUnwindSafe(|| { let result = catch_unwind(AssertUnwindSafe(|| {
#[cfg(feature = "plugin")] #[cfg(feature = "plugin")]
#[allow(deprecated)]
read_plugin_file(engine_state, plugin_file, NUSHELL_FOLDER); read_plugin_file(engine_state, plugin_file, NUSHELL_FOLDER);
read_config_file(engine_state, stack, env_file, true); read_config_file(engine_state, stack, env_file, true);
@ -301,6 +305,7 @@ pub(crate) fn set_config_path(
let config_path = match config_file { let config_path = match config_file {
Some(s) => canonicalize_with(&s.item, cwd).ok(), Some(s) => canonicalize_with(&s.item, cwd).ok(),
None => nu_path::config_dir().map(|mut p| { None => nu_path::config_dir().map(|mut p| {
#[allow(deprecated)]
p.push(NUSHELL_FOLDER); p.push(NUSHELL_FOLDER);
let mut p = canonicalize_with(&p, cwd).unwrap_or(p.into()); let mut p = canonicalize_with(&p, cwd).unwrap_or(p.into());
p.push(default_config_name); p.push(default_config_name);

View File

@ -1,5 +1,4 @@
#[cfg(feature = "plugin")] #[cfg(feature = "plugin")]
use crate::config_files::NUSHELL_FOLDER;
use crate::{ use crate::{
command, command,
config_files::{self, setup_config}, config_files::{self, setup_config},
@ -8,6 +7,8 @@ use log::trace;
#[cfg(feature = "plugin")] #[cfg(feature = "plugin")]
use nu_cli::read_plugin_file; use nu_cli::read_plugin_file;
use nu_cli::{evaluate_commands, evaluate_file, evaluate_repl, EvaluateCommandsOpts}; use nu_cli::{evaluate_commands, evaluate_file, evaluate_repl, EvaluateCommandsOpts};
#[allow(deprecated)]
use nu_path::NUSHELL_FOLDER;
use nu_protocol::{ use nu_protocol::{
engine::{EngineState, Stack}, engine::{EngineState, Stack},
report_error_new, PipelineData, Spanned, report_error_new, PipelineData, Spanned,
@ -37,6 +38,7 @@ pub(crate) fn run_commands(
// if the --no-config-file(-n) flag is passed, do not load plugin, env, or config files // if the --no-config-file(-n) flag is passed, do not load plugin, env, or config files
if parsed_nu_cli_args.no_config_file.is_none() { if parsed_nu_cli_args.no_config_file.is_none() {
#[cfg(feature = "plugin")] #[cfg(feature = "plugin")]
#[allow(deprecated)]
read_plugin_file(engine_state, parsed_nu_cli_args.plugin_file, NUSHELL_FOLDER); read_plugin_file(engine_state, parsed_nu_cli_args.plugin_file, NUSHELL_FOLDER);
perf!("read plugins", start_time, use_color); perf!("read plugins", start_time, use_color);
@ -125,6 +127,7 @@ pub(crate) fn run_file(
if parsed_nu_cli_args.no_config_file.is_none() { if parsed_nu_cli_args.no_config_file.is_none() {
let start_time = std::time::Instant::now(); let start_time = std::time::Instant::now();
#[cfg(feature = "plugin")] #[cfg(feature = "plugin")]
#[allow(deprecated)]
read_plugin_file(engine_state, parsed_nu_cli_args.plugin_file, NUSHELL_FOLDER); read_plugin_file(engine_state, parsed_nu_cli_args.plugin_file, NUSHELL_FOLDER);
perf!("read plugins", start_time, use_color); perf!("read plugins", start_time, use_color);
@ -216,7 +219,6 @@ pub(crate) fn run_repl(
let ret_val = evaluate_repl( let ret_val = evaluate_repl(
engine_state, engine_state,
stack, stack,
config_files::NUSHELL_FOLDER,
parsed_nu_cli_args.execute, parsed_nu_cli_args.execute,
parsed_nu_cli_args.no_std_lib, parsed_nu_cli_args.no_std_lib,
entire_start_time, entire_start_time,