1use std::fmt;
9use std::net::SocketAddr;
10use std::str::FromStr;
11
12use serde::{Deserialize, Serialize};
13
14#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
16#[serde(rename_all = "snake_case")]
17pub enum Scope {
18 Device,
20 Workgroup,
22 Workspace,
24}
25
26impl fmt::Display for Scope {
27 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28 f.write_str(match self {
29 Scope::Device => "device",
30 Scope::Workgroup => "workgroup",
31 Scope::Workspace => "workspace",
32 })
33 }
34}
35
36impl FromStr for Scope {
37 type Err = String;
38
39 fn from_str(s: &str) -> Result<Self, String> {
40 match s {
41 "device" => Ok(Scope::Device),
42 "workgroup" => Ok(Scope::Workgroup),
43 "workspace" => Ok(Scope::Workspace),
44 other => Err(format!(
45 "unknown scope `{other}` (expected device, workgroup or workspace)"
46 )),
47 }
48 }
49}
50
51#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
53#[serde(rename_all = "snake_case")]
54pub enum Kind {
55 Bool,
57 Int {
59 min: i64,
61 max: i64,
63 },
64 Enum {
66 choices: Vec<String>,
68 },
69 String {
71 non_empty: bool,
73 },
74 Url,
76 Path,
78 SocketAddr,
80 List {
82 item: Box<Kind>,
84 },
85 Secret,
87}
88
89#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
91#[serde(rename_all = "snake_case")]
92pub enum Apply {
93 Live,
95 Restart,
97}
98
99#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
103#[serde(untagged)]
104pub enum Value {
105 Bool(bool),
107 Int(i64),
109 String(String),
111 List(Vec<Value>),
113}
114
115impl fmt::Display for Value {
116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117 match self {
118 Value::Bool(b) => write!(f, "{b}"),
119 Value::Int(i) => write!(f, "{i}"),
120 Value::String(s) => f.write_str(s),
121 Value::List(items) => {
122 for (i, item) in items.iter().enumerate() {
123 if i > 0 {
124 f.write_str(",")?;
125 }
126 write!(f, "{item}")?;
127 }
128 Ok(())
129 }
130 }
131 }
132}
133
134#[derive(
136 Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
137)]
138#[serde(rename_all = "snake_case")]
139pub enum Process {
140 #[default]
142 Bridge,
143 App,
145}
146
147pub const SERVER_NAMES: [&str; 5] = ["http", "update", "sync", "retrieve", "workspace"];
151
152#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
154pub struct SettingDef {
155 pub key: String,
157 pub kind: Kind,
159 pub scopes: Vec<Scope>,
161 pub overridable: bool,
163 pub apply: Apply,
165 pub default: Option<Value>,
167 pub section: String,
169 pub doc: String,
171 #[serde(default)]
173 pub process: Process,
174}
175
176impl SettingDef {
177 pub fn home(&self) -> Scope {
179 self.scopes[0]
180 }
181
182 pub fn allows(&self, scope: Scope) -> bool {
185 scope == self.home()
186 || (scope == Scope::Device && self.overridable)
187 || self.scopes.contains(&scope)
188 }
189}
190
191#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
193#[serde(rename_all = "snake_case")]
194pub enum SecretState {
195 Set,
197 Unset,
199}
200
201#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
203#[serde(rename_all = "snake_case")]
204pub enum EntryValue {
205 Value(Value),
207 Secret(SecretState),
209 Unset,
211}
212
213#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
215#[serde(rename_all = "snake_case")]
216pub enum Origin {
217 Scope(Scope),
219 Default,
221}
222
223#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
225pub struct Entry {
226 pub key: String,
228 pub value: EntryValue,
230 pub origin: Origin,
232 pub pending_restart: bool,
234 pub note: Option<String>,
236}
237
238impl Kind {
239 pub fn parse(&self, text: &str) -> Result<Value, String> {
241 let value = match self {
242 Kind::Bool => match text {
243 "true" | "on" => Value::Bool(true),
244 "false" | "off" => Value::Bool(false),
245 _ => return Err("not a boolean (expected one of true, false, on, off)".into()),
246 },
247 Kind::Int { .. } => Value::Int(
248 text.trim()
249 .parse::<i64>()
250 .map_err(|_| "not an integer".to_string())?,
251 ),
252 Kind::Enum { .. } | Kind::String { .. } | Kind::Url | Kind::Path | Kind::SocketAddr => {
253 Value::String(text.to_string())
254 }
255 Kind::List { item } => Value::List(
256 split_list(text)
257 .iter()
258 .map(|part| item.parse(part))
259 .collect::<Result<_, _>>()?,
260 ),
261 Kind::Secret => {
262 return Err(
263 "a secret cannot be given as text; read it with --stdin or a prompt".into(),
264 );
265 }
266 };
267 self.check(&value)?;
268 Ok(value)
269 }
270
271 pub fn check(&self, value: &Value) -> Result<(), String> {
273 match (self, value) {
274 (Kind::Bool, Value::Bool(_)) => Ok(()),
275 (Kind::Int { min, max }, Value::Int(i)) => {
276 if (*min..=*max).contains(i) {
277 Ok(())
278 } else {
279 Err(format!("out of range (expected {min}..={max})"))
280 }
281 }
282 (Kind::Enum { choices }, Value::String(s)) => {
283 if choices.contains(s) {
284 Ok(())
285 } else {
286 Err(format!("not one of the choices ({})", choices.join(", ")))
287 }
288 }
289 (Kind::String { non_empty }, Value::String(s)) => {
290 if *non_empty && s.is_empty() {
291 Err("must not be empty".into())
292 } else {
293 Ok(())
294 }
295 }
296 (Kind::Url, Value::String(s)) => {
297 let rest = s
298 .strip_prefix("http://")
299 .or_else(|| s.strip_prefix("https://"));
300 match rest {
301 Some(rest) if !rest.is_empty() => Ok(()),
302 _ => Err("not an http or https URL".into()),
303 }
304 }
305 (Kind::Path, Value::String(s)) => {
306 if std::path::Path::new(s).as_os_str().is_empty() {
307 Err("path must not be empty".into())
308 } else {
309 Ok(())
310 }
311 }
312 (Kind::SocketAddr, Value::String(s)) => s
313 .parse::<SocketAddr>()
314 .map(|_| ())
315 .map_err(|_| "not a host:port socket address".to_string()),
316 (Kind::List { item }, Value::List(items)) => {
317 items.iter().try_for_each(|v| item.check(v))
318 }
319 (Kind::Secret, Value::String(_)) => Ok(()),
320 (Kind::Secret, _) => Err("a secret must be a string".into()),
322 (kind, _) => Err(format!("has the wrong type (expected {})", kind.name())),
324 }
325 }
326
327 fn name(&self) -> &'static str {
329 match self {
330 Kind::Bool => "bool",
331 Kind::Int { .. } => "integer",
332 Kind::Enum { .. } => "choice",
333 Kind::String { .. } => "string",
334 Kind::Url => "URL",
335 Kind::Path => "path",
336 Kind::SocketAddr => "socket address",
337 Kind::List { .. } => "list",
338 Kind::Secret => "secret",
339 }
340 }
341}
342
343fn split_list(text: &str) -> Vec<String> {
345 let text = text.trim();
346 let text = text
347 .strip_prefix('[')
348 .and_then(|t| t.strip_suffix(']'))
349 .unwrap_or(text);
350 if text.trim().is_empty() {
351 return Vec::new();
352 }
353 text.split(',')
354 .map(|part| {
355 let part = part.trim();
356 part.strip_prefix('"')
357 .and_then(|p| p.strip_suffix('"'))
358 .unwrap_or(part)
359 .to_string()
360 })
361 .collect()
362}
363
364pub mod gui {
366 pub const THEME_PREFERENCE: &str = "gui.theme.preference";
368 pub const THEME_CONTRAST: &str = "gui.theme.contrast";
370 pub const THEME_ACCENT: &str = "gui.theme.accent";
372 pub const THEME_ACCENT_HUE: &str = "gui.theme.accent_hue";
374 pub const THEME_ACCENT_CHROMA: &str = "gui.theme.accent_chroma";
376 pub const ACCENT_CHOICES: [&str; 10] = [
379 "default", "neutral", "red", "orange", "yellow", "green", "cyan", "blue", "purple",
380 "custom",
381 ];
382 pub const LOCALE: &str = "gui.locale";
385 pub const THEME_KEYS: [&str; 5] = [
387 THEME_PREFERENCE,
388 THEME_CONTRAST,
389 THEME_ACCENT,
390 THEME_ACCENT_HUE,
391 THEME_ACCENT_CHROMA,
392 ];
393}
394
395#[cfg(test)]
396mod tests {
397 use super::*;
398
399 #[test]
400 fn a_wrong_typed_secret_is_not_echoed() {
401 let value = Value::List(vec![Value::String("hunter2-sekrit".into())]);
402 let err = Kind::Secret.check(&value).unwrap_err();
403 assert!(!err.contains("hunter2"), "{err}");
404 let err = Kind::Secret.check(&Value::Int(424242)).unwrap_err();
405 assert!(!err.contains("424242"), "{err}");
406 }
407
408 #[test]
409 fn a_rejected_value_is_not_echoed() {
410 let list = Kind::List {
411 item: Box::new(Kind::Url),
412 };
413 let parsed = [
414 (Kind::Bool, "MARKER-42"),
415 (Kind::Int { min: 1, max: 10 }, "MARKER-42"),
416 (Kind::Int { min: 1, max: 10 }, "4242424"),
417 (
418 Kind::Enum {
419 choices: vec!["a".into()],
420 },
421 "MARKER-42",
422 ),
423 (Kind::Url, "MARKER-42"),
424 (Kind::SocketAddr, "MARKER-42"),
425 (list, "MARKER-42"),
426 ];
427 for (kind, text) in parsed {
428 let err = kind.parse(text).unwrap_err();
429 assert!(!err.contains(text), "{kind:?}: {err}");
430 }
431 let checked = [
432 (Kind::Int { min: 1, max: 10 }, Value::Int(4242424)),
433 (Kind::Bool, Value::String("MARKER-42".into())),
434 (
435 Kind::Int { min: 1, max: 10 },
436 Value::String("MARKER-42".into()),
437 ),
438 (
439 Kind::Enum {
440 choices: vec!["a".into()],
441 },
442 Value::List(vec![Value::String("MARKER-42".into())]),
443 ),
444 ];
445 for (kind, value) in checked {
446 let err = kind.check(&value).unwrap_err();
447 assert!(!err.contains("MARKER-42"), "{kind:?}: {err}");
448 assert!(!err.contains("4242424"), "{kind:?}: {err}");
449 assert!(
450 !err.contains("choices"),
451 "names the kind, not its Debug: {err}"
452 );
453 }
454 }
455
456 fn def(key: &str, home: Scope) -> SettingDef {
457 SettingDef {
458 key: key.into(),
459 kind: Kind::Bool,
460 scopes: vec![home],
461 overridable: false,
462 apply: Apply::Live,
463 default: None,
464 section: "test".into(),
465 doc: "test".into(),
466 process: Process::Bridge,
467 }
468 }
469
470 #[test]
471 fn an_older_def_reads_as_the_bridges() {
472 let json = r#"{"key":"a.b","kind":"bool","scopes":["device"],"overridable":false,
473 "apply":"live","default":null,"section":"s","doc":"d"}"#;
474 let def: SettingDef = serde_json::from_str(json).unwrap();
475 assert_eq!(def.process, Process::Bridge);
476 assert_eq!(serde_json::to_value(Process::App).unwrap(), "app");
477 }
478
479 #[test]
480 fn bools_accept_on_off_true_false() {
481 for (t, v) in [
482 ("true", true),
483 ("on", true),
484 ("false", false),
485 ("off", false),
486 ] {
487 assert_eq!(Kind::Bool.parse(t).unwrap(), Value::Bool(v));
488 }
489 assert!(
490 Kind::Bool
491 .parse("yes")
492 .unwrap_err()
493 .contains("true, false, on, off")
494 );
495 }
496 #[test]
497 fn ints_name_their_range() {
498 let k = Kind::Int { min: 64, max: 2048 };
499 assert_eq!(k.parse("1024").unwrap(), Value::Int(1024));
500 assert!(k.parse("32").unwrap_err().contains("64..=2048"));
501 }
502 #[test]
503 fn enums_list_their_choices() {
504 let k = Kind::Enum {
505 choices: vec!["q8_0".into(), "f16".into()],
506 };
507 assert!(k.parse("q4").unwrap_err().contains("q8_0, f16"));
508 }
509 #[test]
510 fn urls_are_http_only() {
511 assert!(Kind::Url.parse("https://a.example").is_ok());
512 assert!(Kind::Url.parse("ftp://a.example").is_err());
513 }
514 #[test]
515 fn lists_take_commas_or_a_toml_array() {
516 let k = Kind::List {
517 item: Box::new(Kind::Url),
518 };
519 let want = Value::List(vec![
520 Value::String("https://a".into()),
521 Value::String("https://b".into()),
522 ]);
523 assert_eq!(k.parse("https://a,https://b").unwrap(), want);
524 assert_eq!(k.parse(r#"["https://a", "https://b"]"#).unwrap(), want);
525 assert_eq!(k.parse("").unwrap(), Value::List(vec![]));
526 }
527 #[test]
528 fn secrets_are_never_parsed_from_text() {
529 assert!(
530 Kind::Secret
531 .parse("sk-123")
532 .unwrap_err()
533 .contains("--stdin")
534 );
535 }
536 #[test]
537 fn device_is_allowed_only_when_overridable() {
538 let mut d = def("embed.remote.model", Scope::Workgroup);
539 assert!(!d.allows(Scope::Device));
540 d.overridable = true;
541 assert!(d.allows(Scope::Device));
542 }
543 #[test]
544 fn values_round_trip_through_json() {
545 let v = Value::List(vec![Value::Int(1), Value::Int(2)]);
546 let json = serde_json::to_string(&v).unwrap();
547 assert_eq!(json, "[1,2]");
548 assert_eq!(serde_json::from_str::<Value>(&json).unwrap(), v);
549 for v in [Value::Bool(true), Value::Int(-7), Value::String("x".into())] {
550 let back: Value = serde_json::from_str(&serde_json::to_string(&v).unwrap()).unwrap();
551 assert_eq!(back, v);
552 }
553 }
554 #[test]
555 fn scopes_display_and_parse() {
556 for s in [Scope::Device, Scope::Workgroup, Scope::Workspace] {
557 assert_eq!(s.to_string().parse::<Scope>().unwrap(), s);
558 }
559 assert_eq!(Scope::Device.to_string(), "device");
560 assert!("nope".parse::<Scope>().is_err());
561 }
562 #[test]
563 fn check_validates_typed_values() {
564 let k = Kind::Int { min: 1, max: 3 };
565 assert!(k.check(&Value::Int(2)).is_ok());
566 assert!(k.check(&Value::Int(9)).is_err());
567 assert!(k.check(&Value::Bool(true)).is_err());
568 assert!(
569 Kind::String { non_empty: true }
570 .check(&Value::String(String::new()))
571 .is_err()
572 );
573 assert!(Kind::SocketAddr.parse("127.0.0.1:80").is_ok());
574 assert!(Kind::SocketAddr.parse("nope").is_err());
575 assert!(Kind::Secret.check(&Value::String("x".into())).is_ok());
576 }
577 #[test]
578 fn the_crate_stays_free_of_framework_crates() {
579 let manifest = include_str!("../Cargo.toml");
580 let deps = manifest.split("[dependencies]").nth(1).unwrap();
581 assert!(!deps.contains("sapphire-framework-"));
582 }
583}