Skip to content
1        10        20        30        40        50        60        70        80        90        100       110       120       130       1401use std::{2    collections::HashMap,3    error::Error,4    fs,5    io::{self, BufRead, IsTerminal, Read, Write},6    net::ToSocketAddrs,7    path::{Path, PathBuf},8    process::{Command, Stdio},9    time::Duration,10};1112use crate::commands::{13    new::Bump,14    progress,15    release::{self, DeployAction, DeploymentTarget},16};1718/// How `ino once remote create` gets its answers. Without options it asks on19/// the terminal. A scripted run, such as the Ino console's, passes them instead.20#[derive(Debug, Default)]21pub struct CreateOptions {22    /// `KEY=VALUE` lines for the app's environment. `-` reads them from stdin.23    pub env_file: Option<PathBuf>,24    /// Skip the confirmation prompts.25    pub yes: bool,26}2728pub fn create(options: &CreateOptions) -> Result<(), Box<dyn Error>> {29    let (remote, target) = read_deployment()?;30    let api_key = read_api_key()?;31    let scripted = options.yes || options.env_file.is_some();3233    let runtime = tokio::runtime::Builder::new_current_thread()34        .enable_all()35        .build()?;36    let client = reqwest::Client::builder()37        .timeout(Duration::from_secs(30))38        .build()?;39    let hosts = runtime.block_on(release::deployed_hosts(&client, &target, &api_key))?;40    if hosts.contains(&target.host) {41        return Err(format!(42            "app {} already exists on {}; release with `ino` to update it",43            target.host, target.server44        )45        .into());46    }4748    if !host_resolves(&target.host) {49        let warning = format!(50            "{} does not resolve yet, so the first health check will likely fail and roll back.",51            target.host52        );53        if scripted {54            progress::notice(&warning);55        } else if !confirm(&format!("{warning} Continue? [y/N] "))? {56            return Err("app creation cancelled".into());57        }58    }5960    let env = match &options.env_file {61        Some(path) => read_environment_file(path)?,62        None if scripted => HashMap::new(),63        None => read_environment()?,64    };65    let mut names = env.keys().cloned().collect::<Vec<_>>();66    names.sort();67    let environment = if names.is_empty() {68        "none".to_owned()69    } else {70        names.join(", ")71    };72    if !options.yes73        && !confirm(&format!(74            "Release {remote} and create {} on {} with environment variables: {environment}? This commits and pushes Git and the image. [y/N] ",75            target.host, target.server76        ))?77    {78        return Err("app creation cancelled".into());79    }8081    release::run_release(Bump::Auto, &DeployAction::Create { api_key, env })82}8384/// Reads `KEY=VALUE` lines from `path`, or from stdin when `path` is `-`.85/// Blank lines and lines starting with `#` are skipped. Error messages name86/// the line but never its value, since values are secrets.87fn read_environment_file(path: &Path) -> Result<HashMap<String, String>, Box<dyn Error>> {88    let text = if path == Path::new("-") {89        let mut text = String::new();90        io::stdin().lock().read_to_string(&mut text)?;91        text92    } else {93        fs::read_to_string(path)94            .map_err(|error| format!("reading environment file {}: {error}", path.display()))?95    };96    parse_environment(&text)97}9899fn parse_environment(text: &str) -> Result<HashMap<String, String>, Box<dyn Error>> {100    let mut env = HashMap::new();101    for (index, line) in text.lines().enumerate() {102        let line = line.trim();103        if line.is_empty() || line.starts_with('#') {104            continue;105        }106        match line.split_once('=') {107            Some((key, value)) if !key.trim().is_empty() => {108                env.insert(key.trim().to_owned(), value.trim().to_owned());109            }110            _ => {111                return Err(112                    format!("environment file line {} must be KEY=VALUE", index + 1).into(),113                );114            }115        }116    }117    Ok(env)118}119120fn read_deployment() -> Result<(String, DeploymentTarget), Box<dyn Error>> {121    let dockerfile =122        fs::read_to_string("Dockerfile").map_err(|error| format!("reading Dockerfile: {error}"))?;123    let metadata = release::parse_image_metadata(&dockerfile)?;124    let target = metadata.deployment.ok_or(125        "Dockerfile must declare ino.deploy.server and ino.deploy.host labels for a remote app",126    )?;127    Ok((metadata.remote, target))128}129130pub(super) fn read_api_key() -> Result<String, Box<dyn Error>> {131    if let Some(key) = std::env::var("INO_API_KEY")132        .ok()133        .filter(|key| !key.is_empty())134    {135        return Ok(key);136    }137    let key = read_secret("Ino server API key: ")?;138    if key.is_empty() {139        return Err("an Ino server API key is required".into());140    }141    Ok(key)142}143144fn read_environment() -> io::Result<HashMap<String, String>> {145    println!("App environment variables as KEY=VALUE, one per line. Enter a blank line to finish.");146    let mut env = HashMap::new();147    loop {148        let line = read_line("env> ")?;149        if line.is_empty() {150            return Ok(env);151        }152        match line.split_once('=') {153            Some((key, value)) if !key.trim().is_empty() => {154                env.insert(key.trim().to_owned(), value.trim().to_owned());155            }156            _ => println!("expected KEY=VALUE"),157        }158    }159}160161fn host_resolves(host: &str) -> bool {162    (host, 443)163        .to_socket_addrs()164        .is_ok_and(|mut addresses| addresses.next().is_some())165}166167fn read_line(prompt: &str) -> io::Result<String> {168    print!("{prompt}");169    io::stdout().flush()?;170    let mut answer = String::new();171    io::stdin().lock().read_line(&mut answer)?;172    Ok(answer.trim().to_owned())173}174175fn read_secret(prompt: &str) -> io::Result<String> {176    print!("{prompt}");177    io::stdout().flush()?;178    let hidden = io::stdin().is_terminal() && set_echo(false);179    let mut answer = String::new();180    let result = io::stdin().lock().read_line(&mut answer);181    if hidden {182        set_echo(true);183        println!();184    }185    result?;186    Ok(answer.trim().to_owned())187}188189fn set_echo(enabled: bool) -> bool {190    Command::new("stty")191        .arg(if enabled { "echo" } else { "-echo" })192        .stdin(Stdio::inherit())193        .status()194        .is_ok_and(|status| status.success())195}196197fn confirm(prompt: &str) -> io::Result<bool> {198    let answer = read_line(prompt)?;199    Ok(matches!(answer.to_ascii_lowercase().as_str(), "y" | "yes"))200}201202#[cfg(test)]203mod tests {204    use super::parse_environment;205206    #[test]207    fn reads_key_value_lines_and_skips_blanks_and_comments() {208        let env = parse_environment("# note\n\nRAILS_ENV = production\nTOKEN=a=b\n").unwrap();209        assert_eq!(env.get("RAILS_ENV").map(String::as_str), Some("production"));210        assert_eq!(env.get("TOKEN").map(String::as_str), Some("a=b"));211        assert_eq!(env.len(), 2);212    }213214    #[test]215    fn names_the_line_of_a_malformed_entry_without_its_value() {216        let error = parse_environment("OK=1\nsecret-value-here\n").unwrap_err();217        let message = error.to_string();218        assert!(message.contains("line 2"));219        assert!(!message.contains("secret-value-here"));220    }221}