troll 0.3.2

The port manager that guards the bridge: permanent claims, expiring leases, and a live view of who listens where.
use std::{fs, io, path::Path};

use troll_core::Config;

use crate::error::CliError;

pub(super) const FILE_NAME: &str = "config.toml";

/// Inspect separately from reading so --yes can keep any existing config,
/// even if it is unreadable or was written by a newer version of troll.
pub(super) fn exists(path: &Path) -> Result<bool, CliError> {
    match path.symlink_metadata() {
        Ok(_) => Ok(true),
        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
        Err(error) => Err(CliError::ReadConfig(path.to_owned(), error)),
    }
}

pub(super) fn read(path: &Path) -> Result<Option<String>, CliError> {
    if !exists(path)? {
        return Ok(None);
    }
    // Follow a hand-managed symlink for reading, as the other commands do.
    let result = fs::metadata(path).and_then(|metadata| {
        if !metadata.is_file() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "expected a regular file",
            ));
        }
        fs::read_to_string(path)
    });
    result
        .map(Some)
        .map_err(|error| CliError::ReadConfig(path.to_owned(), error))
}

pub(super) fn check_unchanged(path: &Path, previous: Option<&str>) -> Result<(), CliError> {
    if read(path)?.as_deref() != previous {
        return Err(CliError::InitConfigChanged(path.to_owned()));
    }
    Ok(())
}

pub(super) fn render(home: &Path, config: &Config, port: Option<u16>) -> Result<String, CliError> {
    let policy = &config.policy;
    let service_port = port.map_or_else(String::new, |port| format!("service_port = {port}\n"));
    let mut text = format!(
        "lease_range = [{}, {}]\n{service_port}lease_default = \"{}\"\nlease_max = \"{}\"\nsweep_interval = \"{}\"\n",
        policy.lease_range.start(),
        policy.lease_range.end(),
        duration(policy.lease_default.unsigned_abs().as_secs()),
        duration(policy.lease_max.unsigned_abs().as_secs()),
        duration(config.sweep_interval.as_secs()),
    );
    // Preserve a hand-configured app range when replacing an existing file.
    if config.app_range_is_explicit() {
        text.push_str(&format!(
            "app_range = [{}, {}]\n",
            policy.app_range.start(),
            policy.app_range.end(),
        ));
    }
    if config.registry_home != home {
        text.push_str(&format!(
            "registry_home = {}\n",
            path_value(home, &config.registry_home)?
        ));
    }
    if let Some(roots) = &config.project_roots {
        let values = roots
            .iter()
            .map(|path| path_value(home, path))
            .collect::<Result<Vec<_>, _>>()?;
        text.push_str(&format!("project_roots = [{}]\n", values.join(", ")));
    }
    if let Some(patterns) = &config.third_party {
        let values = patterns
            .iter()
            .map(|value| string_value(value))
            .collect::<Result<Vec<_>, _>>()?;
        text.push_str(&format!("third_party = [{}]\n", values.join(", ")));
    }
    if !config.pools.is_empty() {
        text.push_str("\n[pools]\n");
        for (name, range) in &config.pools {
            text.push_str(&format!("{name} = [{}, {}]\n", range.start(), range.end()));
        }
    }
    Ok(text)
}

fn duration(seconds: u64) -> String {
    const SECONDS_PER_DAY: u64 = 86_400;
    if seconds > SECONDS_PER_DAY && seconds.is_multiple_of(SECONDS_PER_DAY) {
        return format!("{}d", seconds / SECONDS_PER_DAY);
    }
    for (unit, length) in [('h', 3_600), ('m', 60)] {
        if seconds.is_multiple_of(length) {
            return format!("{}{unit}", seconds / length);
        }
    }
    format!("{seconds}s")
}

fn path_value(home: &Path, path: &Path) -> Result<String, CliError> {
    let relative = path.strip_prefix(home).unwrap_or(path);
    // Values read from TOML are UTF-8. Strip the resolved home before encoding
    // so a relative value also works below a non-UTF-8 XDG directory.
    let value = relative.to_str().ok_or_else(|| {
        CliError::InvalidInit(format!(
            "configuration path {path:?} cannot be represented in TOML"
        ))
    })?;
    string_value(value)
}

fn string_value(value: &str) -> Result<String, CliError> {
    // JSON's string escapes are also TOML basic-string escapes. TOML requires
    // DEL (which JSON leaves unescaped) to be escaped too.
    Ok(serde_json::to_string(value)
        .map_err(CliError::Json)?
        .replace('\u{7f}', "\\u007f"))
}

pub(super) fn replacement_preview(path: &Path, before: &str, after: &str) -> String {
    let mut detail = format!("Changes to {path:?}\n");
    for (prefix, text) in [('-', before), ('+', after)] {
        for line in text.lines() {
            detail.push(prefix);
            detail.push(' ');
            for ch in line.chars() {
                if ch.is_control() && ch != '\t' {
                    detail.extend(ch.escape_default());
                } else {
                    detail.push(ch);
                }
            }
            detail.push('\n');
        }
    }
    detail
}