shep 0.25.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
//! `shep upgrade <dog>`: moves an installed dog to what its receipt says it
//! follows.
//!
//! An index install moves to the index's version and a ref install rebuilds
//! its ref at the newest commit, both through [`fetch_dog`] and
//! [`adopt_fetched`], so an upgrade is checked and recorded as an install is.
//! The directory it replaced is kept with a copy of its receipt, and the new
//! receipt names it. The one before that is removed, so at most one is kept.
//! `--rollback` is in [`super::dog_rollback`].

use std::path::Path;

use shep_core::paths::ShepPaths;

use crate::cli::{Format, InstallArgs, UpgradeArgs};
use crate::commands::shep_toml::ShepToml;
use crate::dog_index::DogSourceKind;
use crate::exit::ExitCode;
use crate::output::{DogActionStatus, SCHEMA_VERSION, Streams, write_json_line};

use super::consent::Input;
use super::dog_rollback::rollback;
use super::install::{Reach, Upgrading, adopt_fetched, fetch_dog, load_index};
use super::install_depends::Catalog;
use super::receipt::{self, HeldPin};
use super::shep_upgrade::bare;
use super::upgrade::{upgrade_notice, upgrade_one};
use super::{adopted_source, emit_dog_action, fail_config};

/// [`DogActionRow`](crate::output::DogActionRow)'s status for a dog already at
/// what it follows.
const CURRENT_STATUS: DogActionStatus =
    DogActionStatus::NoShepherd("already current; nothing changed");

/// Where an upgrade is headed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum Goal {
    /// What the receipt follows: the index's version, or the ref's newest commit.
    Follow,
    /// This ref of the row's repository.
    Ref(String),
    /// The index's version, for a dog installed from a ref.
    Release,
    /// The install the last upgrade replaced.
    Rollback,
}

/// `shep upgrade [<dog>]`.
pub async fn upgrade(streams: &mut Streams<'_>, paths: &ShepPaths, args: &UpgradeArgs) -> ExitCode {
    let goal = match (&args.git_ref, args.release, args.rollback) {
        (Some(git_ref), _, _) => Goal::Ref(git_ref.clone()),
        (None, true, _) => Goal::Release,
        (None, false, true) => Goal::Rollback,
        (None, false, false) => Goal::Follow,
    };
    if args.dog.is_none() && !args.all {
        return bare(streams, paths, args).await;
    }
    // A rollback reads no index: nothing it needs is on the network.
    let (url, rows) = if goal == Goal::Rollback {
        (String::new(), Vec::new())
    } else {
        match load_index(streams, paths, args.refresh).await {
            Ok((url, loaded)) => (url, loaded.index.dogs),
            Err(code) => return code,
        }
    };
    let catalog = Catalog::new(&url, &rows);
    let reach = Reach::real();
    let mut input = Input::stdin();
    if let Some(name) = &args.dog {
        return upgrade_dog(streams, paths, &reach, &mut input, &catalog, name, &goal).await;
    }
    upgrade_all(streams, paths, &reach, &mut input, &catalog).await
}

/// `--dogs`: every adopted dog with a receipt, in turn. One that fails does
/// not stop the rest, and the first failure is the exit code.
///
/// With `--format json` each dog's reply is held back and the rows leave as
/// the `data` array of one document.
pub(super) async fn upgrade_all(
    streams: &mut Streams<'_>,
    paths: &ShepPaths,
    reach: &Reach,
    input: &mut Input,
    catalog: &Catalog<'_>,
) -> ExitCode {
    let cfg = match ShepToml::read_only(&paths.daemon_config) {
        Ok(cfg) => cfg,
        Err(err) => return fail_config(streams, &err),
    };
    let json = streams.fmt == Format::Json;
    let mut rows = Vec::new();
    let mut first_failure = ExitCode::Success;
    let mut upgraded = 0;
    for name in cfg.adopted_dog_names() {
        // An unreadable receipt is not skipped: the upgrade reports it.
        if matches!(receipt::read(paths, &name), Ok(None)) {
            streams.aside(
                "upgrade",
                &format!("skipping {name}: it has no receipt, so `shep adopt` put it there"),
            );
            continue;
        }
        upgraded += 1;
        let code = if json {
            let mut held = Vec::new();
            let mut quiet = Streams {
                out: &mut held,
                err: &mut *streams.err,
                style: streams.style,
                fmt: streams.fmt,
            };
            let code = upgrade_dog(
                &mut quiet,
                paths,
                reach,
                input,
                catalog,
                &name,
                &Goal::Follow,
            )
            .await;
            rows.extend(replies_in(&held));
            code
        } else {
            upgrade_dog(streams, paths, reach, input, catalog, &name, &Goal::Follow).await
        };
        if first_failure == ExitCode::Success {
            first_failure = code;
        }
    }
    if upgraded == 0 {
        streams.aside("upgrade", "no installed dog to upgrade");
    }
    if json {
        let document = serde_json::json!({
            "schema_version": SCHEMA_VERSION,
            "command": "upgrade",
            "data": rows,
        });
        if write_json_line(&mut *streams.out, &document).is_err()
            && first_failure == ExitCode::Success
        {
            first_failure = ExitCode::Failure;
        }
    }
    first_failure
}

/// The `data` of each envelope line in `held`, one dog's reply.
fn replies_in(held: &[u8]) -> Vec<serde_json::Value> {
    held.split(|byte| *byte == b'\n')
        .filter_map(|line| serde_json::from_slice::<serde_json::Value>(line).ok())
        .filter_map(|mut envelope| envelope.get_mut("data").map(serde_json::Value::take))
        .collect()
}

/// Upgrades the one dog adopted as `name` towards `goal`.
pub(super) async fn upgrade_dog(
    streams: &mut Streams<'_>,
    paths: &ShepPaths,
    reach: &Reach,
    input: &mut Input,
    catalog: &Catalog<'_>,
    name: &str,
    goal: &Goal,
) -> ExitCode {
    let cfg = match ShepToml::read_only(&paths.daemon_config) {
        Ok(cfg) => cfg,
        Err(err) => return fail_config(streams, &err),
    };
    if cfg.adopted_dog_path(name).is_none() {
        return if crate::dog::BUILT_IN_DOGS.contains(&name) {
            streams.fail(
                ExitCode::Failure,
                &format!("`{name}` is built in to shep and upgrades with it"),
            )
        } else {
            streams.fail(
                ExitCode::NotFound,
                &format!("`{name}` is not an adopted dog; `shep dogs` lists them"),
            )
        };
    }
    let held = match receipt::read(paths, name) {
        Ok(Some(held)) => held,
        Ok(None) => {
            return streams.fail(
                ExitCode::Failure,
                &format!(
                    "`{name}` has no receipt, so shep did not install it: it came from `shep \
                     adopt <path>`. `shep upgrade` follows what `shep install` put on disk. \
                     Rebuild it and `shep adopt` it again, or `shep install {name}` to take it \
                     from the index"
                ),
            );
        }
        Err(err) => return fail_receipt(streams, paths, name, &err),
    };
    let enabled = cfg.enabled_dog_names().iter().any(|dog| dog == name);
    if *goal == Goal::Rollback {
        return rollback(streams, paths, reach, input, name, &held, enabled).await;
    }

    let Some(row) = catalog.row(name) else {
        return streams.fail(
            ExitCode::NotFound,
            &format!(
                "the dog index has no dog called `{name}` now, so there is nothing to upgrade it \
                 to; `--rollback` still works"
            ),
        );
    };
    // What to build: a ref, or the index's version. A ref install follows its ref.
    let git_ref = match (goal, &held.pinned) {
        (Goal::Ref(git_ref), _) => Some(git_ref.clone()),
        (Goal::Follow, HeldPin::Ref { git_ref, .. }) => Some(git_ref.clone()),
        _ => None,
    };
    if git_ref.is_none()
        && let (
            DogSourceKind::Cargo {
                version: Some(approved),
                ..
            },
            HeldPin::Version(held_version),
        ) = (&row.source, &held.pinned)
        && approved == held_version
    {
        return current(streams, &cfg, name, &held.pinned);
    }

    let install_args = InstallArgs {
        dog: Some(name.to_owned()),
        yes: false,
        no_enable: false,
        refresh: false,
        cargo: false,
        git_ref: None,
    };
    let mut fetched = match fetch_dog(
        streams,
        paths,
        &install_args,
        reach,
        row,
        git_ref.as_deref(),
    )
    .await
    {
        Ok(fetched) => fetched,
        Err(code) => return code,
    };
    // The lock is held now: what is on disk is what this upgrade replaces.
    let held = match receipt::read(paths, name) {
        Ok(Some(held)) => held,
        Ok(None) => {
            return streams.fail(
                ExitCode::Failure,
                &format!("`{name}` lost its receipt while it was being upgraded"),
            );
        }
        Err(err) => return fail_receipt(streams, paths, name, &err),
    };
    let lands = fetched.lands_as();
    if lands == held.pinned {
        return current(streams, &cfg, name, &held.pinned);
    }
    let new_root = receipt::root_of(fetched.binary()).map(Path::to_path_buf);
    let old_root = held.root().map(Path::to_path_buf);
    // A ref switched to a name for the commit it already runs lands in the
    // directory it is in: nothing is replaced, and what it kept stays kept.
    let same_root = new_root == old_root;
    let previous = if same_root {
        held.previous.clone()
    } else {
        old_root
            .clone()
            .filter(|root| receipt::is_install_dir(paths, name, root))
    };
    if !same_root
        && let Some(root) = &previous
        && let Err(err) =
            receipt::write_document(&root.join("receipt.json"), &held.with_previous(None))
    {
        return streams.fail(
            ExitCode::Failure,
            &format!(
                "keeping the receipt of the install it replaces in {}: {err}",
                root.display()
            ),
        );
    }
    if fetched.built_by_cargo()
        && let (HeldPin::Version(old), HeldPin::Version(new)) = (&held.pinned, &lands)
    {
        streams.aside(
            "upgrade_diff",
            &format!("what changed: https://diff.rs/{}/{old}/{new}", row.package),
        );
    }
    fetched.upgrading = Some(Upgrading {
        previous,
        enable: enabled,
    });
    let before = waiting_of(paths, name);
    let mut said_no = false;
    let code = adopt_fetched(
        streams,
        paths,
        &install_args,
        input,
        fetched,
        catalog.url(),
        &mut said_no,
    )
    .await;
    if code != ExitCode::Success {
        return code;
    }
    // The install before the replaced one is no longer kept.
    if let (Some(older), Some(new_root)) = (&held.previous, &new_root)
        && !same_root
        && Some(older) != old_root.as_ref()
        && older != new_root
        && receipt::is_install_dir(paths, name, older)
    {
        let _ = std::fs::remove_dir_all(older);
    }
    streams.aside(
        "upgrade",
        &format!(
            "upgraded {name} from {} to {}",
            describe(&held.pinned),
            describe(&lands)
        ),
    );
    report_waiting(streams, paths, name, &before);
    ExitCode::Success
}

/// The reply for a dog that is already at what it follows.
fn current(streams: &mut Streams<'_>, cfg: &ShepToml, name: &str, at: &HeldPin) -> ExitCode {
    streams.aside(
        "upgrade",
        &format!("{name} is already at {}; nothing to do", describe(at)),
    );
    emit_dog_action(
        streams,
        "upgrade",
        name,
        adopted_source(cfg, name, None),
        CURRENT_STATUS,
    )
}

/// A version, or a ref and the commit it was built at.
pub(super) fn describe(pinned: &HeldPin) -> String {
    match pinned {
        HeldPin::Version(version) => version.clone(),
        HeldPin::Ref { git_ref, commit } => {
            format!("{git_ref} at {}", commit.get(..12).unwrap_or(commit))
        }
    }
}

/// The permissions `name`'s record holds waiting.
pub(super) fn waiting_of(paths: &ShepPaths, name: &str) -> Vec<String> {
    ShepToml::read_only(&paths.daemon_config)
        .ok()
        .and_then(|cfg| cfg.grant_record(name).ok().flatten())
        .map(|record| record.waiting.names().map(str::to_owned).collect())
        .unwrap_or_default()
}

/// Puts a permission the new build declares in `waiting` and says so. The dog
/// has been restarted on the grants it already held.
pub(super) fn report_waiting(
    streams: &mut Streams<'_>,
    paths: &ShepPaths,
    name: &str,
    before: &[String],
) {
    match upgrade_one(paths, name) {
        Ok(true) => {
            let now = waiting_of(paths, name);
            let new: Vec<_> = now
                .iter()
                .filter(|p| !before.contains(p))
                .cloned()
                .collect();
            let detail = if new.is_empty() {
                String::new()
            } else {
                format!(" ({} waiting)", new.join(", "))
            };
            streams.aside(
                "upgrade_waiting",
                &format!("{}{detail}", upgrade_notice(&[name.to_owned()])),
            );
        }
        Ok(false) => {}
        Err(err) => {
            let _ = fail_config(streams, &err);
        }
    }
}

/// The refusal for a receipt that is there and does not read.
pub(super) fn fail_receipt(
    streams: &mut Streams<'_>,
    paths: &ShepPaths,
    name: &str,
    err: &receipt::HeldError,
) -> ExitCode {
    streams.fail(
        ExitCode::Failure,
        &format!(
            "reading {}: {err}",
            receipt::receipt_path(paths, name).display()
        ),
    )
}