mirror of
https://github.com/nushell/nushell
synced 2025-01-13 21:55:07 +00:00
4ed25b63a6
# Release-Notes Short Description * Nushell now always loads its internal `default_env.nu` before the user `env.nu` is loaded, then loads the internal `default_config.nu` before the user's `config.nu` is loaded. This allows for a simpler user-configuration experience. The Configuration Chapter of the Book will be updated soon with the new behavior. # Description Implements the main ideas in #13671 and a few more: * Users can now specify only the environment and config options they want to override in *their* `env.nu` and `config.nu`and yet still have access to all of the defaults: * `default_env.nu` (internally defined) will be loaded whenever (and before) the user's `env.nu` is loaded. * `default_config.nu` (internally defined) will be loaded whenever (and before) the user's `config.nu` is loaded. * No more 900+ line config out-of-the-box. * Faster startup (again): ~40-45% improvement in launch time with a default configuration. * New keys that are added to the defaults in the future will automatically be available to all users after updating Nushell. No need to regenerate config to get the new defaults. * It is now possible to have different internal defaults (which will be used with `-c` and scripts) vs. REPL defaults. This would have solved many of the user complaints about the [`display_errors` implementation](https://www.nushell.sh/blog/2024-09-17-nushell_0_98_0.html#non-zero-exit-codes-are-now-errors-toc). * A basic "scaffold" `config.nu` and `env.nu` are created on first launch (if the config directory isn't present). * Improved "out-of-the-box" experience (OOBE) - No longer asks to create the files; the minimal scaffolding will be automatically created. If deleted, they will not be regenerated. This provides a better "out-of-the-box" experience for the user as they no longer have to make this decision (without much info on the pros or cons) when first launching. * <s>(New: 2024-11-07) Runs the env_conversions process after the `default_env.nu` is loaded so that users can treat `Path`/`PATH` as lists in their own config.</s> * (New: 2024-11-08) Given the changes in #13802, `default_config.nu` will be a minimal file to minimize load-times. This shaves another (on my system) ~3ms off the base launch time. * Related: Keybindings, menus, and hooks that are already internal defaults are no longer duplicated in `$env.config`. The documentation will be updated to cover these scenarios. * (New: 2024-11-08) Move existing "full" `default_config.nu` to `sample_config.nu` for short-term "documentation" purposes. * (New: 2024-11-18) Move the `dark-theme` and `light-theme` to Standard Library and demonstrate their use - Also improves startup times, but we're reaching the limit of optimization. * (New: 2024-11-18) Extensively documented/commented `sample_env.nu` and `sample_config.nu`. These can be displayed in-shell using (for example) `config nu --sample | nu-highlight | less -R`. Note: Much of this will eventually be moved to or (some) duplicated in the Doc. But for now, this some nice in-shell doc that replaces the older "commented/documented default". * (New: 2024-11-20) Runs the `ENV_CONVERSIONS` process (1) after the `default_env.nu` (allows `PATH` to be used as a list in user's `env.nu`) and (2) before `default_config.nu` is loaded (allows user's `ENV_CONVERSIONS` from their `env.nu` to be used in their `config.nu`). * <s>(New: 2024-11-20) The default `ENV_CONVERSIONS` is now an empty record. The internal Rust code handles `PATH` (and variants) conversions regardless of the `ENV_CONVERSIONS` variable. This shaves a *very* small amount of time off the startup.</s> Reset - Looks like there might be a bug in `nu-enginer::env::ensure_path()` on Windows that would need to be fixed in order for this to work. # User-Facing Changes By default, you shouldn't see much, if any, change when running this with your existing configuration. To see the greatest benefit from these changes, you'll probably want to start with a "fresh" config. This can be easily tested using something like: ```nushell let temp_home = (mktemp -d) $env.XDG_CONFIG_HOME = $temp_home $env.XDG_DATA_HOME = $temp_home ./target/release/nu ``` You should see a message where the (mostly empty) `env.nu` and `config.nu` are created on first start. Defaults should be the same (or similar to) those before the PR. Please let me know if you notice any differences. --- Users should now specify configuration in terms of overrides of each setting. For instance, rather than modifying `history` settings in the monolithic `config.nu`, the following is recommended in an updated `config.nu`: ```nu $env.config.history = { file_format: sqlite, sync_on_enter: true isolation: true max_size: 1_000_000 } ``` or even just: ```nu $env.config.history.file_format = sqlite $env.config.history.isolation: true $env.config.history.max_size = 1_000_000 ``` Note: It seems many users are already appending a `source my_config.nu` (or similar pattern) to the end of the existing `config.nu` to make updates easier. In this case, they will likely want to remove all of the previous defaults and just move their `my_config.nu` to `config.nu`. Note: It should be unlikely that there are any breaking changes here, but there's a slim chance that some code, somewhere, *expects* an absence of certain config values. Otherwise, all config values are available before and after this change. # Tests + Formatting - 🟢 `toolkit fmt` - 🟢 `toolkit clippy` - 🟢 `toolkit test` - 🟢 `toolkit test stdlib` # After Submitting Configuration Chapter (and related) of the doc is currently WIP and will be finished in time for 0.101 release.
317 lines
9.9 KiB
Rust
317 lines
9.9 KiB
Rust
use log::warn;
|
|
#[cfg(feature = "plugin")]
|
|
use nu_cli::read_plugin_file;
|
|
use nu_cli::{eval_config_contents, eval_source};
|
|
use nu_engine::convert_env_values;
|
|
use nu_path::canonicalize_with;
|
|
use nu_protocol::{
|
|
engine::{EngineState, Stack, StateWorkingSet},
|
|
report_parse_error, report_shell_error, Config, ParseError, PipelineData, Spanned,
|
|
};
|
|
use nu_utils::{get_default_config, get_default_env, get_scaffold_config, get_scaffold_env, perf};
|
|
use std::{
|
|
fs,
|
|
fs::File,
|
|
io::{Result, Write},
|
|
panic::{catch_unwind, AssertUnwindSafe},
|
|
path::Path,
|
|
sync::Arc,
|
|
};
|
|
|
|
const CONFIG_FILE: &str = "config.nu";
|
|
const ENV_FILE: &str = "env.nu";
|
|
const LOGINSHELL_FILE: &str = "login.nu";
|
|
|
|
pub(crate) fn read_config_file(
|
|
engine_state: &mut EngineState,
|
|
stack: &mut Stack,
|
|
config_file: Option<Spanned<String>>,
|
|
is_env_config: bool,
|
|
create_scaffold: bool,
|
|
) {
|
|
warn!(
|
|
"read_config_file() config_file_specified: {:?}, is_env_config: {is_env_config}",
|
|
&config_file
|
|
);
|
|
|
|
if is_env_config {
|
|
eval_default_config(engine_state, stack, get_default_env(), is_env_config);
|
|
|
|
let start_time = std::time::Instant::now();
|
|
let config = engine_state.get_config();
|
|
let use_color = config.use_ansi_coloring;
|
|
// Translate environment variables from Strings to Values
|
|
if let Err(e) = convert_env_values(engine_state, stack) {
|
|
report_shell_error(engine_state, &e);
|
|
}
|
|
|
|
perf!(
|
|
"translate env vars after default_env.nu",
|
|
start_time,
|
|
use_color
|
|
);
|
|
} else {
|
|
let start_time = std::time::Instant::now();
|
|
let config = engine_state.get_config();
|
|
let use_color = config.use_ansi_coloring;
|
|
if let Err(e) = convert_env_values(engine_state, stack) {
|
|
report_shell_error(engine_state, &e);
|
|
}
|
|
perf!(
|
|
"translate env vars before default_config.nu",
|
|
start_time,
|
|
use_color
|
|
);
|
|
|
|
eval_default_config(engine_state, stack, get_default_config(), is_env_config);
|
|
};
|
|
|
|
warn!("read_config_file() loading_defaults is_env_config: {is_env_config}");
|
|
|
|
// Load config startup file
|
|
if let Some(file) = config_file {
|
|
match engine_state.cwd_as_string(Some(stack)) {
|
|
Ok(cwd) => {
|
|
if let Ok(path) = canonicalize_with(&file.item, cwd) {
|
|
eval_config_contents(path, engine_state, stack);
|
|
} else {
|
|
let e = ParseError::FileNotFound(file.item, file.span);
|
|
report_parse_error(&StateWorkingSet::new(engine_state), &e);
|
|
}
|
|
}
|
|
Err(e) => {
|
|
report_shell_error(engine_state, &e);
|
|
}
|
|
}
|
|
} else if let Some(mut config_path) = nu_path::nu_config_dir() {
|
|
// Create config directory if it does not exist
|
|
if !config_path.exists() {
|
|
if let Err(err) = std::fs::create_dir_all(&config_path) {
|
|
eprintln!("Failed to create config directory: {err}");
|
|
return;
|
|
}
|
|
}
|
|
|
|
config_path.push(if is_env_config { ENV_FILE } else { CONFIG_FILE });
|
|
|
|
if !config_path.exists() {
|
|
let scaffold_config_file = if is_env_config {
|
|
get_scaffold_env()
|
|
} else {
|
|
get_scaffold_config()
|
|
};
|
|
|
|
match create_scaffold {
|
|
true => {
|
|
if let Ok(mut output) = File::create(&config_path) {
|
|
if write!(output, "{scaffold_config_file}").is_ok() {
|
|
let config_type = if is_env_config {
|
|
"Environment config"
|
|
} else {
|
|
"Config"
|
|
};
|
|
println!(
|
|
"{} file created at: {}",
|
|
config_type,
|
|
config_path.to_string_lossy()
|
|
);
|
|
} else {
|
|
eprintln!(
|
|
"Unable to write to {}, sourcing default file instead",
|
|
config_path.to_string_lossy(),
|
|
);
|
|
return;
|
|
}
|
|
} else {
|
|
eprintln!("Unable to create {scaffold_config_file}");
|
|
return;
|
|
}
|
|
}
|
|
_ => {
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
eval_config_contents(config_path.into(), engine_state, stack);
|
|
}
|
|
}
|
|
|
|
pub(crate) fn read_loginshell_file(engine_state: &mut EngineState, stack: &mut Stack) {
|
|
warn!(
|
|
"read_loginshell_file() {}:{}:{}",
|
|
file!(),
|
|
line!(),
|
|
column!()
|
|
);
|
|
|
|
// read and execute loginshell file if exists
|
|
if let Some(mut config_path) = nu_path::nu_config_dir() {
|
|
config_path.push(LOGINSHELL_FILE);
|
|
|
|
warn!("loginshell_file: {}", config_path.display());
|
|
|
|
if config_path.exists() {
|
|
eval_config_contents(config_path.into(), engine_state, stack);
|
|
}
|
|
}
|
|
}
|
|
|
|
pub(crate) fn read_default_env_file(engine_state: &mut EngineState, stack: &mut Stack) {
|
|
let config_file = get_default_env();
|
|
eval_source(
|
|
engine_state,
|
|
stack,
|
|
config_file.as_bytes(),
|
|
"default_env.nu",
|
|
PipelineData::empty(),
|
|
false,
|
|
);
|
|
|
|
warn!(
|
|
"read_default_env_file() env_file_contents: {config_file} {}:{}:{}",
|
|
file!(),
|
|
line!(),
|
|
column!()
|
|
);
|
|
|
|
// Merge the environment in case env vars changed in the config
|
|
if let Err(e) = engine_state.merge_env(stack) {
|
|
report_shell_error(engine_state, &e);
|
|
}
|
|
}
|
|
|
|
/// Get files sorted lexicographically
|
|
///
|
|
/// uses `impl Ord for String`
|
|
fn read_and_sort_directory(path: &Path) -> Result<Vec<String>> {
|
|
let mut entries = Vec::new();
|
|
|
|
for entry in fs::read_dir(path)? {
|
|
let entry = entry?;
|
|
let file_name = entry.file_name();
|
|
let file_name_str = file_name.into_string().unwrap_or_default();
|
|
entries.push(file_name_str);
|
|
}
|
|
|
|
entries.sort();
|
|
|
|
Ok(entries)
|
|
}
|
|
|
|
pub(crate) fn read_vendor_autoload_files(engine_state: &mut EngineState, stack: &mut Stack) {
|
|
warn!(
|
|
"read_vendor_autoload_files() {}:{}:{}",
|
|
file!(),
|
|
line!(),
|
|
column!()
|
|
);
|
|
|
|
// The evaluation order is first determined by the semantics of `get_vendor_autoload_dirs`
|
|
// to determine the order of directories to evaluate
|
|
for autoload_dir in nu_protocol::eval_const::get_vendor_autoload_dirs(engine_state) {
|
|
warn!("read_vendor_autoload_files: {}", autoload_dir.display());
|
|
|
|
if autoload_dir.exists() {
|
|
// on a second levels files are lexicographically sorted by the string of the filename
|
|
let entries = read_and_sort_directory(&autoload_dir);
|
|
if let Ok(entries) = entries {
|
|
for entry in entries {
|
|
if !entry.ends_with(".nu") {
|
|
continue;
|
|
}
|
|
let path = autoload_dir.join(entry);
|
|
warn!("AutoLoading: {:?}", path);
|
|
eval_config_contents(path, engine_state, stack);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fn eval_default_config(
|
|
engine_state: &mut EngineState,
|
|
stack: &mut Stack,
|
|
config_file: &str,
|
|
is_env_config: bool,
|
|
) {
|
|
warn!("eval_default_config() is_env_config: {}", is_env_config);
|
|
eval_source(
|
|
engine_state,
|
|
stack,
|
|
config_file.as_bytes(),
|
|
if is_env_config {
|
|
"default_env.nu"
|
|
} else {
|
|
"default_config.nu"
|
|
},
|
|
PipelineData::empty(),
|
|
false,
|
|
);
|
|
|
|
// Merge the environment in case env vars changed in the config
|
|
if let Err(e) = engine_state.merge_env(stack) {
|
|
report_shell_error(engine_state, &e);
|
|
}
|
|
}
|
|
|
|
pub(crate) fn setup_config(
|
|
engine_state: &mut EngineState,
|
|
stack: &mut Stack,
|
|
#[cfg(feature = "plugin")] plugin_file: Option<Spanned<String>>,
|
|
config_file: Option<Spanned<String>>,
|
|
env_file: Option<Spanned<String>>,
|
|
is_login_shell: bool,
|
|
) {
|
|
warn!(
|
|
"setup_config() config_file_specified: {:?}, env_file_specified: {:?}, login: {}",
|
|
&config_file, &env_file, is_login_shell
|
|
);
|
|
|
|
let create_scaffold = nu_path::nu_config_dir().map_or(false, |p| !p.exists());
|
|
|
|
let result = catch_unwind(AssertUnwindSafe(|| {
|
|
#[cfg(feature = "plugin")]
|
|
read_plugin_file(engine_state, plugin_file);
|
|
|
|
read_config_file(engine_state, stack, env_file, true, create_scaffold);
|
|
read_config_file(engine_state, stack, config_file, false, create_scaffold);
|
|
|
|
if is_login_shell {
|
|
read_loginshell_file(engine_state, stack);
|
|
}
|
|
// read and auto load vendor autoload files
|
|
read_vendor_autoload_files(engine_state, stack);
|
|
}));
|
|
if result.is_err() {
|
|
eprintln!(
|
|
"A panic occurred while reading configuration files, using default configuration."
|
|
);
|
|
engine_state.config = Arc::new(Config::default())
|
|
}
|
|
}
|
|
|
|
pub(crate) fn set_config_path(
|
|
engine_state: &mut EngineState,
|
|
cwd: &Path,
|
|
default_config_name: &str,
|
|
key: &str,
|
|
config_file: Option<&Spanned<String>>,
|
|
) {
|
|
warn!(
|
|
"set_config_path() cwd: {:?}, default_config: {}, key: {}, config_file_specified: {:?}",
|
|
&cwd, &default_config_name, &key, &config_file
|
|
);
|
|
let config_path = match config_file {
|
|
Some(s) => canonicalize_with(&s.item, cwd).ok(),
|
|
None => nu_path::nu_config_dir().map(|p| {
|
|
let mut p = canonicalize_with(&p, cwd).unwrap_or(p.into());
|
|
p.push(default_config_name);
|
|
canonicalize_with(&p, cwd).unwrap_or(p)
|
|
}),
|
|
};
|
|
|
|
if let Some(path) = config_path {
|
|
engine_state.set_config_path(key, path);
|
|
}
|
|
}
|