shep 0.24.1

The shep binary: a process manager that keeps a flock of long-running processes alive on macOS, Linux and Windows, with logs, watch and cron restarts, and webhook alerts
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
//! A sheep's table for a dog that follows the settings standard, with the
//! dog's section shown under it.
//!
//! The rows show what the dog reads: the sheep's own value where it has one,
//! else the section's. A row the sheep does not set is inherited. It is not
//! stored, so typing the same value files an own one, and `d` has nothing to
//! restore.

use std::collections::BTreeSet;
use std::sync::Arc;

use serde_json::{Map, Value};
use shep_core::config::DogTable;
use shep_core::dogs::manifest::Serves;

use super::super::field::{flatten_values, segment};
use super::sheep_dog::SheepDogTable;
use super::{ConfigPane, PaneTarget, StandardSection};

/// The section a sheep's table sits over, and the rows it fills.
#[derive(Clone)]
pub(super) struct Inherits {
    /// The dog's section without its dog-wide keys.
    shared: Map<String, Value>,
    /// Which sheep the dog serves: an opted-in dog reads the section for a
    /// sheep only once the sheep carries a table.
    serves: Serves,
    /// Whether the sheep carries a table for the dog, empty or not.
    pub(super) has_table: bool,
    /// `shared` by row key, what a cleared row goes back to.
    shared_values: Map<String, Value>,
    /// The rows the sheep's own table leaves to the section.
    inherited: BTreeSet<String>,
}

impl SheepDogTable {
    /// The section under the table, once the dog reads it for this sheep.
    fn layering(&self) -> Option<&Inherits> {
        self.inherits
            .as_ref()
            .filter(|inherits| inherits.serves == Serves::EverySheep || inherits.has_table)
    }

    /// What the rows show, and which of them the section fills.
    pub(super) fn displayed(&self) -> (Map<String, Value>, BTreeSet<String>) {
        let own = flatten_values(&self.table, &self.paths);
        let Some(inherits) = self.layering() else {
            return (own, BTreeSet::new());
        };
        let table = DogTable::layered(&[
            &DogTable::from(inherits.shared.clone()),
            &DogTable::from(self.table.clone()),
        ])
        .into_map();
        let shown = flatten_values(&table, &self.paths);
        let inherited = shown
            .iter()
            .filter(|(key, value)| !value.is_null() && own.get(*key).is_none_or(Value::is_null))
            .map(|(key, _)| key.clone())
            .collect();
        (shown, inherited)
    }

    pub(super) fn set_inherited(&mut self, inherited: BTreeSet<String>) {
        if let Some(inherits) = &mut self.inherits {
            inherits.inherited = inherited;
        }
    }
}

impl ConfigPane {
    /// A pane over `dog`'s table on `sheep` with `shared` under it.
    ///
    /// `schema` is the dog's one schema without its dog-wide properties.
    /// `table` is [`None`] for a sheep with no table. A row the table lacks
    /// and the section has shows the section's value, and
    /// [`Self::is_inherited`] says so. A dog serving opted-in sheep shows
    /// none for a sheep with no table, since the dog reads none there.
    #[must_use]
    pub fn sheep_dog_inheriting(
        sheep: String,
        dog: String,
        schema: &Value,
        table: Option<Map<String, Value>>,
        section: &StandardSection,
    ) -> Self {
        let has_table = table.is_some();
        let mut pane = Self::sheep_dog(sheep, dog, schema, table.unwrap_or_default());
        if let Some(state) = pane.dog_table.as_mut() {
            let shared_values = flatten_values(&section.shared, &state.paths);
            state.inherits = Some(Inherits {
                shared: section.shared.clone(),
                serves: section.serves,
                has_table,
                shared_values,
                inherited: BTreeSet::new(),
            });
            let (values, inherited) = state.displayed();
            state.set_inherited(inherited);
            pane.entries = Arc::new(pane.entries.rebuilt(&pane.fields, &state.paths, &values));
            pane.values = values;
        }
        pane
    }

    /// Whether the dog's section, not this sheep's table, gives `key` its
    /// value. False for any pane that does not sit over a section.
    #[must_use]
    pub fn is_inherited(&self, key: &str) -> bool {
        self.dog_table
            .as_ref()
            .and_then(|state| state.inherits.as_ref())
            .is_some_and(|inherits| inherits.inherited.contains(key))
    }

    /// Whether this pane shows the dog's section under the sheep's table:
    /// false for a pane over no section, and for an opted-in sheep with no
    /// table, which the dog reads nothing for.
    #[must_use]
    pub fn inherits_section(&self) -> bool {
        matches!(self.target, PaneTarget::SheepDog { .. })
            && self
                .dog_table
                .as_ref()
                .is_some_and(|state| state.layering().is_some())
    }

    /// Whether `key` is dog-wide on a dog's own pane: the section sets it
    /// for every sheep, and no sheep's table can hold its own.
    #[must_use]
    pub fn is_dog_wide(&self, key: &str) -> bool {
        self.section.as_ref().is_some_and(|section| {
            section.dog_wide.iter().any(|wide| {
                let wide = segment(wide);
                key == wide
                    || key
                        .strip_prefix(wide.as_str())
                        .is_some_and(|rest| rest.starts_with('.'))
            })
        })
    }

    /// Whether this is a dog's pane over a dog that follows the standard,
    /// whose values every sheep shares.
    #[must_use]
    pub fn applies_to_every_sheep(&self) -> bool {
        self.section
            .as_ref()
            .is_some_and(|section| !section.dog_wide.is_empty())
    }

    /// The section's value for `key`, which a row cleared in the pane goes
    /// back to. [`None`] when the section has none.
    pub(super) fn inherited_value(&self, key: &str) -> Option<&Value> {
        self.dog_table
            .as_ref()?
            .inherits
            .as_ref()?
            .shared_values
            .get(key)
            .filter(|value| !value.is_null())
    }

    /// Takes the dog's section as it stands now, keeping the cursor and the
    /// filed edits. A pane over no section ignores it.
    pub(in crate::lookout) fn adopt_section(&mut self, section: &StandardSection) {
        let Some(state) = self.dog_table.as_mut() else {
            return;
        };
        let paths = &state.paths;
        let Some(inherits) = state.inherits.as_mut() else {
            return;
        };
        inherits.shared = section.shared.clone();
        inherits.shared_values = flatten_values(&section.shared, paths);
        let table = inherits.has_table.then(|| state.table.clone());
        self.adopt_table(table);
    }

    /// What `key` goes back to when its own value is cleared: the section's
    /// value, rendered like a filed one. [`None`] when the section has none.
    pub(super) fn inherited_text(&self, key: &str) -> Option<String> {
        let shared = self.inherited_value(key)?;
        Some(self.filed_text(key, shared))
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::super::super::edits::{EditKey, Edits};
    use super::super::PaneEdit;
    use super::super::fixtures::field;
    use super::*;
    use crate::lookout::view::fixtures::{plain, render_all};
    use crate::lookout::view::pane::pane_lines;

    /// The `jobs` dog's one schema as a sheep sees it: `poll` is dog-wide
    /// and already gone.
    fn sheep_form() -> Value {
        json!({
            "type": "object",
            "properties": {
                "model": { "type": "string" },
                "limit": { "type": "integer" },
            },
        })
    }

    fn table(value: Value) -> Map<String, Value> {
        value.as_object().cloned().expect("a table")
    }

    fn section(serves: Serves, shared: Value) -> StandardSection {
        StandardSection {
            serves,
            shared: table(shared),
        }
    }

    fn pane(own: Value) -> ConfigPane {
        ConfigPane::sheep_dog_inheriting(
            "web".into(),
            "jobs".into(),
            &sheep_form(),
            Some(table(own)),
            &section(Serves::EverySheep, json!({ "model": "sonnet", "limit": 3 })),
        )
    }

    fn set(key: &str, value: Value) -> Edits {
        let mut edits = Edits::default();
        edits.set(field(key, value), None);
        edits
    }

    #[test]
    fn a_key_the_sheep_lacks_shows_the_sections_value_as_inherited() {
        let pane = pane(json!({ "limit": 9 }));
        assert!(pane.is_inherited("model"));
        assert_eq!(pane.value("model"), "sonnet");
        assert!(!pane.is_inherited("limit"));
        assert_eq!(pane.value("limit"), "9");
    }

    #[test]
    fn a_sheep_with_no_table_inherits_every_key_the_section_sets() {
        let pane = pane(json!({}));
        assert!(pane.is_inherited("model") && pane.is_inherited("limit"));
        assert_eq!(pane.value("limit"), "3");
    }

    #[test]
    fn an_opted_in_dog_shows_the_section_only_once_the_sheep_has_a_table() {
        let section = section(Serves::OptedIn, json!({ "model": "sonnet" }));
        let mut pane = ConfigPane::sheep_dog_inheriting(
            "web".into(),
            "jobs".into(),
            &sheep_form(),
            None,
            &section,
        );
        assert!(!pane.is_inherited("model"));
        assert_eq!(pane.value("model"), "(unset)");

        pane.adopt_table(Some(table(json!({ "limit": 9 }))));
        assert!(pane.is_inherited("model"));
        assert_eq!(pane.value("model"), "sonnet");
    }

    #[test]
    fn an_opted_in_sheep_with_no_table_draws_no_inheritance_footer() {
        let section = section(Serves::OptedIn, json!({ "model": "sonnet" }));
        let mut pane = ConfigPane::sheep_dog_inheriting(
            "web".into(),
            "jobs".into(),
            &sheep_form(),
            None,
            &section,
        );
        assert!(!pane.inherits_section());
        let text = render_all(&pane_lines(&pane, plain(), 120, 0));
        assert!(!text.contains("comes from"), "{text}");

        pane.adopt_table(Some(table(json!({ "limit": 9 }))));
        assert!(pane.inherits_section());
        let text = render_all(&pane_lines(&pane, plain(), 120, 0));
        assert!(text.contains("^ comes from [jobs]"), "{text}");
    }

    #[test]
    fn a_pane_over_no_section_inherits_nothing() {
        let pane = ConfigPane::sheep_dog(
            "web".into(),
            "jobs".into(),
            &sheep_form(),
            table(json!({ "limit": 9 })),
        );
        assert!(!pane.is_inherited("model") && !pane.inherits_section());
        assert_eq!(pane.value("model"), "(unset)");
    }

    #[test]
    fn setting_then_clearing_a_key_writes_it_to_the_sheeps_table_then_removes_it() {
        let mut pane = pane(json!({ "limit": 9 }));

        let written = pane.edited_table_with(&set("model", json!("haiku")));
        assert_eq!(
            Value::Object(written.clone()),
            json!({ "limit": 9, "model": "haiku" })
        );

        pane.adopt_table(Some(written));
        assert!(!pane.is_inherited("model"));
        assert_eq!(pane.value("model"), "haiku");

        let cleared = pane.edited_table_with(&set("model", Value::Null));
        assert_eq!(Value::Object(cleared.clone()), json!({ "limit": 9 }));

        pane.adopt_table(Some(cleared));
        assert!(pane.is_inherited("model"));
        assert_eq!(pane.value("model"), "sonnet");
    }

    #[test]
    fn typing_the_inherited_value_pins_it_as_an_own_value() {
        let mut pane = pane(json!({ "limit": 9 }));
        pane.file_field("model".into(), json!("sonnet"));
        assert!(pane.edits().get(&EditKey::Field("model".into())).is_some());
        let written = pane.edited_table_with(pane.edits());
        assert_eq!(written["model"], "sonnet");
    }

    #[test]
    fn restoring_an_inherited_row_files_nothing() {
        let mut pane = pane(json!({ "limit": 9 }));
        pane.move_to_key("model");
        pane.file_default();
        assert!(pane.edits().is_empty());
    }

    #[test]
    fn restoring_an_own_row_files_its_removal_and_names_what_it_goes_back_to() {
        let mut pane = pane(json!({ "model": "haiku" }));
        pane.move_to_key("model");
        pane.file_default();
        let filed = pane
            .edits()
            .get(&EditKey::Field("model".into()))
            .expect("filed");
        assert!(matches!(filed.edit(), PaneEdit::Set { value, .. } if value.as_value().is_null()));
        assert_eq!(
            pane.edited_value("model").as_deref(),
            Some("sonnet (inherited)")
        );
    }

    #[test]
    fn a_bool_cycles_from_the_inherited_value() {
        let schema = json!({ "type": "object", "properties": { "auto": { "type": "boolean" } } });
        let mut pane = ConfigPane::sheep_dog_inheriting(
            "web".into(),
            "jobs".into(),
            &schema,
            None,
            &section(Serves::EverySheep, json!({ "auto": true })),
        );
        pane.move_to_key("auto");
        pane.cycle();
        let filed = pane
            .edits()
            .get(&EditKey::Field("auto".into()))
            .expect("filed");
        assert!(
            matches!(filed.edit(), PaneEdit::Set { value, .. } if value.as_value() == &json!(false))
        );
    }

    #[test]
    fn a_bool_cleared_in_the_pane_cycles_from_the_sections_value() {
        let schema = json!({ "type": "object", "properties": { "auto": { "type": "boolean" } } });
        let mut pane = ConfigPane::sheep_dog_inheriting(
            "web".into(),
            "jobs".into(),
            &schema,
            Some(table(json!({ "auto": true }))),
            &section(Serves::EverySheep, json!({ "auto": true })),
        );
        pane.move_to_key("auto");
        pane.file_default();
        pane.cycle();
        let filed = pane
            .edits()
            .get(&EditKey::Field("auto".into()))
            .expect("filed");
        assert!(
            matches!(filed.edit(), PaneEdit::Set { value, .. } if value.as_value() == &json!(false)),
            "{filed:?}"
        );
    }

    fn clients_schema() -> Value {
        json!({
            "type": "object",
            "properties": {
                "clients": { "type": "array", "items": { "$ref": "#/$defs/Client" } },
                "token": { "type": "string", "x-shep-secret": true },
            },
            "$defs": { "Client": { "type": "object", "properties": {
                "name": { "type": "string" },
                "key": { "type": "string", "x-shep-secret": true },
            } } },
        })
    }

    fn cleared_pane(own: Value) -> ConfigPane {
        let mut pane = ConfigPane::sheep_dog_inheriting(
            "web".into(),
            "jobs".into(),
            &clients_schema(),
            Some(table(own)),
            &section(
                Serves::EverySheep,
                json!({
                    "clients": [{ "name": "alpha", "key": "hunter2" }],
                    "token": "s3cret",
                }),
            ),
        );
        pane.file_field("clients".into(), Value::Null);
        pane.file_field("token".into(), Value::Null);
        pane
    }

    #[test]
    fn clearing_an_entries_row_names_a_count_and_never_the_inherited_secret_leaves() {
        let pane = cleared_pane(json!({ "clients": [{ "name": "own" }], "token": "mine" }));
        let text = pane.edited_value("clients").expect("filed");
        assert_eq!(text, "1 entry (inherited)");
        assert!(!text.contains("hunter2"), "{text}");
    }

    #[test]
    fn clearing_a_secret_row_draws_no_value_on_the_row_or_in_the_pending_list() {
        let pane = cleared_pane(json!({ "clients": [{ "name": "own" }], "token": "mine" }));
        let text = render_all(&pane_lines(&pane, plain(), 120, 0));
        assert!(
            !text.contains("s3cret") && !text.contains("hunter2"),
            "{text}"
        );
        assert!(!text.contains("mine"), "{text}");
        assert!(text.contains("<set> -> <set>"), "{text}");
    }

    #[test]
    fn a_new_section_replaces_what_the_inherited_rows_show() {
        let mut pane = pane(json!({ "limit": 9 }));
        pane.adopt_section(&section(Serves::EverySheep, json!({ "model": "haiku" })));
        assert!(pane.is_inherited("model"));
        assert_eq!(pane.value("model"), "haiku");
        assert!(!pane.is_inherited("limit"));
        assert_eq!(pane.value("limit"), "9");
    }

    #[test]
    fn a_new_section_does_not_give_an_opted_in_sheep_with_no_table_a_table() {
        let first = section(Serves::OptedIn, json!({ "model": "sonnet" }));
        let mut pane = ConfigPane::sheep_dog_inheriting(
            "web".into(),
            "jobs".into(),
            &sheep_form(),
            None,
            &first,
        );
        pane.adopt_section(&section(Serves::OptedIn, json!({ "model": "haiku" })));
        assert!(!pane.is_inherited("model"));
        assert_eq!(pane.value("model"), "(unset)");

        pane.adopt_table(Some(table(json!({ "limit": 9 }))));
        pane.adopt_section(&section(Serves::OptedIn, json!({ "model": "opus" })));
        assert!(pane.is_inherited("model"));
        assert_eq!(pane.value("model"), "opus");
    }

    #[test]
    fn a_dog_wide_key_with_a_dot_in_its_name_is_found_by_its_quoted_row() {
        let schema = json!({
            "type": "object",
            "properties": {
                "a.b": { "type": "string", "x-shep-dog-wide": true },
                "model": { "type": "string" },
            },
        });
        let pane = ConfigPane::dog("jobs".into(), None, schema, String::new(), Vec::new());
        assert!(pane.is_dog_wide("\"a.b\""));
        assert!(!pane.is_dog_wide("a.b"));
        assert!(!pane.is_dog_wide("model"));
    }

    #[test]
    fn a_dog_wide_key_with_a_dot_draws_the_mark_on_its_row() {
        let schema = json!({
            "type": "object",
            "properties": {
                "a.b": { "type": "string", "x-shep-dog-wide": true },
                "model": { "type": "string" },
            },
        });
        let pane = ConfigPane::dog(
            "jobs".into(),
            None,
            schema,
            "\"a.b\" = \"x\"\nmodel = \"m\"\n".into(),
            Vec::new(),
        );
        let text = render_all(&pane_lines(&pane, plain(), 120, 0));
        assert!(text.contains("@\"a.b\""), "{text}");
        assert!(!text.contains("@model"), "{text}");
    }

    fn jobs_dog_pane() -> ConfigPane {
        let schema = json!({
            "type": "object",
            "properties": {
                "poll": { "type": "string", "x-shep-dog-wide": true },
                "model": { "type": "string" },
            },
        });
        ConfigPane::dog(
            "jobs".into(),
            None,
            schema,
            "poll = \"5m\"\nmodel = \"sonnet\"\n".into(),
            Vec::new(),
        )
    }

    #[test]
    fn the_dog_pane_marks_a_dog_wide_row_and_says_its_values_reach_every_sheep() {
        let pane = jobs_dog_pane();
        assert!(pane.applies_to_every_sheep());
        assert!(pane.is_dog_wide("poll") && !pane.is_dog_wide("model"));

        let text = render_all(&pane_lines(&pane, plain(), 120, 0));
        let row = |key: &str| {
            text.lines()
                .find(|line| line.trim_start_matches(['>', ' ', '@']).starts_with(key))
                .unwrap_or_else(|| panic!("no {key} row in {text}"))
                .to_owned()
        };
        assert!(row("poll").contains("@poll"), "{}", row("poll"));
        assert!(!row("model").contains('@'), "{}", row("model"));
        assert!(text.contains("apply to every sheep it serves"), "{text}");
    }

    #[test]
    fn a_dog_pane_marking_nothing_dog_wide_draws_as_before() {
        let schema = json!({ "type": "object", "properties": { "model": { "type": "string" } } });
        let pane = ConfigPane::dog("jobs".into(), None, schema, String::new(), Vec::new());
        assert!(!pane.applies_to_every_sheep());
        let text = render_all(&pane_lines(&pane, plain(), 120, 0));
        assert!(
            !text.contains("every sheep") && !text.contains('@'),
            "{text}"
        );
    }

    #[test]
    fn the_pane_marks_an_inherited_row_and_draws_no_dog_wide_row() {
        let text = render_all(&pane_lines(&pane(json!({ "limit": 9 })), plain(), 120, 0));
        let row = |key: &str| {
            text.lines()
                .find(|line| line.contains(key))
                .unwrap_or_else(|| panic!("no {key} row in {text}"))
                .to_owned()
        };
        assert!(row("model").contains("^model"), "{}", row("model"));
        assert!(row("model").contains("sonnet"));
        assert!(row("limit").contains(" limit") && !row("limit").contains("^limit"));
        assert!(!text.contains("poll"), "{text}");
        assert!(text.contains("^ comes from [jobs]"), "{text}");
    }
}