Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

settings: Fix command aliases json schema (#57812)

Dinoe017293aedca
diff --git a/crates/settings/src/settings_store.rs b/crates/settings/src/settings_store.rs
index 4fcbfcde47e..29d9f91dc6b 100644
--- a/crates/settings/src/settings_store.rs
+++ b/crates/settings/src/settings_store.rs
@@ -13,7 +13,7 @@ use gpui::{
use paths::{local_settings_file_relative_path, task_file_name};
use schemars::{JsonSchema, json_schema};
use serde_json::Value;
-use settings_content::{ActionName, ParseStatus};
+use settings_content::{CommandAliasTarget, ParseStatus};
use std::{
any::{Any, TypeId, type_name},
fmt::Debug,
@@ -1287,9 +1287,9 @@ impl SettingsStore {
}
if !params.action_names.is_empty() {
- replace_subschema::<ActionName>(&mut generator, || {
- ActionName::build_schema(
- params.action_names.iter().copied(),
+ replace_subschema::<CommandAliasTarget>(&mut generator, || {
+ CommandAliasTarget::build_schema(
+ params.action_names,
params.action_documentation,
params.deprecations,
params.deprecation_messages,
diff --git a/crates/settings_content/src/action.rs b/crates/settings_content/src/action.rs
index b70a15cb4b7..8793d82fb09 100644
--- a/crates/settings_content/src/action.rs
+++ b/crates/settings_content/src/action.rs
@@ -7,6 +7,94 @@ use serde::{Deserialize, Serialize};
use serde_json::Value;
use settings_macros::MergeFrom;
+/// The value of an entry in `command_aliases`, either a registered action name
+/// or an arbitrary string, for example, a vim command like `"w"` or `"wq"`.
+///
+/// This is a separate type from `ActionName` on purpose, as `ActionName` is
+/// also used by keymap bindings, which only accept registered action names, and
+/// we don't want to weaken those guarantees and accept any arbitrary string.
+#[derive(Serialize, Deserialize, Default, MergeFrom, Clone, Debug, PartialEq)]
+#[serde(transparent)]
+pub struct CommandAliasTarget(String);
+
+impl CommandAliasTarget {
+ pub fn new(name: impl Into<String>) -> Self {
+ Self(name.into())
+ }
+
+ /// Build the runtime schema, an `anyOf` whose entries are the same as the
+ /// ones produced by [`ActionName::build_schema`] plus a final fallback for
+ /// arbitrary strings that aren't registered actions.
+ pub fn build_schema(
+ action_names: &[&str],
+ action_documentation: &HashMap<&str, &str>,
+ deprecations: &HashMap<&str, &str>,
+ deprecation_messages: &HashMap<&str, &str>,
+ ) -> Schema {
+ let action_schema = ActionName::build_schema(
+ action_names.iter().copied(),
+ action_documentation,
+ deprecations,
+ deprecation_messages,
+ );
+
+ let mut alternatives = action_schema
+ .to_value()
+ .get("anyOf")
+ .and_then(Value::as_array)
+ .cloned()
+ .unwrap_or_default();
+
+ let mut exclude = action_names
+ .iter()
+ .map(|name| serde_json::json!({ "const": *name }))
+ .collect::<Vec<Value>>();
+
+ // Since we accept any arbitrary string, besides the list of registered
+ // action names, we'll add any string that uses a `::` pattern to the
+ // list of exclusions, ensuring we display a warning in that case,
+ // otherwise the user might be led into thinking they've typed a valid
+ // action name when that's not the case.
+ exclude.push(serde_json::json!({ "pattern": "::" }));
+
+ alternatives.push(serde_json::json!({
+ "type": "string",
+ "not": { "anyOf": exclude }
+ }));
+
+ json_schema!({ "anyOf": alternatives })
+ }
+}
+
+impl Display for CommandAliasTarget {
+ fn fmt(&self, formatter: &mut Formatter<'_>) -> Result {
+ write!(formatter, "{}", self.0)
+ }
+}
+
+impl AsRef<str> for CommandAliasTarget {
+ fn as_ref(&self) -> &str {
+ &self.0
+ }
+}
+
+impl JsonSchema for CommandAliasTarget {
+ fn schema_name() -> Cow<'static, str> {
+ "CommandAliasTarget".into()
+ }
+
+ /// Returns `true` as a placeholder.
+ ///
+ /// The real schema, an `anyOf` of every registered action name with action
+ /// documentation and deprecation metadata, as well as any arbitrary string,
+ /// cannot be produced here because `JsonSchema::json_schema` receives no
+ /// runtime context. It is instead built by call sites that do have access
+ /// to the GPUI action registry using [`CommandAliasTarget::build_schema`].
+ fn json_schema(_generator: &mut SchemaGenerator) -> Schema {
+ json_schema!(true)
+ }
+}
+
/// The name of a registered GPUI action, serialized as a plain JSON string, for
/// example, "editor::Cancel"` or `"workspace::CloseActiveItem"`.
///
diff --git a/crates/settings_content/src/settings_content.rs b/crates/settings_content/src/settings_content.rs
index 0ae76ccf568..d8fa006554e 100644
--- a/crates/settings_content/src/settings_content.rs
+++ b/crates/settings_content/src/settings_content.rs
@@ -13,7 +13,7 @@ mod theme;
mod title_bar;
mod workspace;
-pub use action::{ActionName, ActionWithArguments};
+pub use action::{ActionName, ActionWithArguments, CommandAliasTarget};
pub use agent::*;
pub use editor::*;
pub use extension::*;
diff --git a/crates/settings_content/src/workspace.rs b/crates/settings_content/src/workspace.rs
index 7873b332832..780fc1dc542 100644
--- a/crates/settings_content/src/workspace.rs
+++ b/crates/settings_content/src/workspace.rs
@@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize};
use settings_macros::{MergeFrom, with_fallible_options};
use crate::{
- ActionName, CenteredPaddingSettings, DelayMs, DockPosition, DockSide, InactiveOpacity,
+ CenteredPaddingSettings, CommandAliasTarget, DelayMs, DockPosition, DockSide, InactiveOpacity,
ShowIndentGuides, ShowScrollbar, serialize_optional_f32_with_two_decimal_places,
};
@@ -94,7 +94,7 @@ pub struct WorkspaceSettingsContent {
///
/// Default: {}
#[serde(default)]
- pub command_aliases: HashMap<String, ActionName>,
+ pub command_aliases: HashMap<String, CommandAliasTarget>,
/// Maximum open tabs in a pane. Will not close an unsaved
/// tab. Set to `None` for unlimited tabs.
///
diff --git a/crates/vim/src/test.rs b/crates/vim/src/test.rs
index 99eda3d6c48..fed30f8dea8 100644
--- a/crates/vim/src/test.rs
+++ b/crates/vim/src/test.rs
@@ -18,7 +18,7 @@ use gpui::{KeyBinding, Modifiers, MouseButton, TestAppContext, px};
use itertools::Itertools;
use language::{CursorShape, Language, LanguageConfig, Point};
pub use neovim_backed_test_context::*;
-use settings::{ActionName, SettingsStore};
+use settings::{CommandAliasTarget, SettingsStore};
use ui::Pixels;
use util::{path, test::marked_text_ranges};
pub use vim_test_context::*;
@@ -2124,7 +2124,7 @@ async fn test_command_alias(cx: &mut gpui::TestAppContext) {
cx.update_global(|store: &mut SettingsStore, cx| {
store.update_user_settings(cx, |s| {
let mut aliases = HashMap::default();
- aliases.insert("Q".to_string(), ActionName::new("upper"));
+ aliases.insert("Q".to_string(), CommandAliasTarget::new("upper"));
s.workspace.command_aliases = aliases
});
});
diff --git a/crates/workspace/src/workspace_settings.rs b/crates/workspace/src/workspace_settings.rs
index bed95a5f9f8..b450a3260ca 100644
--- a/crates/workspace/src/workspace_settings.rs
+++ b/crates/workspace/src/workspace_settings.rs
@@ -3,8 +3,9 @@ use std::{num::NonZeroUsize, time::Duration};
use crate::DockPosition;
use collections::HashMap;
use serde::Deserialize;
+use settings::CommandAliasTarget;
pub use settings::{
- ActionName, AutosaveSetting, BottomDockLayout, EncodingDisplayOptions, InactiveOpacity,
+ AutosaveSetting, BottomDockLayout, EncodingDisplayOptions, InactiveOpacity,
PaneSplitDirectionHorizontal, PaneSplitDirectionVertical, RegisterSetting,
RestoreOnStartupBehavior, Settings,
};
@@ -26,7 +27,7 @@ pub struct WorkspaceSettings {
pub drop_target_size: f32,
pub use_system_path_prompts: bool,
pub use_system_prompts: bool,
- pub command_aliases: HashMap<String, ActionName>,
+ pub command_aliases: HashMap<String, CommandAliasTarget>,
pub max_tabs: Option<NonZeroUsize>,
pub when_closing_with_no_tabs: settings::CloseWindowWhenNoItems,
pub on_last_window_closed: settings::OnLastWindowClosed,