ampelos 0.1.0

Dev-loop trellis: one config for Docker Compose, scripts, hooks, and agents
Documentation
//! Docker Compose backend implementation.
//!
//! Shells out to `docker compose` (preferred) or `docker-compose` (fallback).
//! Detection is performed once at construction time; subsequent calls reuse
//! the discovered argv prefix.

use crate::container::{Backend, BackendError, ExecOptions, ServiceStatus};
use async_trait::async_trait;
use std::process::Stdio;
use tokio::process::Command;
use tracing::debug;

/// Compose driver discriminator: modern plugin (`docker compose`) vs legacy
/// standalone binary (`docker-compose`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Driver {
    Plugin,
    Standalone,
}

#[derive(Debug)]
pub struct ComposeBackend {
    driver: Driver,
}

impl ComposeBackend {
    /// Auto-detect the available compose driver. Prefers the plugin form.
    pub async fn detect() -> Result<Self, BackendError> {
        if Self::probe(&["docker", "compose", "version"]).await {
            debug!("compose driver: plugin");
            return Ok(Self {
                driver: Driver::Plugin,
            });
        }
        if which::which("docker-compose").is_ok() {
            debug!("compose driver: standalone");
            return Ok(Self {
                driver: Driver::Standalone,
            });
        }
        Err(BackendError::BinaryNotFound(
            "docker compose / docker-compose".into(),
        ))
    }

    /// Return the program + leading args used to invoke compose.
    fn prefix(&self) -> &'static [&'static str] {
        match self.driver {
            Driver::Plugin => &["docker", "compose"],
            Driver::Standalone => &["docker-compose"],
        }
    }

    /// Build the `docker compose exec` command for a single invocation.
    /// `pipe_stdin = true` forces `-T` (no TTY) regardless of
    /// `opts.tty`, because piping stdin and TTY allocation are
    /// mutually exclusive in compose exec.
    fn build_exec_command(
        &self,
        service: &str,
        argv: &[&str],
        opts: &ExecOptions,
        pipe_stdin: bool,
    ) -> Command {
        let prefix = self.prefix();
        let (head, tail) = prefix.split_first().expect("non-empty prefix");
        let mut cmd = Command::new(head);
        cmd.args(tail);
        cmd.arg("exec");
        if pipe_stdin {
            cmd.arg("-T");
            cmd.stdin(Stdio::piped());
        } else if opts.tty {
            cmd.arg("-it");
        } else {
            cmd.arg("-T");
        }
        for (k, v) in &opts.env {
            cmd.arg("-e").arg(format!("{k}={v}"));
        }
        if let Some(wd) = &opts.workdir {
            cmd.arg("-w").arg(wd);
        }
        cmd.arg(service);
        cmd.args(argv);
        cmd
    }

    async fn probe(argv: &[&str]) -> bool {
        let (head, tail) = match argv.split_first() {
            Some(parts) => parts,
            None => return false,
        };
        Command::new(head)
            .args(tail)
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .stdin(Stdio::null())
            .status()
            .await
            .map(|s| s.success())
            .unwrap_or(false)
    }
}

#[async_trait]
impl Backend for ComposeBackend {
    fn name(&self) -> &'static str {
        match self.driver {
            Driver::Plugin => "compose",
            Driver::Standalone => "compose-legacy",
        }
    }

    async fn status(&self, service: &str) -> Result<ServiceStatus, BackendError> {
        // `compose ps -q <service>` outputs the container ID(s) for the
        // service, empty when not running.
        let prefix = self.prefix();
        let (head, tail) = prefix.split_first().expect("non-empty prefix");
        let mut cmd = Command::new(head);
        cmd.args(tail).args(["ps", "-q", service]);
        cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
        let output = cmd.output().await?;
        if !output.status.success() {
            return Ok(ServiceStatus::Missing);
        }
        let stdout = std::str::from_utf8(&output.stdout)?.trim();
        if stdout.is_empty() {
            return Ok(ServiceStatus::Stopped);
        }
        Ok(ServiceStatus::Running)
    }

    async fn exec(
        &self,
        service: &str,
        argv: &[&str],
        opts: &ExecOptions,
    ) -> Result<i32, BackendError> {
        let mut cmd = self.build_exec_command(service, argv, opts, /*pipe_stdin=*/ false);
        let status = cmd.status().await?;
        Ok(status.code().unwrap_or(-1))
    }

    async fn exec_with_stdin(
        &self,
        service: &str,
        argv: &[&str],
        opts: &ExecOptions,
        stdin: &str,
    ) -> Result<i32, BackendError> {
        use tokio::io::AsyncWriteExt;

        let mut cmd = self.build_exec_command(service, argv, opts, /*pipe_stdin=*/ true);
        cmd.kill_on_drop(true);

        let mut child = cmd.spawn().map_err(BackendError::Spawn)?;
        if let Some(mut stdin_handle) = child.stdin.take() {
            stdin_handle
                .write_all(stdin.as_bytes())
                .await
                .map_err(BackendError::Spawn)?;
            // Closing stdin (drop) signals EOF — many shells (e.g. bash
            // -s) won't start until stdin is closed.
            drop(stdin_handle);
        }
        let status = child.wait().await.map_err(BackendError::Spawn)?;
        Ok(status.code().unwrap_or(-1))
    }

    async fn spawn_exec(
        &self,
        service: &str,
        argv: &[&str],
        opts: &ExecOptions,
    ) -> Result<tokio::process::Child, BackendError> {
        let mut cmd = self.build_exec_command(service, argv, opts, /*pipe_stdin=*/ false);
        cmd.stdout(Stdio::piped());
        cmd.stderr(Stdio::piped());
        cmd.stdin(Stdio::null());
        cmd.kill_on_drop(true);
        cmd.spawn().map_err(BackendError::Spawn)
    }

    async fn spawn_exec_with_stdin(
        &self,
        service: &str,
        argv: &[&str],
        opts: &ExecOptions,
    ) -> Result<tokio::process::Child, BackendError> {
        let mut cmd = self.build_exec_command(service, argv, opts, /*pipe_stdin=*/ true);
        cmd.stdout(Stdio::piped());
        cmd.stderr(Stdio::piped());
        cmd.kill_on_drop(true);
        cmd.spawn().map_err(BackendError::Spawn)
    }

    async fn passthrough(&self, args: &[&str]) -> Result<i32, BackendError> {
        let prefix = self.prefix();
        let (head, tail) = prefix.split_first().expect("non-empty prefix");
        let status = Command::new(head).args(tail).args(args).status().await?;
        Ok(status.code().unwrap_or(-1))
    }

    async fn list_services(&self) -> Result<Vec<String>, BackendError> {
        let prefix = self.prefix();
        let (head, tail) = prefix.split_first().expect("non-empty prefix");
        let mut cmd = Command::new(head);
        cmd.args(tail).args(["config", "--services"]);
        cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
        let output = cmd.output().await?;
        if !output.status.success() {
            // Non-zero is normal when there's no compose file; the TUI
            // treats an empty list the same as "no services".
            return Ok(Vec::new());
        }
        let stdout = std::str::from_utf8(&output.stdout)?;
        Ok(stdout
            .lines()
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .map(str::to_string)
            .collect())
    }

    async fn service_action(
        &self,
        action: &str,
        services: &[&str],
    ) -> Result<tokio::process::Child, BackendError> {
        let prefix = self.prefix();
        let (head, tail) = prefix.split_first().expect("non-empty prefix");
        let mut cmd = Command::new(head);
        cmd.args(tail);
        match action {
            "up" => {
                // -d so the action returns and the long-running services
                // detach. The TUI's separate compose-logs tail then
                // streams what's actually running.
                cmd.args(["up", "-d"]);
                cmd.args(services);
            }
            "down" => {
                cmd.arg("down");
                // `down` doesn't accept service args in older compose
                // versions; pass them anyway — the modern plugin
                // interprets them as "remove just these services".
                cmd.args(services);
            }
            "stop" => {
                cmd.arg("stop");
                cmd.args(services);
            }
            "restart" => {
                cmd.arg("restart");
                cmd.args(services);
            }
            other => {
                return Err(BackendError::Reported(format!(
                    "unsupported service action `{other}` (expected up / down / stop / restart)"
                )));
            }
        }
        cmd.stdout(Stdio::piped());
        cmd.stderr(Stdio::piped());
        cmd.stdin(Stdio::null());
        cmd.kill_on_drop(true);
        cmd.spawn().map_err(BackendError::Spawn)
    }

    async fn tail_logs(&self, service: &str) -> Result<tokio::process::Child, BackendError> {
        let prefix = self.prefix();
        let (head, tail) = prefix.split_first().expect("non-empty prefix");
        let mut cmd = Command::new(head);
        cmd.args(tail);
        // --tail seeds the buffer with recent history so users don't open
        // an empty pane on a long-running service. -f follows.
        cmd.args(["logs", "-f", "--tail", "200", service]);
        cmd.stdout(Stdio::piped());
        cmd.stderr(Stdio::piped());
        cmd.stdin(Stdio::null());
        cmd.kill_on_drop(true);
        cmd.spawn().map_err(BackendError::Spawn)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn driver_prefix_matches_variant() {
        let plugin = ComposeBackend {
            driver: Driver::Plugin,
        };
        assert_eq!(plugin.prefix(), &["docker", "compose"]);

        let standalone = ComposeBackend {
            driver: Driver::Standalone,
        };
        assert_eq!(standalone.prefix(), &["docker-compose"]);
    }

    #[test]
    fn name_reflects_driver() {
        let plugin = ComposeBackend {
            driver: Driver::Plugin,
        };
        assert_eq!(plugin.name(), "compose");

        let standalone = ComposeBackend {
            driver: Driver::Standalone,
        };
        assert_eq!(standalone.name(), "compose-legacy");
    }
}