shep 0.15.2

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
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
//! `shep copy`: one setting, or one dog's whole table, from one sheep onto
//! another.
//!
//! Three requests do the talking. `Request::ListFlock` resolves the two names
//! against the flock, `Request::SheepConfig` reads each side, and the write is
//! the request the plan turns into: [`Request::SetSheepField`] for a field,
//! [`Request::SetSheepDogSettings`] for a dog's table. There is no copy
//! request, so everything those refuse this refuses, with the same reason.
//!
//! The order is resolve, read, plan, print, ask, write. Nothing is sent until
//! the operator has seen every key the copy touches, which is also why a
//! refusal never leaves a half-written sheep behind.
//!
//! The table form prints the change list before the question, because that is
//! what the question is asked beside. The JSON form prints one envelope at the
//! end, carrying the same list beside `written` and `pending`: one object per
//! invocation is the rule `--format json` keeps.

pub(crate) mod address;
pub(crate) mod confirm;
pub(crate) mod plan;
pub(crate) mod report;

use std::fmt;
use std::io::IsTerminal as _;

use shep_client::Client;
use shep_core::protocol::{Request, Response};

use crate::cli::{CopyArgs, Format};
use crate::commands::rpc::{client_error, unexpected_response};
use crate::exit::ExitCode;
use crate::output::Streams;

use address::{Address, ConfigPath, FlockNames};
use confirm::{Answer, Go, confirm, decide};
use plan::{Plan, Write};
use report::{finish, print_changes, report_for, shows_changes_first};

/// Why a copy stopped before it wrote anything.
///
/// Every variant carries the sentence the operator reads, because the reason
/// is the remedy: `env` names `shep import env`, an instance count names
/// `shep stock`, and a missing source names the path that is missing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum CopyRefusal {
    /// An address or a flag is malformed, or the two sides name different
    /// paths, or the same sheep.
    Usage(String),
    /// No sheep in this flock answers that name.
    UnknownSheep(String),
    /// The source sheep has no table, or no key, at the path named.
    MissingSource(String),
    /// A key this verb never copies, in the reason the shepherd gives for it.
    Refused(String),
}

impl CopyRefusal {
    /// The sentence the operator reads.
    pub(crate) fn message(&self) -> &str {
        match self {
            Self::Usage(message)
            | Self::UnknownSheep(message)
            | Self::MissingSource(message)
            | Self::Refused(message) => message,
        }
    }

    /// The code that reports it.
    ///
    /// [`ExitCode::InvalidConfig`] for a refused key is the code the shepherd's
    /// own refusal of that key carries, so `copy` and the request it stands in
    /// for exit alike.
    const fn code(&self) -> ExitCode {
        match self {
            Self::Usage(_) => ExitCode::Usage,
            Self::UnknownSheep(_) | Self::MissingSource(_) => ExitCode::NotFound,
            Self::Refused(_) => ExitCode::InvalidConfig,
        }
    }

    /// Writes the refusal and hands back the code it wrote.
    fn report(&self, streams: &mut Streams<'_>) -> ExitCode {
        streams.fail(self.code(), self.message())
    }
}

impl fmt::Display for CopyRefusal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.message())
    }
}

impl core::error::Error for CopyRefusal {}

/// `shep copy <from> <to>`.
///
/// # Errors
/// The [`ExitCode`] already reported to `streams`: a malformed address, a name
/// no sheep answers, a key this verb refuses, a missing source, a refusal to
/// write with no terminal to ask on, or a write the shepherd refused.
pub(crate) async fn copy(client: &Client, streams: &mut Streams<'_>, args: &CopyArgs) -> ExitCode {
    let flock = match flock_names(client, streams).await {
        Ok(names) => names,
        Err(code) => return code,
    };
    let from = match address::written(&args.from, &flock) {
        Ok(written) => written,
        Err(refusal) => return refusal.report(streams),
    };
    let to = match address::written(&args.to, &flock) {
        Ok(written) => written,
        Err(refusal) => return refusal.report(streams),
    };
    if let Some(refusal) = same_sheep(&from.sheep, &to.sheep) {
        return refusal.report(streams);
    }
    let except = match plan::except_paths(&args.except) {
        Ok(paths) => paths,
        Err(refusal) => return refusal.report(streams),
    };

    let source = match read_config(client, streams, &from.sheep).await {
        Ok(config) => config,
        Err(code) => return code,
    };
    let target = match read_config(client, streams, &to.sheep).await {
        Ok(config) => config,
        Err(code) => return code,
    };

    // The path half is read after the two configs, because a dog name and a
    // key inside a table may each contain a dot, and only the tables say where
    // one ends.
    let dogs = address::DogNames::new(&flock, &source, &target);
    let from = match address::path_of(&from, &dogs, &source, &target) {
        Ok(path) => Address {
            sheep: from.sheep.clone(),
            path,
        },
        Err(refusal) => return refusal.report(streams),
    };
    let to = match address::path_of(&to, &dogs, &source, &target) {
        Ok(path) => Address {
            sheep: to.sheep.clone(),
            path,
        },
        Err(refusal) => return refusal.report(streams),
    };
    if let Err(refusal) = same_pair(&from, &to) {
        return refusal.report(streams);
    }

    let plan = match build_plan(&from, &to, &except, args.replace, &source, &target) {
        Ok(plan) => plan,
        Err(refusal) => return refusal.report(streams),
    };

    let path = from.path.dotted();
    let mut report = report_for(&from, &to, &plan, false, args.dry_run);

    if plan.changes.is_empty() {
        let message = format!(
            "nothing to copy: `{}` already holds the same value at `{path}`",
            to.sheep
        );
        streams.note("copy", &message);
        return finish(streams, &report);
    }

    let go = decide(
        args.dry_run,
        args.yes,
        std::io::stdin().is_terminal(),
        !plan.changes.is_empty(),
    );

    // The change list prints before anything is asked about it, in every
    // form. Where it prints depends on what that form's stdout carries: the
    // table form's stdout is the change list, and the JSON form's is one
    // envelope that can only be written after the write the question gates.
    if shows_changes_first(streams.fmt, go)
        && let Err(code) = print_changes(streams, &report)
    {
        return code;
    }

    if go == Go::Refuse {
        return streams.fail(
            ExitCode::Usage,
            "nothing was written: `shep copy` asks before it writes, and this run has no \
             terminal to ask on. Pass --yes to write without asking, or --dry-run to see the \
             changes and write nothing",
        );
    }
    if go == Go::Ask {
        let mut reader = std::io::stdin().lock();
        match confirm(
            streams,
            &from.sheep,
            &to.sheep,
            &path,
            plan.changes.len(),
            &mut reader,
        ) {
            Answer::Yes => {}
            Answer::No => {
                streams.note("copy", "nothing was written");
                return finish(streams, &report);
            }
            Answer::Failed(reason) => {
                return streams.fail(
                    ExitCode::Failure,
                    &format!("nothing was written: the question could not be read ({reason})"),
                );
            }
        }
    }
    if go == Go::DryRun {
        streams.note("dry_run", "nothing was written");
        return finish(streams, &report);
    }

    let Some(write) = plan.write.clone() else {
        let message = format!("the plan named {} changes and no write", plan.changes.len());
        return streams.fail(ExitCode::Internal, &message);
    };
    let pending = match write_plan(client, streams, &to.sheep, write).await {
        Ok(pending) => pending,
        Err(code) => return code,
    };

    report = report_for(&from, &to, &plan, true, args.dry_run);
    if !pending.is_empty() {
        let message = format!(
            "{} waiting on the next spawn (`shep reload {}` promotes them)",
            pending.join(", "),
            to.sheep
        );
        streams.note("parked", &message);
    }
    report.pending = pending;
    if streams.fmt == Format::Table {
        let message = format!(
            "wrote {} change{} onto `{}`",
            plan.changes.len(),
            if plan.changes.len() == 1 { "" } else { "s" },
            to.sheep
        );
        streams.note("written", &message);
    }
    finish(streams, &report)
}

/// The flock's names, split into sheep and dogs.
///
/// # Errors
/// The [`ExitCode`] already reported to `streams`.
async fn flock_names(client: &Client, streams: &mut Streams<'_>) -> Result<FlockNames, ExitCode> {
    match client.request(Request::ListFlock).await {
        Ok(Response::Flock(info)) => Ok(FlockNames {
            sheep: info
                .iter()
                .filter(|info| info.dog.is_none())
                .map(|info| info.name.clone())
                .collect(),
            dogs: info
                .iter()
                .filter(|info| info.dog.is_some())
                .map(|info| info.name.clone())
                .collect(),
        }),
        Ok(_other) => Err(unexpected_response(streams)),
        Err(err) => Err(client_error(streams, &err)),
    }
}

/// One sheep's config as JSON, which is the shape a plan reads.
///
/// `env` is already emptied by the shepherd, which is what makes `env` a
/// refusal here rather than a copy of something that is not there.
///
/// # Errors
/// The [`ExitCode`] already reported to `streams`.
async fn read_config(
    client: &Client,
    streams: &mut Streams<'_>,
    name: &str,
) -> Result<serde_json::Value, ExitCode> {
    match client
        .request(Request::SheepConfig {
            name: name.to_string(),
        })
        .await
    {
        Ok(Response::SheepConfig(view)) => serde_json::to_value(&view.config).map_err(|_| {
            streams.fail(
                ExitCode::Internal,
                "the shepherd's config answer did not serialize, so nothing was copied",
            )
        }),
        Ok(_other) => Err(unexpected_response(streams)),
        Err(err) => Err(client_error(streams, &err)),
    }
}

/// The refusal for one sheep named on both sides.
fn same_sheep(from: &str, to: &str) -> Option<CopyRefusal> {
    (from == to).then(|| {
        CopyRefusal::Usage(format!(
            "`{from}` is on both sides: a copy needs two different sheep"
        ))
    })
}

/// The two sides of one copy: two different sheep, and one path between them.
///
/// # Errors
/// [`CopyRefusal::Usage`] for a path that differs, or for a sheep named on
/// both sides.
fn same_pair(from: &Address, to: &Address) -> Result<(), CopyRefusal> {
    if from.path != to.path {
        return Err(CopyRefusal::Usage(format!(
            "the path must be the same on both sides: `{}.{}` and `{}.{}`",
            from.sheep,
            from.path.dotted(),
            to.sheep,
            to.path.dotted()
        )));
    }
    if let Some(refusal) = same_sheep(&from.sheep, &to.sheep) {
        return Err(refusal);
    }
    Ok(())
}

/// The plan for one copy.
///
/// # Errors
/// [`CopyRefusal::Usage`] for `--except` on a field, and whatever
/// [`plan::plan_dog`] refuses about the source.
fn build_plan(
    from: &Address,
    to: &Address,
    except: &[Vec<String>],
    replace: bool,
    source: &serde_json::Value,
    target: &serde_json::Value,
) -> Result<Plan, CopyRefusal> {
    match &from.path {
        ConfigPath::Field { name } => {
            if !except.is_empty() {
                return Err(CopyRefusal::Usage(format!(
                    "--except names a key inside a dog's table: `{name}` is one field, and a \
                     copy takes a field whole"
                )));
            }
            Ok(plan::plan_field(name, source, target))
        }
        ConfigPath::Dog { dog, keys } => plan::plan_dog(
            plan::Sides {
                source: &from.sheep,
                target: &to.sheep,
            },
            dog,
            keys,
            except,
            replace,
            source,
            target,
        ),
    }
}

/// Sends the plan's write, and reports which keys wait for a respawn.
///
/// # Errors
/// The [`ExitCode`] already reported to `streams`.
async fn write_plan(
    client: &Client,
    streams: &mut Streams<'_>,
    target: &str,
    write: Write,
) -> Result<Vec<String>, ExitCode> {
    match write {
        Write::Field { name, value } => {
            let request = Request::SetSheepField {
                name: target.to_string(),
                key: name.clone(),
                value,
            };
            match client.request(request).await {
                Ok(Response::SheepFieldSet {
                    pending, warning, ..
                }) => {
                    if let Some(warning) = warning {
                        streams.aside("warning", &warning);
                    }
                    Ok(pending.then_some(name).into_iter().collect())
                }
                Ok(_other) => Err(unexpected_response(streams)),
                Err(err) => Err(client_error(streams, &err)),
            }
        }
        Write::DogTable { dog, table } => {
            let request = Request::SetSheepDogSettings {
                name: target.to_string(),
                dog,
                table: Some(table),
            };
            match client.request(request).await {
                Ok(Response::SheepDogSettingsSet { .. }) => Ok(Vec::new()),
                Ok(_other) => Err(unexpected_response(streams)),
                Err(err) => Err(client_error(streams, &err)),
            }
        }
    }
}

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

    use super::*;
    use crate::commands::copy::plan::ChangeKind;

    /// An address, resolved with no config in hand.
    fn address(raw: &str) -> Address {
        let written = address::written(raw, &flock()).unwrap();
        let dogs =
            address::DogNames::new(&flock(), &serde_json::Value::Null, &serde_json::Value::Null);
        Address {
            sheep: written.sheep.clone(),
            path: address::path_of(
                &written,
                &dogs,
                &serde_json::Value::Null,
                &serde_json::Value::Null,
            )
            .unwrap(),
        }
    }

    /// The flock every test here resolves against.
    fn flock() -> FlockNames {
        FlockNames {
            sheep: ["shep", "shep-kelpie", "web", "api", "we.b"]
                .iter()
                .map(|name| (*name).to_string())
                .collect(),
            dogs: ["metrics", "foo.bar"]
                .iter()
                .map(|name| (*name).to_string())
                .collect(),
        }
    }

    /// One sheep's config, holding one dog table built from `table`.
    fn config_with_dog(dog: &str, table: serde_json::Value) -> serde_json::Value {
        json!({ "name": "web", "dogs": { dog: table } })
    }

    /// The pure half of a copy run: resolve, check the pair, plan.
    fn resolve(
        from: &str,
        to: &str,
        source: serde_json::Value,
        target: serde_json::Value,
        except: &[String],
        replace: bool,
    ) -> Result<Plan, CopyRefusal> {
        let flock = flock();
        let from = address::written(from, &flock)?;
        let to = address::written(to, &flock)?;
        let dogs = address::DogNames::new(&flock, &source, &target);
        let from = Address {
            sheep: from.sheep.clone(),
            path: address::path_of(&from, &dogs, &source, &target)?,
        };
        let to = Address {
            sheep: to.sheep.clone(),
            path: address::path_of(&to, &dogs, &source, &target)?,
        };
        same_pair(&from, &to)?;
        let except = plan::except_paths(except)?;
        build_plan(&from, &to, &except, replace, &source, &target)
    }

    /// The table the plan would leave on the target, for a dog copy.
    fn written_table(plan: &Plan) -> serde_json::Map<String, serde_json::Value> {
        let Write::DogTable { table, .. } = plan.write.clone().expect("a dog copy writes") else {
            panic!("a dog copy writes a dog table");
        };
        table.into_map()
    }

    #[test]
    fn a_dog_sub_table_merges_onto_the_target_and_keeps_its_other_keys() {
        let source = config_with_dog(
            "kelpie",
            json!({ "rulings": { "decide": "panel", "report": "brief" }, "git": { "remote": "origin" } }),
        );
        let target = config_with_dog(
            "kelpie",
            json!({ "rulings": { "decide": "issue", "own": "keep" }, "watch": true }),
        );
        let plan = resolve(
            "shep.dogs.kelpie.rulings",
            "shep-kelpie.dogs.kelpie.rulings",
            source,
            target,
            &[],
            false,
        )
        .expect("the source has this table");

        let kinds: Vec<(&str, &str)> = plan
            .changes
            .iter()
            .map(|change| (change.key.as_str(), change.kind.as_str()))
            .collect();
        assert_eq!(
            kinds,
            [("decide", "changed"), ("report", "added"),],
            "the copied sub-table is what is judged, and a key only the target has inside it stays"
        );

        let table = written_table(&plan);
        assert_eq!(
            table["rulings"],
            json!({ "decide": "panel", "own": "keep", "report": "brief" }),
            "the sub-table merges: the source's keys overwrite, the target's own key stays"
        );
        assert_eq!(table["watch"], json!(true), "a key outside the path stays");
        assert!(
            !table.contains_key("git"),
            "the source's `git` sits outside the copied path, so it is not copied"
        );
    }

    #[test]
    fn replace_makes_the_target_table_exactly_the_source() {
        let source = config_with_dog("kelpie", json!({ "rulings": { "decide": "panel" } }));
        let target = config_with_dog(
            "kelpie",
            json!({ "rulings": { "decide": "issue", "own": "gone" }, "watch": true }),
        );
        let plan = resolve(
            "shep.dogs.kelpie",
            "shep-kelpie.dogs.kelpie",
            source,
            target,
            &[],
            true,
        )
        .expect("the source has this table");

        let kinds: Vec<(&str, &str)> = plan
            .changes
            .iter()
            .map(|change| (change.key.as_str(), change.kind.as_str()))
            .collect();
        assert_eq!(
            kinds,
            [
                ("rulings.decide", "changed"),
                ("rulings.own", "removed"),
                ("watch", "removed"),
            ]
        );
        assert_eq!(
            serde_json::Value::Object(written_table(&plan)),
            json!({ "rulings": { "decide": "panel" } })
        );
    }

    #[test]
    fn an_excepted_key_is_left_as_the_target_had_it() {
        let source = config_with_dog(
            "kelpie",
            json!({ "git": { "checkout": "./src", "remote": "upstream" }, "rulings": { "decide": "panel" } }),
        );
        let target = config_with_dog(
            "kelpie",
            json!({ "git": { "checkout": "./mine", "branch": "main" } }),
        );
        let plan = resolve(
            "shep.dogs.kelpie",
            "shep-kelpie.dogs.kelpie",
            source,
            target,
            &["git.checkout".to_string()],
            false,
        )
        .expect("the source has this table");

        let keys: Vec<&str> = plan.changes.iter().map(|c| c.key.as_str()).collect();
        assert_eq!(keys, ["git.remote", "rulings.decide"]);
        assert_eq!(
            written_table(&plan)["git"],
            json!({ "branch": "main", "checkout": "./mine", "remote": "upstream" }),
            "`git.checkout` is the target's own value, and `git.branch` was never in question"
        );
    }

    #[test]
    fn a_field_copies_and_the_refused_fields_say_why() {
        let source = json!({ "name": "web", "restart_delay": "3s", "env": {} });
        let target = json!({ "name": "api", "restart_delay": "1s", "env": {} });
        let plan = resolve(
            "web.restart_delay",
            "api.restart_delay",
            source.clone(),
            target.clone(),
            &[],
            false,
        )
        .expect("restart_delay is a field");
        assert_eq!(plan.changes.len(), 1);
        assert_eq!(plan.changes[0].kind, ChangeKind::Changed);
        assert_eq!(plan.changes[0].old, Some(json!("1s")));
        assert_eq!(
            plan.write,
            Some(Write::Field {
                name: "restart_delay".to_string(),
                value: json!("3s"),
            }),
            "the write is the request the shepherd already answers"
        );

        for (path, expected) in [
            ("web.env", "shep import env"),
            ("web.name", "different sheep"),
            ("web.instances", "shep stock web"),
            ("web.dogs", "web.dogs.<dog>"),
        ] {
            let err = resolve(
                path,
                &path.replace("web.", "api."),
                source.clone(),
                target.clone(),
                &[],
                false,
            )
            .expect_err("{path} is refused");
            assert!(err.message().contains(expected), "{path}: {err}");
        }
    }

    #[test]
    fn different_paths_on_the_two_sides_are_refused() {
        let source = config_with_dog("kelpie", json!({ "rulings": { "decide": "panel" } }));
        let target = config_with_dog("jobs", json!({ "rulings": { "decide": "issue" } }));
        let err = resolve(
            "web.dogs.kelpie.rulings",
            "api.dogs.jobs.rulings",
            source.clone(),
            target.clone(),
            &[],
            false,
        )
        .expect_err("a dog name is part of the path");
        assert_eq!(
            err,
            CopyRefusal::Usage(
                "the path must be the same on both sides: `web.dogs.kelpie.rulings` and \
                 `api.dogs.jobs.rulings`"
                    .to_string()
            )
        );

        let err = resolve(
            "web.restart_delay",
            "api.kill_timeout",
            source,
            target,
            &[],
            false,
        )
        .expect_err("two fields are two paths");
        assert!(err.message().contains("the path must be the same"), "{err}");
    }

    #[test]
    fn dry_run_writes_nothing_and_a_pipe_needs_yes() {
        assert_eq!(decide(true, false, false, true), Go::DryRun);
        assert_eq!(decide(true, true, true, true), Go::DryRun);
        assert_eq!(decide(false, false, false, true), Go::Refuse);
        assert_eq!(decide(false, true, false, true), Go::Write);
        assert_eq!(decide(false, false, true, true), Go::Ask);
        assert_eq!(decide(false, false, true, false), Go::Nothing);

        let source = config_with_dog("kelpie", json!({ "rulings": { "decide": "panel" } }));
        let target = config_with_dog("kelpie", json!({ "rulings": { "decide": "issue" } }));
        let plan = resolve(
            "web.dogs.kelpie",
            "api.dogs.kelpie",
            source,
            target,
            &[],
            false,
        )
        .expect("the source has this table");

        let dry = report_for(
            &address("web.dogs.kelpie"),
            &address("api.dogs.kelpie"),
            &plan,
            false,
            true,
        );
        assert!(dry.dry_run);
        assert!(
            !dry.written,
            "a dry run reports no write, whatever the plan holds"
        );
        assert_eq!(dry.changes.len(), 1);
        assert_ne!(decide(true, false, false, true), Go::Write);
        assert_ne!(decide(false, false, false, true), Go::Write);
    }

    #[test]
    fn a_missing_source_is_named() {
        let source = config_with_dog("kelpie", json!({ "rulings": { "decide": "panel" } }));
        let target = config_with_dog("kelpie", json!({ "rulings": { "decide": "issue" } }));

        let err = resolve(
            "web.dogs.jobs",
            "api.dogs.jobs",
            source.clone(),
            target.clone(),
            &[],
            false,
        )
        .expect_err("no table for `jobs`");
        assert_eq!(
            err,
            CopyRefusal::MissingSource(
                "no `web.dogs.jobs`: that sheep has no table for the dog `jobs`".to_string()
            )
        );

        let err = resolve(
            "web.dogs.kelpie.reporting",
            "api.dogs.kelpie.reporting",
            source.clone(),
            target.clone(),
            &[],
            false,
        )
        .expect_err("no key `reporting`");
        assert_eq!(
            err,
            CopyRefusal::MissingSource("no `reporting` under `web.dogs.kelpie`".to_string())
        );

        let err = resolve(
            "nope.dogs.kelpie",
            "api.dogs.kelpie",
            source,
            target,
            &[],
            false,
        )
        .expect_err("no sheep `nope`");
        assert_eq!(
            err,
            CopyRefusal::UnknownSheep(
                "no sheep named `nope`; `shep flock` lists the flock".to_string()
            )
        );
    }

    #[test]
    fn a_sheep_name_with_a_dot_resolves() {
        let source = config_with_dog("kelpie", json!({ "rulings": { "decide": "panel" } }));
        let target = config_with_dog("kelpie", json!({ "rulings": { "decide": "issue" } }));
        let plan = resolve(
            "we.b.dogs.kelpie.rulings",
            "api.dogs.kelpie.rulings",
            source,
            target,
            &[],
            false,
        )
        .expect("`we.b` is a sheep name, dots and all");
        assert_eq!(plan.changes.len(), 1);
        assert_eq!(plan.changes[0].key, "decide");
    }

    /// A copy onto itself cannot differ, and saying so beats an empty table.
    #[test]
    fn the_same_sheep_on_both_sides_is_refused() {
        let err = same_pair(&address("web.dogs.kelpie"), &address("web.dogs.kelpie"))
            .expect_err("one sheep is not a copy");
        assert_eq!(
            err,
            CopyRefusal::Usage(
                "`web` is on both sides: a copy needs two different sheep".to_string()
            )
        );
    }

    /// `--except` names a key inside a dog's table, and a field is not one.
    #[test]
    fn except_on_a_field_is_refused() {
        let err = resolve(
            "web.restart_delay",
            "api.restart_delay",
            json!({ "restart_delay": "3s" }),
            json!({ "restart_delay": "1s" }),
            &["git.checkout".to_string()],
            false,
        )
        .expect_err("a field has no keys to leave out");
        assert!(err.message().contains("one field"), "{err}");
    }

    /// A flock running a dog named `foo.bar` does not stop a copy of the key
    /// `bar` under the dog `foo`, which is what the address was naming when no
    /// sheep has a table for the flock's dotted name.
    #[test]
    fn a_flock_dog_name_does_not_hide_a_key_under_a_dog_it_prefixes() {
        let source = config_with_dog("foo", json!({ "bar": { "enabled": true } }));
        let target = config_with_dog("foo", json!({ "keep": 1 }));
        let plan = resolve(
            "web.dogs.foo.bar",
            "api.dogs.foo.bar",
            source,
            target,
            &[],
            false,
        )
        .expect("the table reading wins over the flock's dog name");
        assert_eq!(plan.changes.len(), 1);
        assert_eq!(
            plan.changes[0].key, "enabled",
            "a sub-table copy names its keys under the path it copied"
        );
        let table = written_table(&plan);
        assert_eq!(table["bar"], json!({ "enabled": true }));
        assert_eq!(
            table["keep"],
            json!(1),
            "the target's other key under `foo` survives"
        );
    }
}