mprocs 0.9.3

TUI for running multiple processes
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
//! Config parsing utilities for manual YAML -> Rust config loading.
//!
//! Provides:
//! - [`CfgDoc`] — YAML document with write-back support and `$js`/`$select` pre-resolution
//! - [`CfgNode`] / [`CfgObj`] / [`CfgArr`] — typed accessors with path tracking for errors
//! - [`FromCfg`] / [`IntoCfg`] — conversion traits between Rust types and YAML values
//! - [`CfgCx`] — parsing context (config dir, optional JS evaluator)
//!
//! # Usage
//! ```ignore
//! let cx = CfgCx::new(config_dir);
//! let doc = CfgDoc::load(path, &cx)?;
//! let root = doc.root().as_obj()?;
//!
//! let name: String = root.required("name", &cx)?;
//! let port: usize = root.default("port", 8080, &cx)?;
//! let tags: Option<Vec<String>> = root.optional("tags", &cx)?;
//!
//! // Write-back: modify and save
//! doc.set_at(&CfgPath::root().join("port"), 9090.into_cfg());
//! doc.save()?;
//! ```

use std::ffi::OsString;
use std::fmt::{self, Display};
use std::path::{Path, PathBuf};

use anyhow::{Result, bail};
use indexmap::IndexMap;
use serde_yaml::Value;

#[derive(Clone, Debug, Default)]
pub struct CfgPath(Vec<String>);

impl CfgPath {
  pub fn root() -> Self {
    Self(Vec::new())
  }

  /// Append a segment, returning a new child path.
  pub fn join(&self, segment: impl ToString) -> Self {
    let mut segs = self.0.clone();
    segs.push(segment.to_string());
    Self(segs)
  }

  /// Path segments for navigating the YAML tree during write-back.
  pub fn segments(&self) -> &[String] {
    &self.0
  }
}

impl Display for CfgPath {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    write!(f, "<config>")?;
    for seg in &self.0 {
      write!(f, ".{}", seg)?;
    }
    Ok(())
  }
}

/// Context provided during config loading.
pub struct CfgCx {
  /// Parent directory of the config file, for resolving `<CONFIG_DIR>`.
  pub config_dir: PathBuf,
  /// Optional JS evaluator for `{"$js": "..."}` directives.
  /// Receives the source string, must return the evaluated YAML value.
  pub js_eval: Option<Box<dyn Fn(&str) -> Result<Value>>>,
}

impl CfgCx {
  pub fn new(config_dir: PathBuf) -> Self {
    Self {
      config_dir,
      js_eval: None,
    }
  }

  /// Resolve a `<CONFIG_DIR>` prefix in a path string.
  pub fn resolve_path(&self, path: &str) -> PathBuf {
    if let Some(rest) = path.strip_prefix("<CONFIG_DIR>") {
      let mut buf = self.config_dir.clone();
      buf.push(rest.trim_start_matches(['/', '\\']));
      buf
    } else {
      PathBuf::from(path)
    }
  }
}

/// Pre-process a YAML value tree, evaluating `$js` and `$select` directives.
///
/// - `{"$js": "cx => expr"}` — calls `cx.js_eval` and substitutes the result.
/// - `{"$select": "os", "linux": ..., "$else": ...}` — picks a branch by OS.
pub fn resolve_directives(value: &Value, cx: &CfgCx) -> Result<Value> {
  match value {
    Value::Mapping(map) => {
      if let Some(js_src) = map.get(&Value::from("$js")) {
        let src = js_src
          .as_str()
          .ok_or_else(|| anyhow::anyhow!("$js value must be a string"))?;
        if let Some(eval) = &cx.js_eval {
          let result = eval(src)?;
          return resolve_directives(&result, cx);
        } else {
          bail!("$js directive found but no JS evaluator is configured");
        }
      }

      // $select directive (first key must be "$select")
      if map
        .iter()
        .next()
        .is_some_and(|(k, _)| k.as_str() == Some("$select"))
      {
        let selected = resolve_select(map)?;
        return resolve_directives(selected, cx);
      }

      // Recurse into mapping values
      let mut result = serde_yaml::Mapping::new();
      for (k, v) in map {
        result.insert(k.clone(), resolve_directives(v, cx)?);
      }
      Ok(Value::Mapping(result))
    }
    Value::Sequence(seq) => {
      let items = seq
        .iter()
        .map(|v| resolve_directives(v, cx))
        .collect::<Result<Vec<_>>>()?;
      Ok(Value::Sequence(items))
    }
    other => Ok(other.clone()),
  }
}

fn resolve_select<'a>(map: &'a serde_yaml::Mapping) -> Result<&'a Value> {
  let selector = map
    .get(&Value::from("$select"))
    .and_then(|v| v.as_str())
    .ok_or_else(|| anyhow::anyhow!("$select value must be a string"))?;

  match selector {
    "os" => {
      let os = std::env::consts::OS;
      if let Some(v) = map.get(&Value::from(os)) {
        return Ok(v);
      }
      if let Some(v) = map.get(&Value::from("$else")) {
        return Ok(v);
      }
      bail!(
        "No match for OS '{}' in $select. Use \"$else\" for a default.",
        os
      )
    }
    other => bail!("Unknown $select kind: '{}'", other),
  }
}

/// A config document that supports both parsing and write-back.
///
/// Maintains two YAML trees:
/// - **source** — the original document (with `$js`/`$select` intact), used when saving.
/// - **resolved** — directives evaluated, used for parsing into Rust types.
pub struct CfgDoc {
  source: Value,
  resolved: Value,
  pub file_path: PathBuf,
}

impl CfgDoc {
  /// Create from a pre-parsed YAML value.
  pub fn from_value(
    source: Value,
    file_path: PathBuf,
    cx: &CfgCx,
  ) -> Result<Self> {
    let resolved = resolve_directives(&source, cx)?;
    Ok(Self {
      source,
      resolved,
      file_path,
    })
  }

  /// Load and resolve a YAML config file.
  pub fn load(path: &Path, cx: &CfgCx) -> Result<Self> {
    let content = std::fs::read_to_string(path)?;
    let source: Value = serde_yaml::from_str(&content)?;
    Self::from_value(source, path.to_path_buf(), cx)
  }

  /// Root node of the resolved tree, ready for parsing.
  pub fn root(&self) -> CfgNode<'_> {
    CfgNode::new(&self.resolved, CfgPath::root())
  }

  /// Write the source document back to its file.
  pub fn save(&self) -> Result<()> {
    let yaml = serde_yaml::to_string(&self.source)?;
    std::fs::write(&self.file_path, yaml)?;
    Ok(())
  }

  /// Update a value at a path in both source and resolved trees.
  /// Use this from TUI to persist a config change.
  pub fn set_at(&mut self, path: &CfgPath, value: Value) {
    set_at_path(&mut self.source, path.segments(), value.clone());
    set_at_path(&mut self.resolved, path.segments(), value);
  }

  /// Access the original source tree.
  pub fn source(&self) -> &Value {
    &self.source
  }
}

fn set_at_path(root: &mut Value, segments: &[String], value: Value) {
  if segments.is_empty() {
    *root = value;
    return;
  }
  let (key, rest) = segments.split_first().unwrap();
  match root {
    Value::Mapping(map) => {
      let yaml_key = Value::from(key.as_str());
      if rest.is_empty() {
        map.insert(yaml_key, value);
      } else {
        if map.get(&yaml_key).is_none() {
          map.insert(
            yaml_key.clone(),
            Value::Mapping(serde_yaml::Mapping::new()),
          );
        }
        if let Some(child) = map.get_mut(&yaml_key) {
          set_at_path(child, rest, value);
        }
      }
    }
    Value::Sequence(seq) => {
      if let Ok(idx) = key.parse::<usize>() {
        if let Some(elem) = seq.get_mut(idx) {
          if rest.is_empty() {
            *elem = value;
          } else {
            set_at_path(elem, rest, value);
          }
        }
      }
    }
    _ => {}
  }
}

/// Reference to a resolved config value with path tracking for error messages.
#[derive(Clone)]
pub struct CfgNode<'a> {
  value: &'a Value,
  path: CfgPath,
}

impl<'a> CfgNode<'a> {
  pub fn new(value: &'a Value, path: CfgPath) -> Self {
    Self { value, path }
  }

  pub fn path(&self) -> &CfgPath {
    &self.path
  }

  pub fn raw(&self) -> &'a Value {
    self.value
  }

  /// Create an error anchored at this node's position.
  pub fn error(&self, msg: impl Display) -> anyhow::Error {
    anyhow::anyhow!("{} at {}", msg, self.path)
  }

  // Type checks

  pub fn is_null(&self) -> bool {
    self.value.is_null()
  }
  pub fn is_string(&self) -> bool {
    self.value.is_string()
  }
  pub fn is_mapping(&self) -> bool {
    self.value.is_mapping()
  }
  pub fn is_sequence(&self) -> bool {
    self.value.is_sequence()
  }

  // Primitive access

  pub fn as_str(&self) -> Result<&'a str> {
    self
      .value
      .as_str()
      .ok_or_else(|| self.error("expected string"))
  }

  pub fn as_bool(&self) -> Result<bool> {
    self
      .value
      .as_bool()
      .ok_or_else(|| self.error("expected bool"))
  }

  pub fn as_u64(&self) -> Result<u64> {
    self
      .value
      .as_u64()
      .ok_or_else(|| self.error("expected unsigned integer"))
  }

  pub fn as_i64(&self) -> Result<i64> {
    self
      .value
      .as_i64()
      .ok_or_else(|| self.error("expected integer"))
  }

  pub fn as_f64(&self) -> Result<f64> {
    self
      .value
      .as_f64()
      .ok_or_else(|| self.error("expected number"))
  }

  pub fn as_usize(&self) -> Result<usize> {
    self.as_u64().map(|v| v as usize)
  }

  // Composite access

  pub fn as_obj(&self) -> Result<CfgObj<'a>> {
    let map = self
      .value
      .as_mapping()
      .ok_or_else(|| self.error("expected object"))?;
    Ok(CfgObj {
      map,
      path: self.path.clone(),
    })
  }

  pub fn as_arr(&self) -> Result<CfgArr<'a>> {
    let seq = self
      .value
      .as_sequence()
      .ok_or_else(|| self.error("expected array"))?;
    Ok(CfgArr {
      seq: seq.as_slice(),
      path: self.path.clone(),
    })
  }

  /// Parse this node into a Rust type via [`FromCfg`].
  pub fn parse<T: FromCfg>(&self, cx: &CfgCx) -> Result<T> {
    T::from_cfg(self, cx)
  }
}

pub struct CfgObj<'a> {
  map: &'a serde_yaml::Mapping,
  path: CfgPath,
}

impl<'a> CfgObj<'a> {
  /// Look up a key, returning a [`CfgNode`] if present.
  pub fn get(&self, key: &str) -> Option<CfgNode<'a>> {
    self.map.get(&Value::from(key)).map(|v| CfgNode {
      value: v,
      path: self.path.join(key),
    })
  }

  /// Parse a required field. Errors if the key is missing.
  pub fn required<T: FromCfg>(&self, key: &str, cx: &CfgCx) -> Result<T> {
    match self.get(key) {
      Some(node) => T::from_cfg(&node, cx),
      None => bail!("missing required field '{}' at {}", key, self.path),
    }
  }

  /// Parse an optional field. Returns `None` if missing or null.
  pub fn optional<T: FromCfg>(
    &self,
    key: &str,
    cx: &CfgCx,
  ) -> Result<Option<T>> {
    match self.get(key) {
      Some(node) if !node.is_null() => Ok(Some(T::from_cfg(&node, cx)?)),
      _ => Ok(None),
    }
  }

  /// Parse a field with a fallback. Returns `default` if missing or null.
  pub fn default<T: FromCfg>(
    &self,
    key: &str,
    default: T,
    cx: &CfgCx,
  ) -> Result<T> {
    match self.get(key) {
      Some(node) if !node.is_null() => T::from_cfg(&node, cx),
      _ => Ok(default),
    }
  }

  /// Iterate over string-keyed entries. Non-string keys are silently skipped.
  pub fn iter(&self) -> impl Iterator<Item = (&'a str, CfgNode<'a>)> + '_ {
    self.map.iter().filter_map(move |(k, v)| {
      let key = k.as_str()?;
      Some((
        key,
        CfgNode {
          value: v,
          path: self.path.join(key),
        },
      ))
    })
  }

  pub fn path(&self) -> &CfgPath {
    &self.path
  }

  pub fn error(&self, msg: impl Display) -> anyhow::Error {
    anyhow::anyhow!("{} at {}", msg, self.path)
  }
}

pub struct CfgArr<'a> {
  seq: &'a [Value],
  path: CfgPath,
}

impl<'a> CfgArr<'a> {
  pub fn len(&self) -> usize {
    self.seq.len()
  }

  pub fn is_empty(&self) -> bool {
    self.seq.is_empty()
  }

  pub fn get(&self, index: usize) -> Option<CfgNode<'a>> {
    self.seq.get(index).map(|v| CfgNode {
      value: v,
      path: self.path.join(index),
    })
  }

  pub fn iter(&self) -> impl Iterator<Item = CfgNode<'a>> + '_ {
    self.seq.iter().enumerate().map(move |(i, v)| CfgNode {
      value: v,
      path: self.path.join(i),
    })
  }

  /// Parse all elements as `T`.
  pub fn collect<T: FromCfg>(&self, cx: &CfgCx) -> Result<Vec<T>> {
    self.iter().map(|node| T::from_cfg(&node, cx)).collect()
  }

  pub fn path(&self) -> &CfgPath {
    &self.path
  }
}

//
// FromCfg
//

pub trait FromCfg: Sized {
  fn from_cfg(node: &CfgNode<'_>, cx: &CfgCx) -> Result<Self>;
}

// Primitive impls

impl FromCfg for String {
  fn from_cfg(node: &CfgNode<'_>, _cx: &CfgCx) -> Result<Self> {
    Ok(node.as_str()?.to_owned())
  }
}

impl FromCfg for bool {
  fn from_cfg(node: &CfgNode<'_>, _cx: &CfgCx) -> Result<Self> {
    node.as_bool()
  }
}

impl FromCfg for usize {
  fn from_cfg(node: &CfgNode<'_>, _cx: &CfgCx) -> Result<Self> {
    node.as_usize()
  }
}

impl FromCfg for u64 {
  fn from_cfg(node: &CfgNode<'_>, _cx: &CfgCx) -> Result<Self> {
    node.as_u64()
  }
}

impl FromCfg for i64 {
  fn from_cfg(node: &CfgNode<'_>, _cx: &CfgCx) -> Result<Self> {
    node.as_i64()
  }
}

impl FromCfg for f64 {
  fn from_cfg(node: &CfgNode<'_>, _cx: &CfgCx) -> Result<Self> {
    node.as_f64()
  }
}

impl FromCfg for PathBuf {
  fn from_cfg(node: &CfgNode<'_>, _cx: &CfgCx) -> Result<Self> {
    Ok(PathBuf::from(node.as_str()?))
  }
}

impl FromCfg for OsString {
  fn from_cfg(node: &CfgNode<'_>, _cx: &CfgCx) -> Result<Self> {
    Ok(OsString::from(node.as_str()?))
  }
}

impl FromCfg for Value {
  fn from_cfg(node: &CfgNode<'_>, _cx: &CfgCx) -> Result<Self> {
    Ok(node.raw().clone())
  }
}

// Composite impls

impl<T: FromCfg> FromCfg for Vec<T> {
  fn from_cfg(node: &CfgNode<'_>, cx: &CfgCx) -> Result<Self> {
    node.as_arr()?.collect(cx)
  }
}

impl<T: FromCfg> FromCfg for Option<T> {
  fn from_cfg(node: &CfgNode<'_>, cx: &CfgCx) -> Result<Self> {
    if node.is_null() {
      Ok(None)
    } else {
      Ok(Some(T::from_cfg(node, cx)?))
    }
  }
}

impl<T: FromCfg> FromCfg for IndexMap<String, T> {
  fn from_cfg(node: &CfgNode<'_>, cx: &CfgCx) -> Result<Self> {
    let obj = node.as_obj()?;
    obj
      .iter()
      .map(|(k, v)| Ok((k.to_owned(), T::from_cfg(&v, cx)?)))
      .collect()
  }
}

//
// IntoCfg
//

pub trait IntoCfg {
  fn into_cfg(&self) -> Value;
}

impl IntoCfg for String {
  fn into_cfg(&self) -> Value {
    Value::String(self.clone())
  }
}

impl IntoCfg for &str {
  fn into_cfg(&self) -> Value {
    Value::String(self.to_string())
  }
}

impl IntoCfg for bool {
  fn into_cfg(&self) -> Value {
    Value::Bool(*self)
  }
}

impl IntoCfg for usize {
  fn into_cfg(&self) -> Value {
    Value::Number((*self as u64).into())
  }
}

impl IntoCfg for u64 {
  fn into_cfg(&self) -> Value {
    Value::Number((*self).into())
  }
}

impl IntoCfg for i64 {
  fn into_cfg(&self) -> Value {
    Value::Number((*self).into())
  }
}

impl<T: IntoCfg> IntoCfg for Vec<T> {
  fn into_cfg(&self) -> Value {
    Value::Sequence(self.iter().map(|v| v.into_cfg()).collect())
  }
}

impl<T: IntoCfg> IntoCfg for Option<T> {
  fn into_cfg(&self) -> Value {
    match self {
      Some(v) => v.into_cfg(),
      None => Value::Null,
    }
  }
}

impl<T: IntoCfg> IntoCfg for IndexMap<String, T> {
  fn into_cfg(&self) -> Value {
    let mut map = serde_yaml::Mapping::new();
    for (k, v) in self {
      map.insert(Value::String(k.clone()), v.into_cfg());
    }
    Value::Mapping(map)
  }
}

impl IntoCfg for Value {
  fn into_cfg(&self) -> Value {
    self.clone()
  }
}