use crate::config::Config;
use crate::container::devcontainer::DevcontainerBackend;
use anyhow::{Context, Result};
use std::path::Path;
use std::sync::Arc;
use tokio::process::Command;
pub async fn run(
config: &Config,
project_root: &Path,
identity: &crate::runtime::Identity,
service: Option<&str>,
) -> Result<i32> {
if let Some(name) = service {
return shell_into_service(name).await;
}
shell_into_devcontainer(config, project_root, identity).await
}
async fn shell_into_devcontainer(
config: &Config,
project_root: &Path,
identity: &crate::runtime::Identity,
) -> Result<i32> {
if !config.devcontainer.enabled {
anyhow::bail!(
"no shell target. Either enable `[devcontainer] enabled = true` in croft.toml, \
or pass `--service <name>` to enter a compose service."
);
}
let dc = crate::cli::app::build_devcontainer(config, project_root, identity)
.context("build devcontainer backend")?
.ok_or_else(|| anyhow::anyhow!("devcontainer disabled — this is a bug, please report"))?;
dc.ensure_up()
.await
.context("ensure devcontainer is running")?;
exec_into(&dc).await
}
async fn exec_into(dc: &Arc<DevcontainerBackend>) -> Result<i32> {
let mut cmd = Command::new("docker");
cmd.args([
"exec",
"-it",
dc.container_name(),
"sh",
"-c",
"exec ${SHELL:-/bin/sh}",
]);
let status = cmd
.status()
.await
.context("spawn docker exec for devcontainer shell")?;
Ok(status.code().unwrap_or(-1))
}
async fn shell_into_service(service: &str) -> Result<i32> {
let mut cmd = Command::new("docker");
cmd.args([
"compose",
"exec",
"-it",
service,
"sh",
"-c",
"exec ${SHELL:-/bin/sh}",
]);
let status = cmd
.status()
.await
.with_context(|| format!("spawn docker compose exec for `{service}`"))?;
Ok(status.code().unwrap_or(-1))
}