config: generate errors for things like --config tarm=foo

Invalid option names, or values that evaluate as nil (such as the `foo`
above: that's treated as a global variable reference, but `foo` isn't a
defined global and evaluates as `nil`) will now cause the program
startup to error out with an actionable error message.

Previously, the invalid config name would generate a warning, and the
invalid value would silently have no effect as it has the same effect as
omitting the named value and leaving it as its default value.

I think these cases should both immediately error out and stop
further processing, so that's what we're doing.

This commit also adds support for adding:

```
   #[dynamic(deprecated = "use newer option instead")]
   pub some_config_value: bool,
```

but not options currently use this.
This commit is contained in:
Wez Furlong committed 2022-05-21 13:10:30 -07:00
1 parent 736169a752
commit da7da888cd
9 files changed
+101 -14

No files matched your search

+15 -2
View File
@@ -779,13 +779,26 @@ impl Config {
) -> anyhow::Result<mlua::Value<'l>> {
let overrides = CONFIG_OVERRIDES.lock().unwrap();
for (key, value) in &*overrides {
if value == "nil" {
// Literal nil as the value is the same as not specifying the value.
// We special case this here as we want to explicitly check for
// the value evaluating as nil, as can happen in the case where the
// user specifies something like: `--config term=xterm`.
// The RHS references a global that doesn't exist and evaluates as
// nil. We want to raise this as an error.
continue;
}
let literal = value.escape_debug();
let code = format!(
r#"
local wezterm = require 'wezterm';
config.{} = {};
local value = {value};
if value == nil then
error("{literal} evaluated as nil. Check for missing quotes or other syntax issues")
end
config.{key} = value;
return config;
"#,
key, value
);
let chunk = lua.load(&code);
let chunk = chunk.set_name(&format!("--config {}={}", key, value))?;
+19 -7
View File
@@ -2,7 +2,7 @@
use anyhow::{anyhow, bail, Context, Error};
use lazy_static::lazy_static;
use mlua::{FromLua, Lua};
use mlua::Lua;
use ordered_float::NotNan;
use smol::channel::{Receiver, Sender};
use smol::prelude::*;
@@ -17,7 +17,7 @@ use std::rc::Rc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use wezterm_dynamic::{ToDynamic, Value};
use wezterm_dynamic::{FromDynamic, FromDynamicOptions, ToDynamic, UnknownFieldAction, Value};
mod background;
mod bell;
@@ -255,8 +255,16 @@ fn default_config_with_overrides_applied() -> anyhow::Result<Config> {
let table = mlua::Value::Table(lua.create_table()?);
let config = Config::apply_overrides_to(&lua, table)?;
let cfg: Config = Config::from_lua(config, &lua)
.context("Error converting lua value from overrides to Config struct")?;
let dyn_config = luahelper::lua_value_to_dynamic(config)?;
let cfg: Config = Config::from_dynamic(
&dyn_config,
FromDynamicOptions {
unknown_fields: UnknownFieldAction::Deny,
deprecated_fields: UnknownFieldAction::Warn,
},
)
.context("Error converting lua value from overrides to Config struct")?;
// Compute but discard the key bindings here so that we raise any
// problems earlier than we use them.
let _ = cfg.key_bindings();
@@ -268,15 +276,16 @@ pub fn common_init(
config_file: Option<&OsString>,
overrides: &[(String, String)],
skip_config: bool,
) {
) -> anyhow::Result<()> {
if let Some(config_file) = config_file {
set_config_file_override(Path::new(config_file));
} else if skip_config {
CONFIG_SKIP.store(true, Ordering::Relaxed);
}
set_config_overrides(overrides);
set_config_overrides(overrides)?;
reload();
Ok(())
}
pub fn assign_error_callback(cb: ErrorCallback) {
@@ -320,8 +329,11 @@ pub fn set_config_file_override(path: &Path) {
.replace(path.to_path_buf());
}
pub fn set_config_overrides(items: &[(String, String)]) {
pub fn set_config_overrides(items: &[(String, String)]) -> anyhow::Result<()> {
*CONFIG_OVERRIDES.lock().unwrap() = items.to_vec();
let _ = default_config_with_overrides_applied()?;
Ok(())
}
pub fn is_config_overridden() -> bool {
+1
View File
@@ -46,6 +46,7 @@ As features stabilize some brief notes about them will accumulate here.
* Search mode's search term is now remembered globally between activations of search mode. [#1912](https://github.com/wez/wezterm/issues/1912)
* Quickselect no longer jumps to the bottom of the viewport when activated, allowing you to quickselect within the current viewport region
* Quickselect now supports multi-line anchors such as `^` and `$`. [#2008](https://github.com/wez/wezterm/issues/2008)
* Overriding config using the cli `--config` option will now error out and prevent starting up if unknown config options are specified, or if the value evaluates to `nil`. Unknown options continue to generate warnings (rather than errors) when observed in the config file so that you're not "locked out" of wezterm if you make a typo in the config file.
#### Fixed
* Flush after replying to XTGETTCAP and DECRQM. [#1850](https://github.com/wez/wezterm/issues/1850) [#1950](https://github.com/wez/wezterm/issues/1950)
+31 -2
View File
@@ -72,6 +72,7 @@ pub struct FieldInfo<'a> {
pub allow_default: DefValue,
pub into: Option<Path>,
pub try_from: Option<Path>,
pub deprecated: Option<String>,
}
impl<'a> FieldInfo<'a> {
@@ -100,6 +101,15 @@ impl<'a> FieldInfo<'a> {
let name = &self.name;
let ident = &self.field.ident;
let ty = &self.field.ty;
let check_deprecated = if let Some(reason) = &self.deprecated {
quote!(
wezterm_dynamic::Error::raise_deprecated_fields(options, #struct_name, #name, #reason)?;
)
} else {
quote!()
};
if self.skip {
quote!()
} else if self.flatten {
@@ -118,6 +128,7 @@ impl<'a> FieldInfo<'a> {
#ident: match obj.get_by_str(#name) {
Some(v) => {
use std::convert::TryFrom;
#check_deprecated
let target = <#try_from>::from_dynamic(v, options)
.map_err(|source| source.field_context(
#struct_name,
@@ -142,6 +153,7 @@ impl<'a> FieldInfo<'a> {
#ident: match obj.get_by_str(&#name) {
Some(v) => {
use std::convert::TryFrom;
#check_deprecated
let target = <#try_from>::from_dynamic(v, options)
.map_err(|source| source.field_context(
#struct_name,
@@ -165,7 +177,10 @@ impl<'a> FieldInfo<'a> {
quote!(
#ident: {
use std::convert::TryFrom;
let target = <#try_from>::from_dynamic(obj.get_by_str(#name).unwrap_or(&Value::Null), options)
let target = <#try_from>::from_dynamic(obj.get_by_str(#name).map(|v| {
#check_deprecated
v
}).unwrap_or(&Value::Null), options)
.map_err(|source| source.field_context(
#struct_name,
#name,
@@ -187,6 +202,7 @@ impl<'a> FieldInfo<'a> {
quote!(
#ident: match obj.get_by_str(#name) {
Some(v) => {
#check_deprecated
<#ty>::from_dynamic(v, options)
.map_err(|source| source.field_context(
#struct_name,
@@ -204,6 +220,7 @@ impl<'a> FieldInfo<'a> {
quote!(
#ident: match obj.get_by_str(#name) {
Some(v) => {
#check_deprecated
<#ty>::from_dynamic(v, options)
.map_err(|source| source.field_context(
#struct_name,
@@ -221,7 +238,11 @@ impl<'a> FieldInfo<'a> {
quote!(
#ident:
<#ty>::from_dynamic(
obj.get_by_str(#name).unwrap_or(&Value::Null),
obj.get_by_str(#name).map(|v| {
#check_deprecated
v
}).
unwrap_or(&Value::Null),
options
)
.map_err(|source| source.field_context(#struct_name, #name, obj))?,
@@ -239,6 +260,7 @@ pub fn field_info(field: &Field) -> Result<FieldInfo> {
let mut allow_default = DefValue::None;
let mut try_from = None;
let mut into = None;
let mut deprecated = None;
for attr in &field.attrs {
if !attr.path.is_ident("dynamic") {
@@ -265,6 +287,12 @@ pub fn field_info(field: &Field) -> Result<FieldInfo> {
continue;
}
}
if value.path.is_ident("deprecated") {
if let Lit::Str(s) = &value.lit {
deprecated.replace(s.value());
continue;
}
}
if value.path.is_ident("into") {
if let Lit::Str(s) = &value.lit {
into = Some(s.parse()?);
@@ -306,5 +334,6 @@ pub fn field_info(field: &Field) -> Result<FieldInfo> {
allow_default,
try_from,
into,
deprecated,
})
}
+31
View File
@@ -51,6 +51,12 @@ pub enum Error {
type_name: &'static str,
key_type: String,
},
#[error("{}::{} is deprecated: {}", .type_name, .field_name, .reason)]
DeprecatedField {
type_name: &'static str,
field_name: &'static str,
reason: &'static str,
},
}
impl Error {
@@ -84,6 +90,31 @@ impl Error {
errors
}
pub fn raise_deprecated_fields(
options: FromDynamicOptions,
type_name: &'static str,
field_name: &'static str,
reason: &'static str,
) -> Result<(), Self> {
if options.deprecated_fields == UnknownFieldAction::Ignore {
return Ok(());
}
let err = Self::DeprecatedField {
type_name,
field_name,
reason,
};
match options.deprecated_fields {
UnknownFieldAction::Deny => Err(err),
UnknownFieldAction::Warn => {
log::warn!("{:#}", err);
Ok(())
}
UnknownFieldAction::Ignore => unreachable!(),
}
}
pub fn raise_unknown_fields(
options: FromDynamicOptions,
type_name: &'static str,
+1
View File
@@ -27,6 +27,7 @@ impl Default for UnknownFieldAction {
#[derive(Copy, Clone, Debug, Default)]
pub struct FromDynamicOptions {
pub unknown_fields: UnknownFieldAction,
pub deprecated_fields: UnknownFieldAction,
}
impl FromDynamicOptions {
+1 -1
View File
@@ -942,7 +942,7 @@ fn run() -> anyhow::Result<()> {
opts.config_file.as_ref(),
&opts.config_override,
opts.skip_config,
);
)?;
let config = config::configuration();
let sub = match opts.cmd.as_ref().cloned() {
+1 -1
View File
@@ -76,7 +76,7 @@ fn run() -> anyhow::Result<()> {
opts.config_file.as_ref(),
&opts.config_override,
opts.skip_config,
);
)?;
let config = config::configuration();
#[cfg(unix)]
+1 -1
View File
@@ -379,7 +379,7 @@ fn run() -> anyhow::Result<()> {
opts.config_file.as_ref(),
&opts.config_override,
opts.skip_config,
);
)?;
let config = config::configuration();
match opts