shep 0.24.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
//! Bare `shep upgrade`: shep through the channel it came from, the shepherd
//! reload, then every installed dog the index has a newer version of.
//!
//! One confirm lists the lot. The channel's manager runs in the foreground
//! with the terminal, so its prompts and `sudo` work. The reload runs the
//! `shep` found on `PATH`, because this process holds the old code and the
//! manager may have removed its path.

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

use semver::Version;
use shep_client::Client;
use shep_core::paths::ShepPaths;

use crate::cli::{Format, UpgradeArgs};
use crate::commands::shep_toml::{ShepToml, ShepTomlError};
use crate::dog_index::{AvailableDog, BUILD_TARGET};
use crate::dog_origin::Origins;
use crate::exit::ExitCode;
use crate::install_channel::Channel;
use crate::output::Streams;

use super::adopt::lookup_on_path;
use super::consent::Input;
use super::dog_upgrade::{Goal, upgrade_dog};
use super::fail_config;
use super::install::{Reach, load_index};
use super::install_depends::Catalog;

/// The command that reloads the shepherd onto the shep on `PATH`.
const RELOAD_COMMAND: &str = "shep daemon reload";

/// What this shep is and how it was installed, as far as upgrading it asks.
#[derive(Debug)]
pub(super) struct Host {
    /// How the running shep got here.
    pub(super) channel: Channel,
    /// Whether this is Windows, where no manager runs.
    pub(super) windows: bool,
    /// The triple the running shep was built for, which names its archive.
    pub(super) target: &'static str,
    /// The `PATH` the manager and the new `shep` are looked up on.
    pub(super) path_var: Option<OsString>,
    /// The version of the running shep.
    pub(super) running: Version,
}

impl Host {
    /// This process.
    pub(super) fn real() -> Self {
        Self {
            channel: Channel::running(),
            windows: cfg!(windows),
            target: BUILD_TARGET,
            path_var: std::env::var_os("PATH"),
            running: Version::parse(env!("CARGO_PKG_VERSION"))
                .expect("Cargo only builds a package with a semver version"),
        }
    }
}

/// Everything one bare `shep upgrade` reads.
#[derive(Debug)]
pub(super) struct Upgrade<'a> {
    pub(super) paths: &'a ShepPaths,
    pub(super) host: &'a Host,
    pub(super) reach: &'a Reach,
    pub(super) catalog: &'a Catalog<'a>,
    /// Where each adopted dog stands against the index.
    pub(super) origins: &'a Origins<'a>,
    /// The latest shep the index names, if it names one.
    pub(super) shep: Option<&'a Version>,
    /// `--reload`: reload the shepherd without asking.
    pub(super) reload: bool,
}

/// `shep upgrade` with no dog and no `--dogs`.
pub(super) async fn bare(
    streams: &mut Streams<'_>,
    paths: &ShepPaths,
    args: &UpgradeArgs,
) -> ExitCode {
    if streams.fmt == Format::Json {
        return streams.fail(
            ExitCode::Usage,
            "bare `shep upgrade` asks before it changes anything and has no JSON form; \
             `shep upgrade --dogs --format json` upgrades the dogs and reports each",
        );
    }
    let (url, loaded) = match load_index(streams, paths, args.refresh).await {
        Ok(loaded) => loaded,
        Err(code) => return code,
    };
    let rows: Vec<AvailableDog> = loaded.index.dogs.clone();
    let latest = loaded.index.shep.clone();
    let origins = Origins::over(paths, Some(loaded.index));
    let host = Host::real();
    run(
        streams,
        &mut Input::stdin(),
        &Upgrade {
            paths,
            host: &host,
            reach: &Reach::real(),
            catalog: &Catalog::new(&url, &rows),
            origins: &origins,
            shep: latest.as_ref(),
            reload: args.reload,
        },
    )
    .await
}

/// What the confirm lists.
struct Plan {
    /// The latest shep, when it is newer than the running one.
    shep: Option<Version>,
    dogs: Vec<DogStep>,
}

/// One dog the index has a newer version of.
struct DogStep {
    name: String,
    /// The installed version, `-` when nothing recorded it.
    from: String,
    to: String,
}

impl Plan {
    fn of(up: &Upgrade<'_>) -> Result<Self, ShepTomlError> {
        let cfg = ShepToml::read_only(&up.paths.daemon_config)?;
        let dogs = cfg
            .adopted_dog_names()
            .into_iter()
            .filter_map(|name| {
                let path = cfg.adopted_dog_path(&name)?;
                let origin = up.origins.of(&name, Some(&path));
                Some(DogStep {
                    from: origin.version.unwrap_or_else(|| "-".to_owned()),
                    to: origin.newer?,
                    name,
                })
            })
            .collect();
        Ok(Self {
            shep: up.shep.filter(|latest| **latest > up.host.running).cloned(),
            dogs,
        })
    }

    fn is_empty(&self) -> bool {
        self.shep.is_none() && self.dogs.is_empty()
    }

    /// One line per step: names, old versions and new versions in columns.
    fn listing(&self, host: &Host) -> String {
        let mut rows = Vec::new();
        if let Some(latest) = &self.shep {
            rows.push((
                "shep",
                host.running.to_string(),
                latest.to_string(),
                host.channel.command(),
            ));
        }
        for dog in &self.dogs {
            rows.push((dog.name.as_str(), dog.from.clone(), dog.to.clone(), None));
        }
        let name_width = rows.iter().map(|row| row.0.len()).max().unwrap_or_default();
        let from_width = rows.iter().map(|row| row.1.len()).max().unwrap_or_default();
        let mut text = String::new();
        for (name, from, to, command) in rows {
            text.push_str(&format!(
                "{name:<name_width$}  {from:<from_width$} \u{2192} {to}"
            ));
            if let Some(command) = command {
                text.push_str(&format!("   {command}"));
            }
            text.push('\n');
        }
        text
    }
}

/// Plans, confirms, upgrades shep, offers the reload, then upgrades the dogs.
/// The exit code is the first failure, or success.
pub(super) async fn run(
    streams: &mut Streams<'_>,
    input: &mut Input,
    up: &Upgrade<'_>,
) -> ExitCode {
    let plan = match Plan::of(up) {
        Ok(plan) => plan,
        Err(err) => return fail_config(streams, &err),
    };
    if plan.is_empty() {
        let _ = writeln!(streams.out, "shep and every dog are current");
        return ExitCode::Success;
    }
    let _ = write!(streams.out, "{}", plan.listing(up.host));
    let _ = write!(streams.err, "Upgrade these? [Y/n] ");
    let _ = streams.err.flush();
    match yes_by_default(input) {
        Ok(true) => {}
        Ok(false) => return ExitCode::Success,
        Err(reason) => {
            return streams.fail(
                ExitCode::Failure,
                &format!("nothing was changed: the question could not be read ({reason})"),
            );
        }
    }
    let mut first_failure = ExitCode::Success;
    if let Some(latest) = &plan.shep {
        match upgrade_shep(streams, input, up, latest).await {
            Ok(code) => first_failure = code,
            Err(code) => return code,
        }
    }
    for dog in &plan.dogs {
        let code = upgrade_dog(
            streams,
            up.paths,
            up.reach,
            input,
            up.catalog,
            &dog.name,
            &Goal::Follow,
        )
        .await;
        if first_failure == ExitCode::Success {
            first_failure = code;
        }
    }
    first_failure
}

/// Reads a line: Enter, `y` and `yes` are a yes, end of input and anything
/// else a no.
fn yes_by_default(input: &mut Input) -> Result<bool, String> {
    match input.read_line() {
        Ok(Some(line)) => Ok(matches!(
            line.trim().to_ascii_lowercase().as_str(),
            "" | "y" | "yes"
        )),
        Ok(None) => Ok(false),
        Err(err) => Err(err.to_string()),
    }
}

/// Upgrades shep itself, then offers the reload. `Err` stops the run before
/// the dogs; `Ok` carries a failure that does not.
async fn upgrade_shep(
    streams: &mut Streams<'_>,
    input: &mut Input,
    up: &Upgrade<'_>,
    latest: &Version,
) -> Result<ExitCode, ExitCode> {
    let host = up.host;
    if host.windows {
        // The running shepherd holds shep.exe, and with no `execve` a reload
        // stops and starts the flock.
        match host.channel.command() {
            Some(command) => {
                let _ = writeln!(
                    streams.out,
                    "Run `{command}` to upgrade shep. shep does not run it here: the shepherd \
                     holds shep.exe."
                );
            }
            None => print_steps(streams, host),
        }
        let _ = writeln!(
            streams.out,
            "Then run `{RELOAD_COMMAND}`. The flock restarts, because Windows cannot hand it over."
        );
        return Ok(ExitCode::Success);
    }
    let Some(command) = host.channel.command() else {
        print_steps(streams, host);
        let _ = writeln!(
            streams.out,
            "Then `{RELOAD_COMMAND}` moves the shepherd onto {latest}."
        );
        return Ok(ExitCode::Success);
    };
    run_manager(streams, host, &command).await?;
    let (new_shep, installed) = installed_shep(streams, host, &command).await?;
    Ok(reload(streams, input, up, &installed, &new_shep).await)
}

/// The by-hand steps of a channel with no command.
fn print_steps(streams: &mut Streams<'_>, host: &Host) {
    let _ = writeln!(streams.out, "To upgrade shep:");
    for (at, step) in host.channel.manual_steps(host.target).iter().enumerate() {
        let _ = writeln!(streams.out, "  {}. {step}", at + 1);
    }
}

/// Runs `command` with this process's terminal and waits for it.
async fn run_manager(
    streams: &mut Streams<'_>,
    host: &Host,
    command: &str,
) -> Result<(), ExitCode> {
    let mut words = command.split_whitespace();
    let program = words.next().unwrap_or_default();
    let Some(program) = lookup_on_path(Path::new(program), host.path_var.as_deref()) else {
        return Err(streams.fail(
            ExitCode::Failure,
            &format!("`{program}` is not on PATH; run `{command}` yourself"),
        ));
    };
    let _ = writeln!(streams.out, "Running `{command}`");
    let _ = streams.out.flush();
    match tokio::process::Command::new(&program)
        .args(words)
        .status()
        .await
    {
        Ok(status) if status.success() => Ok(()),
        Ok(status) => Err(streams.fail(
            ExitCode::Failure,
            &format!("`{command}` failed ({status}); the dogs were left alone"),
        )),
        Err(err) => Err(streams.fail(
            ExitCode::SpawnFailed,
            &format!("running {}: {err}", program.display()),
        )),
    }
}

/// The `shep` on `PATH` after the manager ran, with the version it reports,
/// once that is newer than this one.
async fn installed_shep(
    streams: &mut Streams<'_>,
    host: &Host,
    command: &str,
) -> Result<(PathBuf, Version), ExitCode> {
    let Some(found) = lookup_on_path(Path::new("shep"), host.path_var.as_deref()) else {
        return Err(streams.fail(
            ExitCode::Failure,
            &format!("`{command}` finished but there is no shep on PATH; the dogs were left alone"),
        ));
    };
    let output = tokio::process::Command::new(&found)
        .arg("--version")
        .stdin(std::process::Stdio::null())
        .output()
        .await;
    let reported = output
        .ok()
        .filter(|output| output.status.success())
        .and_then(|output| {
            String::from_utf8_lossy(&output.stdout)
                .split_whitespace()
                .find_map(|word| Version::parse(word).ok())
        });
    match reported {
        Some(version) if version > host.running => Ok((found, version)),
        Some(version) => Err(streams.fail(
            ExitCode::Failure,
            &format!(
                "`{command}` finished but the shep on PATH is still {version}: the channel has \
                 not caught up with the release yet. The dogs were left alone; try again later"
            ),
        )),
        None => Err(streams.fail(
            ExitCode::Failure,
            &format!(
                "`{command}` finished but {} did not report a version; the dogs were left alone",
                found.display()
            ),
        )),
    }
}

/// Reloads the shepherd onto `new_shep`, which reports `installed`, when one
/// answers and the operator agrees. A failed reload is the exit code but does
/// not stop the dogs.
async fn reload(
    streams: &mut Streams<'_>,
    input: &mut Input,
    up: &Upgrade<'_>,
    installed: &Version,
    new_shep: &Path,
) -> ExitCode {
    if Client::connect(&up.paths.socket).await.is_err() {
        return ExitCode::Success;
    }
    let go = if up.reload {
        true
    } else if input.is_terminal() {
        let _ = write!(
            streams.err,
            "Reload the shepherd onto {installed} now? [Y/n] "
        );
        let _ = streams.err.flush();
        yes_by_default(input).unwrap_or(false)
    } else {
        false
    };
    if !go {
        let _ = writeln!(
            streams.out,
            "The shepherd still runs the old shep. `{RELOAD_COMMAND}` moves it onto {installed}."
        );
        return ExitCode::Success;
    }
    match tokio::process::Command::new(new_shep)
        .args(["daemon", "reload"])
        .status()
        .await
    {
        Ok(status) if status.success() => ExitCode::Success,
        Ok(status) => streams.fail(
            ExitCode::Failure,
            &format!("`{RELOAD_COMMAND}` failed ({status}); run it again once the cause is fixed"),
        ),
        Err(err) => streams.fail(
            ExitCode::SpawnFailed,
            &format!("running {}: {err}", new_shep.display()),
        ),
    }
}