aboutsummaryrefslogtreecommitdiffstats
path: root/pkgs/populate/src/main.rs
blob: 17d9678746625d6ae55f6b89e91fd327992b1c5c (plain)
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
//! populate SPEC: delivers sources to a target directory, as the spec, a
//! JSON file or - for standard input, says.  See docs/design.md.

mod check;
mod flake;
mod flake_input;
mod populate;
mod rsync;
mod run;
mod sh;
mod spec;

use std::io::Read;
use std::process::ExitCode;

/// Exit status when the spec can't be read, isn't JSON, or isn't a spec.
const USAGE: u8 = 2;

fn main() -> ExitCode {
    let args: Vec<String> = std::env::args().skip(1).collect();
    let [path] = args.as_slice() else {
        eprintln!("usage: populate SPEC");
        return ExitCode::from(USAGE);
    };
    let text = if path == "-" {
        let mut text = String::new();
        std::io::stdin().read_to_string(&mut text).map(|_| text)
    } else {
        std::fs::read_to_string(path)
    };
    let text = match text {
        Ok(text) => text,
        Err(e) => {
            eprintln!("populate: can't read {path}: {e}");
            return ExitCode::from(USAGE);
        }
    };
    let version = serde_json::from_str::<serde_json::Value>(&text)
        .ok()
        .and_then(|value| value.get("version").and_then(|v| v.as_u64()));
    if let Some(version) = version.filter(|v| *v != spec::VERSION) {
        eprintln!(
            "populate: {path} is a spec of version {version}, this populate reads version {}",
            spec::VERSION
        );
        return ExitCode::from(USAGE);
    }
    let spec: spec::Spec = match serde_json::from_str(&text) {
        Ok(spec) => spec,
        Err(e) => {
            eprintln!("populate: {path} isn't a spec: {e}");
            return ExitCode::from(USAGE);
        }
    };
    if let Err(message) = check::spec(&spec) {
        eprintln!("{message}");
        return ExitCode::FAILURE;
    }
    run::trap_signals();
    let context = match run::Context::new(spec.target.clone(), spec.target.local) {
        Ok(context) => context,
        Err(failure) => return exit(failure),
    };
    let result = populate::populate(&context, &spec);
    run::ignore_signals();
    context.clean_up();
    match result {
        Ok(()) => ExitCode::SUCCESS,
        Err(failure) => exit(failure),
    }
}

/// Says why populate fails, unless a command did, and returns the exit
/// status for that.
fn exit(failure: run::Failure) -> ExitCode {
    match failure {
        run::Failure::Message(message) => {
            eprintln!("{message}");
            ExitCode::FAILURE
        }
        run::Failure::Command => ExitCode::FAILURE,
        run::Failure::Signal(signal) => ExitCode::from(128 + signal as u8),
    }
}