diff options
Diffstat (limited to 'pkgs/populate')
| -rw-r--r-- | pkgs/populate/README.md | 29 | ||||
| -rw-r--r-- | pkgs/populate/src/cli.rs | 321 | ||||
| -rw-r--r-- | pkgs/populate/src/main.rs | 24 | ||||
| -rw-r--r-- | pkgs/populate/src/shell.rs | 72 |
4 files changed, 379 insertions, 67 deletions
diff --git a/pkgs/populate/README.md b/pkgs/populate/README.md index e85b502..e0015fa 100644 --- a/pkgs/populate/README.md +++ b/pkgs/populate/README.md @@ -86,6 +86,35 @@ Exit status: or aren't sources. - 129, 130, 143: populate got SIGHUP, SIGINT, or SIGTERM, and stopped. +### populate shell + +``` +populate shell [OPTION]... TARGET SCRIPT +``` + +`populate shell` runs the shell code `SCRIPT` with `/bin/sh` on `TARGET`, +reached like populate reaches it: directly if it's local, else via ssh. +`SCRIPT` gets `local` or `remote` as `$1`, telling which, e.g. for using +something on the local machine. `TARGET`'s path is unused. krops runs +`nixos-rebuild` on targets with it. + +| Option | Meaning | +|-------------------|---------------------------------------------------------| +| `--sudo` | Run `SCRIPT` as root, via sudo on the target. | +| `--ssh-arg ARG` | Pass `ARG` to ssh; repeatable. | +| `--user USER` | The target's user; empty for ssh's default. | +| `--host HOST` | The target's host. | +| `--port PORT` | The port ssh connects to. | +| `--local` | The target is the machine populate runs on. | +| `--remote` | The target isn't, even if it looks so. | +| `--tty` | Give `SCRIPT` a terminal, if the target is remote. | +| `--local-only` | Fail, without running `SCRIPT`, unless it's local. | +| `-h`, `--help` | Print the usage and exit. | + +The exit status is `SCRIPT`'s, or ssh's, if ssh fails, 1 if +`--local-only` fails, and 2 if the command line is wrong. A file of +sources named `shell` needs another name for populate, e.g. `./shell`. + ## Sources diff --git a/pkgs/populate/src/cli.rs b/pkgs/populate/src/cli.rs index c059c0f..9f76ba8 100644 --- a/pkgs/populate/src/cli.rs +++ b/pkgs/populate/src/cli.rs @@ -5,9 +5,11 @@ use crate::spec::TargetParts; /// What the command line asks for. #[derive(Debug, PartialEq)] pub enum Command { - Help, + /// Printing a usage, USAGE or SHELL_USAGE. + Help(&'static str), Version, Populate(Options), + Shell(ShellOptions), } /// The arguments of populating. @@ -27,8 +29,27 @@ pub struct Options { pub local: Option<bool>, } +/// The arguments of populate shell. +#[derive(Debug, Default, PartialEq)] +pub struct ShellOptions { + /// The target, as given, with the options changing its parts applied. + pub target: TargetParts, + pub sudo: bool, + pub ssh_args: Vec<String>, + /// Whether the target is the machine populate runs on, if --local or + /// --remote says so. + pub local: Option<bool>, + /// Whether the script gets a terminal on a remote target. + pub tty: bool, + /// Whether to fail unless the target is local. + pub local_only: bool, + /// The shell code to run. + pub script: String, +} + pub const USAGE: &str = "\ usage: populate [OPTION]... SOURCES [TARGET] + populate shell [OPTION]... TARGET SCRIPT Delivers the sources in the file SOURCES, a JSON object, or standard input if SOURCES is -, to the target directory TARGET. @@ -52,85 +73,218 @@ Options: --remote the target isn't, even if it looks so -h, --help print this and exit -V, --version print populate's version and exit + +See populate shell --help for populate shell. "; -/// The command line, without the program's name. Options and the other -/// arguments may come in any order, up to --. -pub fn parse(args: &[String]) -> Result<Command, String> { - let mut options = Options::default(); - let mut positional: Vec<String> = Vec::new(); - let mut overrides: Vec<(&'static str, String)> = Vec::new(); +pub const SHELL_USAGE: &str = "\ +usage: populate shell [OPTION]... TARGET SCRIPT + +Runs the shell code SCRIPT with /bin/sh on TARGET, reached like populate +reaches it, with local or remote as $1, telling whether TARGET is local. +TARGET is like populate's, with its path left unused. The exit status is +SCRIPT's, or ssh's if ssh fails. + +Options: + --sudo run SCRIPT as root, via sudo on the target + --ssh-arg ARG pass ARG to ssh; repeatable + --user USER the target's user; empty for ssh's default + --host HOST the target's host + --port PORT the port ssh connects to + --local the target is the machine populate runs on + --remote the target isn't, even if it looks so + --tty give SCRIPT a terminal, if the target is remote + --local-only fail, without running SCRIPT, unless the target is local + -h, --help print this and exit +"; + +/// What the options and arguments common to populate and populate shell +/// say. +#[derive(Default)] +struct Parsed { + /// The flags given, among those the command takes. + flags: Vec<&'static str>, + ssh_args: Vec<String>, + /// --user, --host, --port, and --path, in order. + overrides: Vec<(&'static str, String)>, + positional: Vec<String>, + help: bool, + version: bool, +} + +/// Parses args, with the flags among flags, and the options with an +/// argument among options. Options and the other arguments may come in any +/// order, up to --. +fn parse_args( + args: &[String], + flags: &[&'static str], + options: &[&'static str], +) -> Result<Parsed, String> { + let mut parsed = Parsed::default(); let mut args = args.iter(); while let Some(arg) = args.next() { if arg == "--" { - positional.extend(args.by_ref().cloned()); + parsed.positional.extend(args.by_ref().cloned()); break; } if arg == "-" || !arg.starts_with('-') { - positional.push(arg.clone()); + parsed.positional.push(arg.clone()); continue; } let (name, inline) = match arg.split_once('=') { Some((name, value)) if name.starts_with("--") => (name, Some(value.to_string())), _ => (arg.as_str(), None), }; - let mut value = |name: &str| -> Result<String, String> { - match &inline { - Some(value) => Ok(value.clone()), - None => args - .next() - .cloned() - .ok_or_else(|| format!("option {name} needs an argument")), + if let Some(flag) = flags.iter().find(|f| **f == name) { + if inline.is_some() { + return Err(format!("option {name} takes no argument")); } + match *flag { + "-h" | "--help" => parsed.help = true, + "-V" | "--version" => parsed.version = true, + flag => parsed.flags.push(flag), + } + if parsed.help || parsed.version { + return Ok(parsed); + } + continue; + } + let Some(option) = options.iter().find(|o| **o == name) else { + return Err(format!("unknown option {name}")); + }; + let value = match inline { + Some(value) => value, + None => args + .next() + .cloned() + .ok_or_else(|| format!("option {name} needs an argument"))?, }; - match name { - "-h" | "--help" => return Ok(Command::Help), - "-V" | "--version" => return Ok(Command::Version), - "--backup" => options.backup = true, - "--force" => options.force = true, - "--prune" => options.prune = true, - "--sudo" => options.sudo = true, - "--local" => options.local = Some(true), - "--remote" => options.local = Some(false), - "--ssh-arg" => options.ssh_args.push(value(name)?), - "--user" => overrides.push(("user", value(name)?)), - "--host" => overrides.push(("host", value(name)?)), - "--port" => overrides.push(("port", value(name)?)), - "--path" => overrides.push(("path", value(name)?)), - _ => return Err(format!("unknown option {name}")), + match *option { + "--ssh-arg" => parsed.ssh_args.push(value), + option => parsed + .overrides + .push((option.trim_start_matches("--"), value)), } - if inline.is_some() - && matches!( - name, - "--backup" | "--force" | "--prune" | "--sudo" | "--local" | "--remote" - ) - { - return Err(format!("option {name} takes no argument")); + } + Ok(parsed) +} + +impl Parsed { + fn has(&self, flag: &str) -> bool { + self.flags.contains(&flag) + } + + /// Whether --local or --remote says the target is local, the last of + /// them winning. + fn local(&self) -> Option<bool> { + self.flags.iter().rev().find_map(|flag| match *flag { + "--local" => Some(true), + "--remote" => Some(false), + _ => None, + }) + } + + /// The target text, with the options changing its parts applied. + fn target(&self, text: &str) -> Result<TargetParts, String> { + let mut target = TargetParts::parse(text)?; + for (part, value) in &self.overrides { + let value = Some(value.clone()); + match *part { + "user" => target.user = value, + "host" => target.host = value, + "port" => target.port = value, + _ => target.path = value, + } + } + if let Some(path) = &target.path { + if path.is_empty() { + return Err("the target's path is empty".to_string()); + } } + Ok(target) } - let (sources, target) = match positional.as_slice() { +} + +/// The command line, without the program's name. +pub fn parse(args: &[String]) -> Result<Command, String> { + match args.split_first() { + Some((first, rest)) if first == "shell" => parse_shell(rest), + _ => parse_populate(args), + } +} + +fn parse_populate(args: &[String]) -> Result<Command, String> { + let parsed = parse_args( + args, + &[ + "-h", + "--help", + "-V", + "--version", + "--backup", + "--force", + "--prune", + "--sudo", + "--local", + "--remote", + ], + &["--ssh-arg", "--user", "--host", "--port", "--path"], + )?; + if parsed.help { + return Ok(Command::Help(USAGE)); + } + if parsed.version { + return Ok(Command::Version); + } + let (sources, target) = match parsed.positional.as_slice() { [sources] => (sources.clone(), String::new()), [sources, target] => (sources.clone(), target.clone()), [] => return Err("SOURCES is missing".to_string()), _ => return Err("too many arguments".to_string()), }; - options.sources = sources; - options.target = TargetParts::parse(&target)?; - for (part, value) in overrides { - let target = &mut options.target; - match part { - "user" => target.user = Some(value), - "host" => target.host = Some(value), - "port" => target.port = Some(value), - _ => target.path = Some(value), - } - } - if let Some(path) = &options.target.path { - if path.is_empty() { - return Err("the target's path is empty".to_string()); - } + Ok(Command::Populate(Options { + backup: parsed.has("--backup"), + force: parsed.has("--force"), + prune: parsed.has("--prune"), + sources, + target: parsed.target(&target)?, + sudo: parsed.has("--sudo"), + local: parsed.local(), + ssh_args: parsed.ssh_args, + })) +} + +fn parse_shell(args: &[String]) -> Result<Command, String> { + let parsed = parse_args( + args, + &[ + "-h", + "--help", + "--sudo", + "--local", + "--remote", + "--tty", + "--local-only", + ], + &["--ssh-arg", "--user", "--host", "--port"], + )?; + if parsed.help { + return Ok(Command::Help(SHELL_USAGE)); } - Ok(Command::Populate(options)) + let (target, script) = match parsed.positional.as_slice() { + [target, script] => (target.clone(), script.clone()), + [] | [_] => return Err("shell: TARGET and SCRIPT are missing".to_string()), + _ => return Err("shell: too many arguments".to_string()), + }; + Ok(Command::Shell(ShellOptions { + target: parsed.target(&target)?, + sudo: parsed.has("--sudo"), + local: parsed.local(), + tty: parsed.has("--tty"), + local_only: parsed.has("--local-only"), + script, + ssh_args: parsed.ssh_args, + })) } #[cfg(test)] @@ -187,9 +341,64 @@ mod tests { assert_eq!(options(&["--", "--sources"]).sources, "--sources"); } + fn shell_options(args: &[&str]) -> ShellOptions { + match parse(args) { + Ok(Command::Shell(options)) => options, + other => panic!("{other:?}"), + } + } + + #[test] + fn shell() { + let o = shell_options(&[ + "shell", + "--sudo", + "--tty", + "--ssh-arg=-v", + "--port", + "22", + "root@host", + "echo $1", + ]); + assert!(o.sudo && o.tty && !o.local_only); + assert_eq!(o.ssh_args, ["-v"]); + assert_eq!(o.target.user.as_deref(), Some("root")); + assert_eq!(o.target.port.as_deref(), Some("22")); + assert_eq!(o.script, "echo $1"); + assert_eq!(o.local, None); + let o = shell_options(&[ + "shell", + "--local", + "--remote", + "--local-only", + "", + "--", + "-x", + ]); + assert_eq!(o.local, Some(false)); + assert!(o.local_only); + assert_eq!(o.target, TargetParts::default()); + assert_eq!(o.script, "-x"); + assert_eq!(parse(&["shell", "-h"]), Ok(Command::Help(SHELL_USAGE))); + assert_eq!( + parse(&["shell", "x"]), + Err("shell: TARGET and SCRIPT are missing".to_string()) + ); + assert_eq!( + parse(&["shell", "--backup", "x", "y"]), + Err("unknown option --backup".to_string()) + ); + assert_eq!( + parse(&["shell", "--path", "/x", "x", "y"]), + Err("unknown option --path".to_string()) + ); + // A file named shell is ./shell. + assert_eq!(options(&["./shell"]).sources, "./shell"); + } + #[test] fn errors() { - assert_eq!(parse(&["--help", "--bogus"]), Ok(Command::Help)); + assert_eq!(parse(&["--help", "--bogus"]), Ok(Command::Help(USAGE))); assert_eq!( parse(&["--bogus"]), Err("unknown option --bogus".to_string()) diff --git a/pkgs/populate/src/main.rs b/pkgs/populate/src/main.rs index eeed1ef..684c515 100644 --- a/pkgs/populate/src/main.rs +++ b/pkgs/populate/src/main.rs @@ -1,6 +1,7 @@ //! populate [OPTION]... SOURCES [TARGET]: delivers the sources in the JSON //! file SOURCES, or standard input for -, to the target directory TARGET. -//! See README.md. +//! populate shell [OPTION]... TARGET SCRIPT runs the shell code SCRIPT on +//! TARGET. See README.md. mod check; mod cli; @@ -10,6 +11,7 @@ mod populate; mod rsync; mod run; mod sh; +mod shell; mod spec; use std::io::Read; @@ -22,8 +24,8 @@ const USAGE: u8 = 2; fn main() -> ExitCode { let args: Vec<String> = std::env::args().skip(1).collect(); let options = match cli::parse(&args) { - Ok(cli::Command::Help) => { - print!("{}", cli::USAGE); + Ok(cli::Command::Help(usage)) => { + print!("{usage}"); return ExitCode::SUCCESS; } Ok(cli::Command::Version) => { @@ -31,16 +33,16 @@ fn main() -> ExitCode { return ExitCode::SUCCESS; } Ok(cli::Command::Populate(options)) => options, + Ok(cli::Command::Shell(options)) => return shell::shell(options), Err(message) => { + // The usage lines of the command the arguments are for. + let usage = if args.first().map(String::as_str) == Some("shell") { + cli::SHELL_USAGE.lines().take(1).collect::<Vec<_>>() + } else { + cli::USAGE.lines().take(2).collect::<Vec<_>>() + }; eprintln!("populate: {message}"); - eprint!( - "{}", - cli::USAGE - .lines() - .next() - .map(|l| format!("{l}\n")) - .unwrap_or_default() - ); + eprintln!("{}", usage.join("\n")); return ExitCode::from(USAGE); } }; diff --git a/pkgs/populate/src/shell.rs b/pkgs/populate/src/shell.rs new file mode 100644 index 0000000..befd4aa --- /dev/null +++ b/pkgs/populate/src/shell.rs @@ -0,0 +1,72 @@ +//! populate shell: runs shell code on a target, reached like populate +//! reaches it. + +use crate::cli::ShellOptions; +use crate::run::{self, Origin}; +use std::os::unix::process::CommandExt; +use std::process::{Command, ExitCode}; + +/// Runs the script as the options say, replacing populate, so the script's +/// exit status, terminal, and signals are populate's. Returns only if +/// that fails. +pub fn shell(options: ShellOptions) -> ExitCode { + let origin = Origin::from_env(); + let target = options + .target + .complete(&origin, options.sudo, options.ssh_args); + let local = options.local.unwrap_or_else(|| origin.is_local(&target)); + if options.local_only && !local { + let user = target + .user + .as_deref() + .map(|user| format!("{user}@")) + .unwrap_or_default(); + eprintln!( + "populate: shell: {user}{} is not the machine populate runs on", + target.host + ); + return ExitCode::FAILURE; + } + let mut words: Vec<String> = Vec::new(); + if target.sudo { + words.push("sudo".to_string()); + } + words.extend([ + "/bin/sh".to_string(), + "-c".to_string(), + options.script, + "sh".to_string(), + if local { "local" } else { "remote" }.to_string(), + ]); + let mut command = if local { + let mut command = Command::new(&words[0]); + command.args(&words[1..]); + command + } else { + let mut command = Command::new("ssh"); + if let Some(user) = &target.user { + command.args(["-l", user]); + } + if let Some(port) = &target.port { + command.args(["-p", port]); + } + command + .arg(if options.tty { "-t" } else { "-T" }) + .args(&target.extra_options) + .arg(&target.host) + .arg( + words + .iter() + .map(|word| run::quote(word)) + .collect::<Vec<_>>() + .join(" "), + ); + command + }; + let error = command.exec(); + eprintln!( + "populate: shell: can't run {}: {error}", + command.get_program().to_string_lossy() + ); + ExitCode::from(127) +} |
