croft-software 0.2.232

VSCode-style TUI written in Rust
//! One row per setting (#2062, "One settings table"): what serde cannot say
//! about a key of [`crate::prefs::Prefs`]. `Prefs` keeps each setting's
//! name, type and default; this table says who may set it, when a change
//! applies, and how Settings (UI) edits it. The lists that used to be kept
//! by hand beside `Prefs` (the keys a workspace may set, the optional
//! settings' kinds, the choice lists, the settings read only at start) are
//! read from here, and a test fails when the table and `Prefs` disagree, so
//! a new setting cannot be added without saying all three.

/// Who may set a setting.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Scope {
    /// The user layers alone: extension enablement, MCP consent and
    /// fingerprints, host accents, machine-state flags, anything that runs a
    /// command or reaches a host. A cloned repo must not be able to change
    /// what croft trusts or executes.
    User,
    /// Also a repo-controlled layer (the workspace's, and the one synced from
    /// another machine): appearance and editor/terminal behaviour toggles.
    /// Making a setting `Workspace` is a deliberate review decision.
    Workspace,
}

/// When a change to a setting takes effect.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Applies {
    /// When the settings file is saved (#2907).
    Live,
    /// When the next terminal pane opens (#2905).
    NewPane,
    /// The next time croft starts: what it sets is loaded once. Saving one
    /// says so (#2907).
    NextStart,
}

/// The values a setting takes, past what its JSON type says: how Settings
/// (UI) edits it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Values {
    /// Any value of its JSON type: a switch, a number, text, or the JSON file
    /// for an object or a list.
    Any,
    /// One of these values. An empty value counts as the first.
    OneOf(&'static [&'static str]),
    /// Optional (unset by default, #1555): unset, or one of these values,
    /// the first of which is `""`, the unset one.
    OptionalOneOf(&'static [&'static str]),
    /// Optional text: an empty entry unsets it.
    OptionalText,
    /// Optional whole number: an empty entry unsets it.
    OptionalNumber,
    /// Optional: unset (the system's language), or one of the languages
    /// croft has a catalog for, worked out when asked.
    Language,
    /// One of the themes croft ships, worked out when asked.
    Theme,
}

impl Values {
    /// Whether the setting is unset by default (#1555): its value is then
    /// `null`, which says nothing of its type, and an empty entry unsets it.
    pub fn optional(self) -> bool {
        matches!(
            self,
            Self::OptionalOneOf(_) | Self::OptionalText | Self::OptionalNumber | Self::Language
        )
    }
}

/// One setting: its key in `config.json` and what serde cannot say about it.
#[derive(Clone, Copy, Debug)]
pub struct Setting {
    pub key: &'static str,
    pub scope: Scope,
    pub applies: Applies,
    pub values: Values,
}

const fn user(key: &'static str) -> Setting {
    Setting {
        key,
        scope: Scope::User,
        applies: Applies::Live,
        values: Values::Any,
    }
}

const fn workspace(key: &'static str) -> Setting {
    Setting {
        scope: Scope::Workspace,
        ..user(key)
    }
}

impl Setting {
    const fn values(self, values: Values) -> Self {
        Self { values, ..self }
    }

    const fn applies(self, applies: Applies) -> Self {
        Self { applies, ..self }
    }
}

/// Every top-level setting, in `Prefs`'s order.
pub static SETTINGS: &[Setting] = &[
    workspace("theme").values(Values::Theme),
    user("osk_split"),
    user("suppress_terminal_warning"),
    workspace("explorer_views"),
    user("sidebar_auto_hide"),
    user("problems_scope").values(Values::OneOf(&["whole_project", "open_files"])),
    user("problems_project_scope").values(Values::OneOf(&["auto", "on", "off"])),
    user("build_column_unit").values(Values::OneOf(&["display", "byte", "char"])),
    user("diff_ignore_whitespace").values(Values::OneOf(&["off", "leading", "all"])),
    user("disabled_extensions").applies(Applies::NextStart),
    user("tour_done").applies(Applies::NextStart),
    user("mcp_consented"),
    user("mcp_tool_fingerprints"),
    user("layout").applies(Applies::NextStart),
    workspace("format_on_save"),
    workspace("default_formatter").values(Values::OptionalText),
    workspace("language_formatters"),
    workspace("insert_final_newline"),
    workspace("trim_trailing_whitespace"),
    workspace("trim_final_newlines"),
    workspace("format_on_type"),
    workspace("auto_save"),
    workspace("auto_save_on_focus_change"),
    workspace("disable_inline_blame"),
    workspace("disable_auto_close_pairs"),
    workspace("disable_paste_reindent"),
    workspace("disable_quick_suggestions"),
    workspace("disable_inline_values"),
    workspace("disable_save_before_debug"),
    user("vim_mode"),
    user("multi_cursor_persist"),
    workspace("render_whitespace").values(Values::OneOf(&["selection", "all", "none"])),
    workspace("rulers"),
    workspace("word_based_suggestions").values(Values::OneOf(&[
        "matchingDocuments",
        "currentDocument",
        "allDocuments",
        "off",
    ])),
    workspace("disable_bracket_colors"),
    workspace("disable_indent_guides"),
    user("home_walks_wrapped_rows"),
    workspace("line_numbers").values(Values::OneOf(&["on", "relative", "interval", "off"])),
    workspace("disable_inlay_hints"),
    user("disable_proactive_navigator"),
    workspace("copy_on_select"),
    workspace("files_exclude"),
    workspace("search_exclude"),
    workspace("disable_compact_folders"),
    workspace("files_associations"),
    // Per-language overrides (#1440), which hold only the editor settings in
    // `crate::prefs::LANGUAGE_KEYS`; any other key in a block is dropped.
    workspace("languages"),
    workspace("files_encoding"),
    workspace("disable_log_highlight"),
    user("disable_secret_redaction"),
    user("host_accents"),
    user("disable_remote_offer"),
    user("remote_offer_excluded_hosts"),
    user("config_sync_excluded_hosts"),
    user("config_sync_excluded_files"),
    user("fleet_groups"),
    // An enum: free text such as `enabled` was saved and then ignored.
    user("code_scanning").values(Values::OneOf(&["off", "on", "prompt"])),
    user("lane_agent").values(Values::OptionalText),
    // Unset, the depth the terminal says it draws (#2908).
    user("color_depth").values(Values::OptionalOneOf(&["", "truecolor", "256", "16"])),
    user("terminal_scrollback").applies(Applies::NewPane),
    user("terminal_rewind_mb")
        .applies(Applies::NewPane)
        .values(Values::OptionalNumber),
    user("terminal_persistent_panes").applies(Applies::NewPane),
    user("terminal_multiline_paste_warning"),
    user("review_ai_prefix").values(Values::OptionalText),
    user("screen_reader"),
    user("screen_reader_command").values(Values::OptionalText),
    user("codeql_cli_path").values(Values::OptionalText),
    user("locale")
        .applies(Applies::NextStart)
        .values(Values::Language),
    user("notifications"),
];

/// The row for `key`, if it is a setting.
pub fn setting(key: &str) -> Option<&'static Setting> {
    SETTINGS.iter().find(|s| s.key == key)
}

/// Whether a workspace layer, or the layer synced from another machine, may
/// set `key`.
pub fn workspace_may_set(key: &str) -> bool {
    setting(key).is_some_and(|s| s.scope == Scope::Workspace)
}

/// Whether `key` is read only when croft starts, so saving it waits for the
/// next start.
pub fn applies_at_next_start(key: &str) -> bool {
    setting(key).is_some_and(|s| s.applies == Applies::NextStart)
}

/// The values `key` takes; `Any` for a key with no row.
pub fn values(key: &str) -> Values {
    setting(key).map_or(Values::Any, |s| s.values)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::BTreeSet;

    /// The keys of `Prefs`: its serialized default, and `languages`, which
    /// is skipped there while it is empty.
    fn prefs_keys() -> BTreeSet<String> {
        let serde_json::Value::Object(map) =
            serde_json::to_value(crate::prefs::Prefs::default()).unwrap()
        else {
            panic!("Prefs serializes to an object");
        };
        let mut keys: BTreeSet<String> = map.into_iter().map(|(k, _)| k).collect();
        keys.insert(String::from("languages"));
        keys
    }

    /// Every setting has exactly one row, and every row is a setting: a key
    /// added to `Prefs` fails here until it says who may set it, when it
    /// applies and how it is edited.
    #[test]
    fn every_setting_has_one_row_and_every_row_is_a_setting() {
        let rows: Vec<&str> = SETTINGS.iter().map(|s| s.key).collect();
        let unique: BTreeSet<&str> = rows.iter().copied().collect();
        assert_eq!(unique.len(), rows.len(), "a key with two rows");
        let rows: BTreeSet<String> = unique.into_iter().map(String::from).collect();
        let keys = prefs_keys();
        let missing: Vec<_> = keys.difference(&rows).collect();
        let extra: Vec<_> = rows.difference(&keys).collect();
        assert!(missing.is_empty(), "settings with no row: {missing:?}");
        assert!(extra.is_empty(), "rows for no setting: {extra:?}");
    }

    /// An optional setting is `null` by default and a declared optional
    /// kind; any other setting has a value.
    #[test]
    fn optional_kinds_match_the_settings_that_are_unset_by_default() {
        let serde_json::Value::Object(map) =
            serde_json::to_value(crate::prefs::Prefs::default()).unwrap()
        else {
            panic!("Prefs serializes to an object");
        };
        for s in SETTINGS {
            let optional = s.values.optional();
            let unset = map.get(s.key).is_some_and(serde_json::Value::is_null);
            assert_eq!(optional, unset, "{}", s.key);
        }
    }

    /// An optional choice lists the unset value first, so stepping past the
    /// last value goes back to unset.
    #[test]
    fn optional_choices_start_with_unset() {
        for s in SETTINGS {
            if let Values::OptionalOneOf(values) = s.values {
                assert_eq!(values.first(), Some(&""), "{}", s.key);
            }
        }
    }

    /// docs/SETTINGS.md, which names the settings by these rows' groups
    /// (#2062 settings card step 3), as the key ledger keeps the shortcut
    /// docs honest.
    fn settings_doc() -> String {
        std::fs::read_to_string(
            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("docs/SETTINGS.md"),
        )
        .unwrap()
    }

    /// The text of `doc` from `from` to the first `to` after it.
    fn between<'a>(doc: &'a str, from: &str, to: &str) -> &'a str {
        let start = doc
            .find(from)
            .unwrap_or_else(|| panic!("docs/SETTINGS.md has no {from:?}"));
        let rest = &doc[start..];
        &rest[..rest
            .find(to)
            .unwrap_or_else(|| panic!("docs/SETTINGS.md has no {to:?} after {from:?}"))]
    }

    /// The setting-like words in backticks: lower case, digits and `_`.
    fn backticked_keys(text: &str) -> BTreeSet<String> {
        text.split('`')
            .skip(1)
            .step_by(2)
            .filter(|w| {
                !w.is_empty()
                    && w.chars()
                        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
            })
            .map(String::from)
            .collect()
    }

    /// The keys of the rows that `keep`.
    fn rows(keep: impl Fn(&Setting) -> bool) -> BTreeSet<String> {
        SETTINGS
            .iter()
            .filter(|s| keep(s))
            .map(|s| s.key.to_string())
            .collect()
    }

    /// The docs' workspace allowlist is exactly the `Workspace` rows, and
    /// every setting they name as refused is a user-only row.
    #[test]
    fn the_docs_list_exactly_the_settings_a_workspace_may_set() {
        let doc = settings_doc();
        let section = between(&doc, "## What workspace layers may set", "\n## ");
        let (allowed, refused) = section
            .split_once("Everything else")
            .expect("the section names what a workspace may not set");
        assert_eq!(
            backticked_keys(allowed),
            rows(|s| s.scope == Scope::Workspace),
            "docs/SETTINGS.md's allowlist and the table's Workspace rows differ"
        );
        let refused = backticked_keys(between(refused, "", "is ignored from workspace layers"));
        assert!(refused.len() > 10, "fixture: {refused:?}");
        let not_user: Vec<&String> = refused
            .iter()
            .filter(|k| setting(k).is_none_or(|s| s.scope != Scope::User))
            .collect();
        assert!(
            not_user.is_empty(),
            "docs/SETTINGS.md refuses these from a workspace, and no user-only row says so: {not_user:?}"
        );
    }

    /// The docs name exactly the settings that apply at the next start, and
    /// those that apply to the next terminal pane.
    #[test]
    fn the_docs_name_when_each_delayed_setting_applies() {
        let doc = settings_doc();
        assert_eq!(
            backticked_keys(between(
                &doc,
                "read once, when croft starts",
                "Settings (UI) says so"
            )),
            rows(|s| s.applies == Applies::NextStart),
        );
        assert_eq!(
            backticked_keys(between(
                &doc,
                "re-merge on the spot.",
                "apply to the next terminal pane"
            )),
            rows(|s| s.applies == Applies::NewPane),
        );
    }
}