Lutra/crates/engine/tests/settings.rs
danny d097558ba5 M4.10: remotes: fetch, pull, push, clone and manage remotes
Owner decision D23: Lutra runs fetch, pull (merge or rebase per the new
git.pull.mode setting), push (upstream set on the first push) and clone
through the user's git. Any HTTPS or SSH server works; sign-in stays with
git's credential helper (its own window is allowed for network calls only)
and the ssh agent. Terminal prompts stay off, ext:: is refused, and URL
userinfo is redacted in every message, progress line and remote listing.

- vcs: Call::network with a 30 min timeout, a stderr progress sink and a
  Cancel flag that kills git's process group; remote.rs with clone_repo,
  fetch, pull, push (--porcelain rejections), remotes and add/set-url/
  remove; explained refusals (rejected push, sign-in, host key, not found,
  unreachable, no upstream, local changes, conflicts).
- engine: git.fetch/pull/push/clone/cancel/remotes/remoteAdd/remoteSetUrl/
  remoteRemove, one network call at a time, gitProgress events,
  gitChanged after changes.
- ui: status-bar progress with Cancel and ahead/behind, vcs.fetch/pull/
  push/clone/manageRemotes (Git menu, no default shortcuts), Clone
  Repository and Manage Remotes dialogs; desktop pick_dir IPC.
- Tests against local bare repositories only (vcs 8, engine 3, Vitest 11)
  plus unit and property tests; docs updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 17:50:26 +01:00

321 lines
10 KiB
Rust

//! Settings commands, persistence across engines, corrupt files, and a
//! property test over random `settings.json` content.
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::indexing_slicing
)]
use std::fs;
use lutra_engine::settings::{DEFS, FILE_NAME};
use lutra_engine::{Engine, EngineConfig, Event, NotificationLevel};
use proptest::prelude::*;
use serde_json::{Value, json};
use tempfile::TempDir;
fn config(dir: &TempDir) -> EngineConfig {
EngineConfig {
config_dir: dir.path().join("config"),
data_dir: dir.path().join("data"),
}
}
fn engine(dir: &TempDir) -> Engine {
Engine::with_config(config(dir)).unwrap()
}
fn get_all(engine: &mut Engine) -> Value {
engine.execute("settings.get", Value::Null).unwrap().value["values"].clone()
}
#[test]
fn list_describes_the_c2_keys_with_catalog_keys_only() {
let mut e = Engine::new().unwrap();
let list = e.execute("settings.list", Value::Null).unwrap().value;
let keys: Vec<_> = list
.as_array()
.unwrap()
.iter()
.map(|s| s["key"].as_str().unwrap())
.collect();
assert_eq!(
keys,
[
"appearance.theme",
"editor.fontSize",
"ui.language",
"php.executable",
"phpactor.path",
"phpactor.autoDownload",
"editor.autosave.onBlur",
"editor.autosave.onTabSwitch",
"editor.autosave.idleSeconds",
"editor.completion.autoPopup",
"editor.completion.delayMs",
"editor.hover.delayMs",
"git.executable",
"git.pull.mode"
]
);
for s in list.as_array().unwrap() {
assert!(s.get("label").is_none());
assert!(s["labelKey"].as_str().unwrap().starts_with("settings."));
assert!(
s["descriptionKey"]
.as_str()
.unwrap()
.ends_with(".description")
);
}
assert_eq!(list[1]["type"], "int");
assert_eq!(list[1]["default"], 14);
assert_eq!(list[2]["enumValues"], json!(["en"]));
assert_eq!(list[3]["type"], "string");
assert_eq!(list[3]["default"], "");
assert_eq!(list[5]["type"], "bool");
assert_eq!(list[5]["default"], true);
assert_eq!(list[5]["section"], "php");
}
#[test]
fn string_and_bool_settings_are_validated() {
let mut e = Engine::new().unwrap();
for (key, bad) in [
("php.executable", json!(3)),
("php.executable", json!("x".repeat(4097))),
("php.executable", json!(format!("a{}b", char::from(0)))),
("phpactor.autoDownload", json!("yes")),
] {
let err = e
.execute("settings.set", json!({"key": key, "value": bad}))
.unwrap_err();
assert_eq!(err.code(), "invalid_params", "{key}");
}
e.execute(
"settings.set",
json!({"key": "phpactor.autoDownload", "value": false}),
)
.unwrap();
e.execute(
"settings.set",
json!({"key": "php.executable", "value": "C:/PHP/php.exe"}),
)
.unwrap();
let values = get_all(&mut e);
assert_eq!(values["phpactor.autoDownload"], false);
assert_eq!(values["php.executable"], "C:/PHP/php.exe");
}
#[test]
fn get_set_reset_and_events() {
let mut e = Engine::new().unwrap();
assert_eq!(
get_all(&mut e),
json!({
"appearance.theme": "system",
"editor.fontSize": 14,
"ui.language": "en",
"php.executable": "",
"phpactor.path": "",
"phpactor.autoDownload": true,
"editor.autosave.onBlur": true,
"editor.autosave.onTabSwitch": true,
"editor.autosave.idleSeconds": 15,
"editor.completion.autoPopup": true,
"editor.completion.delayMs": 0,
"editor.hover.delayMs": 350,
"git.executable": "",
"git.pull.mode": "merge"
})
);
let out = e
.execute(
"settings.set",
json!({"key": "appearance.theme", "value": "lutra-light"}),
)
.unwrap();
assert_eq!(out.value, json!({"value": "lutra-light"}));
assert_eq!(
out.events.first(),
Some(&Event::SettingsChanged {
keys: vec!["appearance.theme".into()]
})
);
let same = e
.execute(
"settings.set",
json!({"key": "appearance.theme", "value": "lutra-light"}),
)
.unwrap();
assert!(same.events.is_empty());
let got = e
.execute("settings.get", json!({"keys": ["appearance.theme"]}))
.unwrap()
.value;
assert_eq!(got, json!({"values": {"appearance.theme": "lutra-light"}}));
let reset = e
.execute("settings.reset", json!({"key": "appearance.theme"}))
.unwrap();
assert_eq!(reset.value, json!({"value": "system"}));
assert_eq!(reset.events.len(), 2);
let again = e
.execute("settings.reset", json!({"key": "appearance.theme"}))
.unwrap();
assert!(again.events.is_empty());
}
#[test]
fn bad_params_are_invalid_params() {
let mut e = Engine::new().unwrap();
for (command, params) in [
(
"settings.set",
json!({"key": "editor.fontSize", "value": 100}),
),
(
"settings.set",
json!({"key": "editor.fontSize", "value": "16"}),
),
("settings.set", json!({"key": "ui.language", "value": "de"})),
("settings.set", json!({"key": "nope", "value": 1})),
("settings.set", json!({"key": "editor.fontSize"})),
("settings.reset", json!({"key": "nope"})),
("settings.get", json!({"keys": ["nope"]})),
("settings.get", json!({"keys": "editor.fontSize"})),
] {
let err = e.execute(command, params.clone()).unwrap_err();
assert_eq!(err.code(), "invalid_params", "{command} {params}");
}
assert!(e.take_events().is_empty());
assert_eq!(get_all(&mut e)["editor.fontSize"], 14);
}
#[test]
fn values_survive_a_restart() {
let dir = tempfile::tempdir().unwrap();
{
let mut e = engine(&dir);
assert!(e.take_events().is_empty(), "a missing file is no problem");
e.execute(
"settings.set",
json!({"key": "editor.fontSize", "value": 16}),
)
.unwrap();
}
let file = dir.path().join("config").join(FILE_NAME);
let saved: Value = serde_json::from_str(&fs::read_to_string(&file).unwrap()).unwrap();
assert_eq!(saved, json!({"editor.fontSize": 16}));
let mut e = engine(&dir);
assert_eq!(get_all(&mut e)["editor.fontSize"], 16);
assert_eq!(e.state().config, Some(config(&dir)));
}
#[test]
fn a_corrupt_file_is_backed_up_and_reported() {
let dir = tempfile::tempdir().unwrap();
let config_dir = dir.path().join("config");
fs::create_dir_all(&config_dir).unwrap();
fs::write(config_dir.join(FILE_NAME), "{\"editor.fontSize\": 16,").unwrap();
let mut e = engine(&dir);
let events = e.take_events();
let [
Event::Notification {
level,
message_key,
message,
params,
..
},
] = events.as_slice()
else {
panic!("expected one notification, got {events:?}");
};
assert_eq!(*level, NotificationLevel::Warning);
assert_eq!(
message_key.as_deref(),
Some("notification.settings.corrupt")
);
assert!(message.as_deref().unwrap().contains("defaults"));
let backup = params.as_ref().unwrap()["backup"].as_str().unwrap();
assert!(backup.starts_with("settings.json.bad-"), "{backup}");
assert_eq!(
fs::read_to_string(config_dir.join(backup)).unwrap(),
"{\"editor.fontSize\": 16,"
);
assert_eq!(get_all(&mut e)["editor.fontSize"], 14);
}
#[test]
fn engine_new_has_no_persistence() {
let e = Engine::new().unwrap();
assert_eq!(e.state().config, None);
assert_eq!(e.state().settings.file(), None);
}
/// Arbitrary JSON values, nested a few levels.
fn json_value() -> impl Strategy<Value = Value> {
let leaf = prop_oneof![
Just(Value::Null),
any::<bool>().prop_map(Value::from),
any::<i64>().prop_map(Value::from),
any::<f64>()
.prop_map(|f| serde_json::Number::from_f64(f).map_or(Value::Null, Value::Number)),
"[a-z.\\-]{0,12}".prop_map(Value::from),
prop::sample::select(vec!["lutra-dark", "lutra-light", "system", "en", "de"])
.prop_map(Value::from),
(0i64..64).prop_map(Value::from),
];
leaf.prop_recursive(3, 24, 4, |inner| {
prop_oneof![
prop::collection::vec(inner.clone(), 0..4).prop_map(Value::from),
prop::collection::btree_map(key(), inner, 0..4)
.prop_map(|m| Value::Object(m.into_iter().collect())),
]
})
}
/// Keys that are often known settings.
fn key() -> impl Strategy<Value = String> {
prop_oneof![
prop::sample::select(DEFS.iter().map(|d| d.key.to_string()).collect::<Vec<_>>()),
"[a-zA-Z.]{0,10}",
]
}
/// File content: random bytes, random JSON, or an object of known keys.
fn content() -> impl Strategy<Value = Vec<u8>> {
prop_oneof![
prop::collection::vec(any::<u8>(), 0..64),
json_value().prop_map(|v| v.to_string().into_bytes()),
prop::collection::btree_map(key(), json_value(), 0..6).prop_map(|m| {
Value::Object(m.into_iter().collect())
.to_string()
.into_bytes()
}),
]
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(128))]
#[test]
fn random_files_never_panic_and_give_valid_values(bytes in content()) {
let dir = tempfile::tempdir().unwrap();
let config_dir = dir.path().join("config");
fs::create_dir_all(&config_dir).unwrap();
fs::write(config_dir.join(FILE_NAME), &bytes).unwrap();
let mut e = engine(&dir);
let values = get_all(&mut e);
for def in DEFS {
prop_assert!(def.accepts(&values[def.key]), "{} = {}", def.key, values[def.key]);
}
let set = e.execute("settings.set", json!({"key": "editor.fontSize", "value": 20}));
prop_assert!(set.is_ok());
let mut again = engine(&dir);
prop_assert_eq!(&get_all(&mut again)["editor.fontSize"], &json!(20));
}
}