capy-cli 0.9.0

The command-line interface for the Capy web framework.
Documentation
//! Development orchestration with interchangeable terminal and inline presentation.
mod buffer;
mod events;
mod output;
mod platform;
mod supervisor;
mod tui;
mod watcher;

use anyhow::{bail, Context, Result};
use capy_cli::{FrontendDriver, ProjectConfig};
use capy_core::AppConfig;
use crossterm::event::{Event, EventStream};
use events::{Control, DevEvent, OutputStream, Status};
use futures_util::StreamExt;
use std::{
    io::{self, IsTerminal, Write},
    path::{Path, PathBuf},
    process::ExitCode,
    time::Duration,
};
use supervisor::{Definition, DevSupervisor, Process, Recipe};
use tokio::sync::mpsc;
use tui::{app::App, terminal::Session};

#[derive(clap::Args, Clone, Copy, Debug, Default)]
pub(crate) struct Options {
    /// Open the dashboard when stdin/stdout support it, including in CI.
    #[arg(long, conflicts_with = "inline")]
    tui: bool,
    /// Use prefixed plain output, without terminal control sequences.
    #[arg(long, conflicts_with_all = ["tui", "stream"])]
    inline: bool,
    /// Start the dashboard in chronological stream mode (inline without a TTY).
    #[arg(long, conflicts_with = "inline")]
    stream: bool,
}
impl Options {
    fn interactive(self, stdin: bool, stdout: bool, ci: bool, dumb: bool) -> bool {
        !self.inline && stdin && stdout && !dumb && (!ci || self.tui || self.stream)
    }
}

pub(crate) fn run(root: &Path, options: Options) -> Result<ExitCode> {
    let (processes, config) = prepare(root)?;
    let interactive = options.interactive(
        io::stdin().is_terminal(),
        io::stdout().is_terminal(),
        std::env::var_os("CI").is_some(),
        std::env::var("TERM").is_ok_and(|v| v == "dumb"),
    );
    let runtime = tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()?;
    runtime
        .block_on(run_async(
            processes,
            config.app.name,
            root,
            options,
            interactive,
        ))
        .map(ExitCode::from)
}

fn prepare(root: &Path) -> Result<(Vec<Process>, AppConfig)> {
    let driver = ProjectConfig::load(root)?.frontend.driver;
    driver.validate(root)?;
    let config = AppConfig::load_from(root)?;
    if config.port() == 0 {
        bail!("capy dev requires a fixed APP_PORT so the frontend can reach the backend. Set a port in config/app.toml, .env, or APP_PORT.");
    }
    let host = match config.host() {
        "0.0.0.0" => "127.0.0.1",
        "::" => "::1",
        host => host,
    };
    let origin = if host.contains(':') {
        format!("http://[{host}]:{}", config.port())
    } else {
        format!("http://{host}:{}", config.port())
    };
    let mut processes = vec![
        Process {
            definition: Definition {
                id: 0,
                name: "server".into(),
                command: "cargo build → serve".into(),
                url: Some(origin.clone()),
                restartable: true,
            },
            recipe: Some(Recipe::Backend {
                root: root.into(),
                config: Box::new(config.clone()),
                logs: 1,
            }),
        },
        Process {
            definition: Definition {
                id: 1,
                name: "logs".into(),
                command: "application tracing".into(),
                url: None,
                restartable: false,
            },
            recipe: None,
        },
    ];
    if driver == FrontendDriver::React {
        let port: u16 = std::env::var("CAPY_FRONTEND_PORT")
            .unwrap_or_else(|_| "5173".into())
            .parse()
            .context("CAPY_FRONTEND_PORT must be a TCP port between 1 and 65535.")?;
        if port == 0 {
            bail!("CAPY_FRONTEND_PORT must be a TCP port between 1 and 65535.");
        }
        if port == config.port() {
            bail!("The frontend and backend must use different ports.");
        }
        std::net::TcpListener::bind(("127.0.0.1", port)).with_context(|| {
            format!("Frontend port {port} is unavailable. Set CAPY_FRONTEND_PORT to another port.")
        })?;
        processes.push(Process {
            definition: Definition {
                id: 2,
                name: "frontend".into(),
                command: "pnpm run dev".into(),
                url: Some(format!("http://127.0.0.1:{port}")),
                restartable: true,
            },
            recipe: Some(Recipe::Frontend {
                root: root.into(),
                driver,
                origin,
                port,
            }),
        });
    }
    Ok((processes, config))
}

fn project_path(root: &Path) -> String {
    if let Some(home) = std::env::var_os("HOME").map(PathBuf::from) {
        if let Ok(relative) = root.strip_prefix(home) {
            return format!("~/{}", relative.display());
        }
    }
    root.display().to_string()
}

async fn run_async(
    processes: Vec<Process>,
    name: String,
    root: &Path,
    options: Options,
    interactive: bool,
) -> Result<u8> {
    // Register signals and acquire the terminal before any children exist.
    let mut signals = platform::Signals::new()?;
    let mut session = if interactive {
        Some(Session::new().context("Could not initialize terminal; use capy dev --inline")?)
    } else {
        None
    };
    let mut input = if interactive {
        Some(EventStream::new())
    } else {
        None
    };
    let mut app = App::new(
        processes.iter().map(|p| p.definition.clone()).collect(),
        name,
        project_path(root),
        options.stream,
    );
    let (events_tx, mut events) = mpsc::channel(512);
    let (control, control_rx) = mpsc::channel(16);
    let mut supervisor =
        tokio::spawn(DevSupervisor::new(processes, events_tx, control_rx, interactive).run());
    let mut tick = tokio::time::interval(Duration::from_millis(50));
    tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
    let mut dirty = true;
    let mut stopping = false;
    let mut error = None;
    let result = loop {
        tokio::select! {
            biased;
            result = &mut supervisor => break result.context("Development supervisor failed")?,
            _ = signals.recv(), if !stopping => {
                stopping = true;
                input = None;
                let _ = control.send(Control::Shutdown).await;
                app.feedback = "Stopping development processes…".into(); dirty = true;
            }
            event = async { match &mut input { Some(input) => input.next().await, None => std::future::pending().await } }, if !stopping => {
                match event {
                    Some(Ok(Event::Key(key))) => {
                        if let Some(request) = app.key(key) {
                            if request == Control::Shutdown { stopping = true; input = None; app.feedback = "Stopping development processes…".into(); }
                            let _ = control.send(request).await;
                        }
                    }
                    Some(Ok(Event::Resize(_, _))) => {},
                    Some(Ok(_)) => {},
                    Some(Err(e)) => { error = Some(anyhow::Error::from(e)); stopping = true; input = None; let _ = control.send(Control::Shutdown).await; }
                    None => { stopping = true; input = None; let _ = control.send(Control::Shutdown).await; }
                }
                dirty = true;
            }
            _ = tick.tick(), if interactive => {
                if dirty && error.is_none() {
                    if let Some(session) = &mut session {
                        if let Err(e) = session.terminal.draw(|frame| tui::ui::draw(frame, &mut app)) {
                            error = Some(anyhow::Error::from(e)); stopping = true; input = None; let _ = control.send(Control::Shutdown).await;
                        }
                    }
                    dirty = false;
                }
            }
            Some(event) = events.recv() => {
                if !interactive && error.is_none() {
                    if let Err(e) = print_event(&event, &app) {
                        error = Some(e.into()); stopping = true; let _ = control.send(Control::Shutdown).await;
                    }
                }
                app.event(event); dirty = true;
            }
        }
    };
    // All senders are now stopped. Preserve trailing errors before restoring the shell.
    while let Ok(event) = events.try_recv() {
        if !interactive && error.is_none() {
            if let Err(e) = print_event(&event, &app) {
                error = Some(e.into());
            }
        }
        app.event(event);
    }
    drop(input);
    drop(session.take());
    if interactive && (result.as_ref().map_or(true, |code| *code != 0)) {
        for context in &app.contexts {
            if matches!(context.status, Status::Failed { .. }) {
                for line in context
                    .output
                    .lines
                    .iter()
                    .skip(context.output.lines.len().saturating_sub(20))
                {
                    let _ = io::stderr()
                        .write_all(output::inline(line, &context.definition.name).as_bytes());
                }
            }
        }
    }
    if let Some(error) = error {
        return Err(error);
    }
    result
}

fn print_event(event: &DevEvent, app: &App) -> io::Result<()> {
    if let DevEvent::Output(line) = event {
        if let Some(context) = app.contexts.iter().find(|c| c.definition.id == line.source) {
            let text = output::inline(line, &context.definition.name);
            if line.stream == OutputStream::Stderr {
                io::stderr().write_all(text.as_bytes())?;
            } else {
                io::stdout().write_all(text.as_bytes())?;
            }
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn tty_mode_selection_respects_redirection_ci_and_forcing() {
        let auto = Options::default();
        assert!(auto.interactive(true, true, false, false));
        for (stdin, stdout, ci, dumb) in [
            (false, true, false, false),
            (true, false, false, false),
            (true, true, true, false),
            (true, true, false, true),
        ] {
            assert!(!auto.interactive(stdin, stdout, ci, dumb));
        }
        let force = Options { tui: true, ..auto };
        assert!(force.interactive(true, true, true, false));
        assert!(!force.interactive(false, true, false, false));
        assert!(!Options {
            inline: true,
            ..auto
        }
        .interactive(true, true, false, false));
    }
    #[test]
    fn api_and_frontend_none_have_only_server_and_logs() {
        let temp = tempfile::tempdir().unwrap();
        for name in ["api", "none"] {
            let root = temp.path().join(name);
            capy_cli::new_project_with_frontend(&root, name, FrontendDriver::None).unwrap();
            let (processes, _) = prepare(&root).unwrap();
            assert_eq!(
                processes
                    .iter()
                    .map(|p| p.definition.name.as_str())
                    .collect::<Vec<_>>(),
                ["server", "logs"]
            );
            assert!(processes[1].recipe.is_none());
        }
    }
}