Reduce duplication in history path construction (#13475)

# Description
Currently there is a bit of chaos regarding construction of history file
paths. Various pieces of code across a number of crates reimplement the
same/similar logic:
- There is `get_history_path`, but it requires a directory parameter (it
really just joins it with a file name).
- Some places use a const for the directory parameter, others use a
string literal - in all cases the value seems to be `"nushell"`.
- Some places assume the `"nushell"` value, other plumb it down from
close to the top of the call stack.
- Some places use a constant for history file names while others assume
it.

This PR tries to make it so that the history/config path format is
defined in a single places and so dependencies on it are easier to
follow:
- It removes `get_history_path` and adds a `file_path` method to
`HistoryConfig` instead (an extra motivation being, this is a convenient
place that can be used from all creates that need a history file path)
- Adds a `nu_config_dir` function that returns the nushell configuration
directory.
- Updates existing code to rely on the above, effectively removing
duplicate uses of `"nushell"` and `NUSHELL_FOLDER` and assumptions about
file names associated with different history formats

# User-Facing Changes
None
This commit is contained in:
Piotr Kufel
2024-10-11 05:51:50 -07:00
committed by GitHub
parent 9f714e62cb
commit bcb7ef48b6
12 changed files with 82 additions and 145 deletions

View File

@ -9,6 +9,16 @@ pub enum HistoryFileFormat {
Plaintext,
}
impl HistoryFileFormat {
pub fn default_file_name(self) -> std::path::PathBuf {
match self {
HistoryFileFormat::Plaintext => "history.txt",
HistoryFileFormat::Sqlite => "history.sqlite3",
}
.into()
}
}
impl FromStr for HistoryFileFormat {
type Err = &'static str;
@ -29,6 +39,15 @@ pub struct HistoryConfig {
pub isolation: bool,
}
impl HistoryConfig {
pub fn file_path(&self) -> Option<std::path::PathBuf> {
nu_path::nu_config_dir().map(|mut history_path| {
history_path.push(self.file_format.default_file_name());
history_path.into()
})
}
}
impl Default for HistoryConfig {
fn default() -> Self {
Self {

View File

@ -34,11 +34,8 @@ pub(crate) fn create_nu_constant(engine_state: &EngineState, span: Span) -> Valu
let mut record = Record::new();
let config_path = match nu_path::config_dir() {
Some(mut path) => {
path.push("nushell");
Ok(canonicalize_path(engine_state, path.as_ref()))
}
let config_path = match nu_path::nu_config_dir() {
Some(path) => Ok(canonicalize_path(engine_state, path.as_ref())),
None => Err(Value::error(
ShellError::ConfigDirNotFound { span: Some(span) },
span,