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::io::Write;

use troll_core::{Zone, ZoneChanges, ZoneConflict, ZoneResult};

use crate::{
    cli::ZoneCommand,
    error::CliError,
    output::{self, SCHEMA, ZoneListOutput, ZoneOutput},
};

use super::Context;

pub(crate) fn build_zone_add(context: &Context, zone: Zone) -> Result<ZoneOutput, CliError> {
    context.ensure_registry_home()?;
    let result = troll_core::add_zone(&context.store, zone)?;
    Ok(ZoneOutput {
        schema: SCHEMA,
        result,
    })
}

pub(crate) fn build_zone_list(context: &Context) -> Result<ZoneListOutput, CliError> {
    let registry = context.store.load()?;
    let conflicts = registry
        .zone
        .iter()
        .flat_map(|zone| zone.conflicts(&registry))
        .collect();
    Ok(ZoneListOutput {
        schema: SCHEMA,
        conflicts,
        conflict_count: registry.zone_conflicts().len(),
        zones: registry.zone,
    })
}

pub(crate) fn build_zone_enabled(
    context: &Context,
    label: &str,
    enabled: bool,
) -> Result<ZoneOutput, CliError> {
    context.ensure_registry_home()?;
    let result = troll_core::set_zone_enabled(&context.store, label, enabled)?;
    Ok(ZoneOutput {
        schema: SCHEMA,
        result,
    })
}

pub(crate) fn build_zone_edit(
    context: &Context,
    label: &str,
    changes: ZoneChanges,
) -> Result<ZoneOutput, CliError> {
    context.ensure_registry_home()?;
    let result = troll_core::edit_zone(&context.store, label, changes)?;
    Ok(ZoneOutput {
        schema: SCHEMA,
        result,
    })
}

pub(crate) fn build_zone_remove(
    context: &Context,
    label: &str,
    expected_tag: Option<&str>,
) -> Result<ZoneOutput, CliError> {
    context.ensure_registry_home()?;
    let zone = troll_core::remove_zone(&context.store, label, expected_tag)?;
    Ok(ZoneOutput {
        schema: SCHEMA,
        result: ZoneResult {
            zone,
            conflicts: Vec::new(),
        },
    })
}

pub(crate) fn build_zone_edit_if_match(
    context: &Context,
    label: &str,
    tag: &str,
    changes: ZoneChanges,
    enabled: Option<bool>,
) -> Result<ZoneOutput, CliError> {
    context.ensure_registry_home()?;
    let result = troll_core::edit_zone_if_match(&context.store, label, tag, changes, enabled)?;
    Ok(ZoneOutput {
        schema: SCHEMA,
        result,
    })
}

pub(super) fn run(context: &Context, action: ZoneCommand, json: bool) -> Result<(), CliError> {
    let (verb, result) = match action {
        ZoneCommand::Add {
            label,
            ports,
            reason,
            disabled,
        } => (
            "Added",
            build_zone_add(
                context,
                Zone {
                    label,
                    reason,
                    ports,
                    enabled: !disabled,
                },
            )?,
        ),
        ZoneCommand::List => {
            let result = build_zone_list(context)?;
            return output::write(json, &result, |out| {
                if result.zones.is_empty() {
                    writeln!(out, "No zones.")?;
                }
                for zone in &result.zones {
                    print_zone(out, zone)?;
                    for conflict in result
                        .conflicts
                        .iter()
                        .filter(|row| row.label == zone.label)
                    {
                        writeln!(out, "  {conflict}")?;
                    }
                }
                writeln!(out, "Conflicts ({})", result.conflict_count)?;
                Ok(())
            });
        }
        ZoneCommand::Enable { label } => ("Enabled", build_zone_enabled(context, &label, true)?),
        ZoneCommand::Disable { label } => ("Disabled", build_zone_enabled(context, &label, false)?),
        ZoneCommand::Edit {
            label,
            ports,
            reason,
            no_reason,
        } => (
            "Edited",
            build_zone_edit(
                context,
                &label,
                ZoneChanges {
                    ports,
                    reason: if no_reason {
                        Some(None)
                    } else {
                        reason.map(Some)
                    },
                },
            )?,
        ),
        ZoneCommand::Remove { label, if_tag } => (
            "Removed",
            build_zone_remove(context, &label, if_tag.as_deref())?,
        ),
    };
    output::write(json, &result, |out| {
        write!(out, "{verb} zone ")?;
        print_zone(out, &result.result.zone)?;
        print_conflicts(out, &result.result.conflicts)
    })
}

fn print_zone(out: &mut dyn Write, zone: &Zone) -> Result<(), CliError> {
    let state = if zone.enabled { "enabled" } else { "disabled" };
    write!(out, "{} ({state})  {}", zone.label, zone.ports.join(", "))?;
    if let Some(reason) = &zone.reason {
        write!(out, "  {reason}")?;
    }
    writeln!(out)?;
    Ok(())
}

fn print_conflicts(out: &mut dyn Write, conflicts: &[ZoneConflict]) -> Result<(), CliError> {
    writeln!(out, "Conflicts ({})", conflicts.len())?;
    for conflict in conflicts {
        writeln!(out, "  {conflict}")?;
    }
    Ok(())
}