use crate::cli::commands;
use crate::config::Config;
use crate::container::devcontainer::{DevcontainerBackend, DevcontainerIdentity, DevcontainerSpec};
use crate::container::{Backend, compose::ComposeBackend};
use crate::runtime::{Executor, Resolution, Resolver, ResolverContext};
use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use std::path::{Path, PathBuf};
use std::sync::Arc;
#[derive(Debug, Parser)]
#[command(name = "croft", version, about = "The dev workspace you tend")]
pub struct Cli {
#[arg(long, global = true)]
pub project: Option<PathBuf>,
#[arg(long, global = true)]
pub explain: bool,
#[arg(long, global = true)]
pub profile: Option<String>,
#[command(subcommand)]
pub command: Option<Command>,
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
pub args: Vec<String>,
}
#[derive(Debug, Subcommand)]
pub enum Command {
#[command(alias = "ls")]
List,
Which { name: String },
Env {
#[arg(long, value_name = "PATH")]
write: Option<PathBuf>,
},
Doctor,
Init {
#[arg(long)]
template: Option<commands::init::Template>,
},
Install {
step: Option<String>,
#[arg(long, conflicts_with_all = ["restart", "step"])]
resume: bool,
#[arg(long, conflicts_with_all = ["resume", "step"])]
restart: bool,
#[arg(long)]
dry_run: bool,
#[arg(long)]
list: bool,
#[arg(long)]
update_hooks: bool,
},
Ui,
Hooks {
#[command(subcommand)]
action: HooksAction,
},
Agents {
#[command(subcommand)]
action: AgentsAction,
},
Completions { shell: clap_complete::Shell },
Lib {
#[command(subcommand)]
action: LibAction,
},
Worktree {
#[command(subcommand)]
action: WorktreeAction,
},
Watch {
recipe: String,
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
args: Vec<String>,
#[arg(long)]
path: Vec<PathBuf>,
#[arg(long)]
debounce_ms: Option<u64>,
},
Update {
#[arg(long)]
force: bool,
#[arg(long)]
prerelease: bool,
},
Shell {
#[arg(long, value_name = "NAME")]
service: Option<String>,
},
}
#[derive(Debug, Subcommand)]
pub enum HooksAction {
Install {
#[arg(long, value_delimiter = ',')]
stages: Vec<String>,
},
Uninstall {
#[arg(long, value_delimiter = ',')]
stages: Vec<String>,
},
Run { stage: String },
}
#[derive(Debug, Subcommand)]
pub enum AgentsAction {
Install {
#[arg(long)]
force: bool,
#[arg(long)]
dry_run: bool,
#[arg(long)]
force_overwrite_drift: bool,
},
Update {
#[arg(long = "source", value_name = "NAME")]
sources: Vec<String>,
#[arg(long)]
force: bool,
#[arg(long)]
dry_run: bool,
#[arg(long)]
force_overwrite_drift: bool,
},
Status {
#[arg(long)]
strict: bool,
},
Diff,
}
#[derive(Debug, Subcommand)]
pub enum LibAction {
Ask {
prompt: String,
#[arg(long)]
default: Option<String>,
},
Confirm {
prompt: String,
#[arg(long, value_parser = parse_yes_no)]
default: Option<bool>,
},
Password { prompt: String },
Select {
prompt: String,
choices: Vec<String>,
#[arg(long)]
multi: bool,
#[arg(long)]
default: Option<usize>,
#[arg(long)]
from: Option<PathBuf>,
},
Filter {
prompt: String,
choices: Vec<String>,
#[arg(long)]
from: Option<PathBuf>,
},
}
fn parse_yes_no(s: &str) -> Result<bool, String> {
match s.to_ascii_lowercase().as_str() {
"y" | "yes" | "true" | "1" => Ok(true),
"n" | "no" | "false" | "0" => Ok(false),
other => Err(format!("expected yes/no, got `{other}`")),
}
}
#[derive(Debug, Subcommand)]
pub enum WorktreeAction {
Status,
List,
Assign {
name: String,
offset: u32,
#[arg(long)]
local: bool,
},
}
pub async fn run(cli: Cli) -> Result<()> {
init_tracing();
if let Some(Command::Init { template }) = cli.command {
let project_root = locate_project_root(cli.project.as_deref())?;
return commands::init::run(&project_root, template);
}
if let Some(Command::Completions { shell }) = cli.command {
return commands::completions::run(shell);
}
if let Some(Command::Lib { action }) = cli.command {
let code = run_lib_action(action)?;
std::process::exit(code);
}
if let Some(Command::Update { force, prerelease }) = cli.command {
return commands::update::run(force, prerelease).await;
}
let project_root = locate_project_root(cli.project.as_deref())?;
let bootstrap_cfg = crate::config::load_project_with_slug(&project_root, None)
.with_context(|| format!("load project at {}", project_root.display()))?;
let identity = crate::runtime::Identity::detect(&project_root, &bootstrap_cfg).await;
let slug_for_overlay = if identity.is_isolated() {
Some(identity.slug.as_str())
} else {
None
};
let config = crate::config::load_project_with_slug(&project_root, slug_for_overlay)
.with_context(|| format!("load project at {}", project_root.display()))?;
let cfg_arc = Arc::new(config);
commands::env::auto_write_if_configured(&cfg_arc, &project_root)
.await
.context("auto-write [worktrees] dotenv")?;
if let Some(sub) = cli.command {
return match sub {
Command::List => cmd_list(&cfg_arc),
Command::Which { name } => cmd_which(&cfg_arc, &name),
Command::Env { write } => commands::env::run(&cfg_arc, &project_root, write).await,
Command::Doctor => {
let code = commands::doctor::run(&cfg_arc, &project_root).await?;
std::process::exit(code);
}
Command::Init { .. } => unreachable!("handled above"),
Command::Completions { .. } => unreachable!("handled above"),
Command::Lib { .. } => unreachable!("handled above"),
Command::Update { .. } => unreachable!("handled above"),
Command::Ui => run_tui(Arc::clone(&cfg_arc), &project_root, &identity).await,
Command::Watch {
recipe,
args,
path,
debounce_ms,
} => {
commands::watch::run(
Arc::clone(&cfg_arc),
&project_root,
recipe,
args,
path,
debounce_ms,
)
.await
}
Command::Worktree { action } => match action {
WorktreeAction::Status => commands::worktree::status(&cfg_arc, &identity).await,
WorktreeAction::List => commands::worktree::list(&cfg_arc, &project_root).await,
WorktreeAction::Assign {
name,
offset,
local,
} => commands::worktree::assign(&name, offset, local, &project_root),
},
Command::Hooks { action } => match action {
HooksAction::Install { stages } => {
commands::hooks::install(&cfg_arc, &project_root, &stages).await
}
HooksAction::Uninstall { stages } => {
commands::hooks::uninstall(&project_root, &stages).await
}
HooksAction::Run { stage } => {
let code = commands::hooks::run(&cfg_arc, &project_root, &stage).await?;
std::process::exit(code);
}
},
Command::Agents { action } => match action {
AgentsAction::Install {
force,
dry_run,
force_overwrite_drift,
} => {
commands::agents::install(
&cfg_arc,
&project_root,
force,
dry_run,
force_overwrite_drift,
)
.await
}
AgentsAction::Update {
sources,
force,
dry_run,
force_overwrite_drift,
} => {
commands::agents::update(
&cfg_arc,
&project_root,
sources,
force,
dry_run,
force_overwrite_drift,
)
.await
}
AgentsAction::Status { strict } => {
let code = commands::agents::status(&cfg_arc, &project_root, strict).await?;
std::process::exit(code);
}
AgentsAction::Diff => commands::agents::diff(&cfg_arc, &project_root).await,
},
Command::Shell { service } => {
let code =
commands::shell::run(&cfg_arc, &project_root, &identity, service.as_deref())
.await?;
std::process::exit(code);
}
Command::Install {
step,
resume,
restart,
dry_run,
list,
update_hooks,
} => {
let code = dispatch_install(
Arc::clone(&cfg_arc),
project_root.clone(),
commands::install::InstallArgs {
step,
resume,
restart,
dry_run,
list,
update_hooks,
assume_fresh: false,
},
)
.await?;
std::process::exit(code);
}
};
}
if cli.args.is_empty() {
return run_tui(Arc::clone(&cfg_arc), &project_root, &identity).await;
}
let (name, rest) = split_args(&cli.args);
let ctx = ResolverContext::default();
let resolver = Resolver::new(&cfg_arc, ctx);
let resolution = resolver.resolve(name);
if cli.explain {
return print_explain(name, &resolution);
}
match resolution {
Resolution::Builtin(b) => {
anyhow::bail!("built-in `{b}` not yet implemented");
}
Resolution::Recipe(recipe_name) => {
let executor =
build_executor(&cfg_arc, &project_root, &identity, cli.profile.as_deref()).await?;
let owned = recipe_name.to_string();
let code = executor.run_recipe(&owned, rest).await?;
std::process::exit(code);
}
Resolution::Script(script_name) => {
let executor =
build_executor(&cfg_arc, &project_root, &identity, cli.profile.as_deref()).await?;
let owned = script_name.to_string();
let code = executor.run_script(&owned, rest).await?;
std::process::exit(code);
}
Resolution::ComposePassthrough(sub) => {
let executor =
build_executor(&cfg_arc, &project_root, &identity, cli.profile.as_deref()).await?;
let mut argv: Vec<&str> = vec![sub];
argv.extend(rest.iter().map(String::as_str));
let code = executor.passthrough(&argv).await?;
std::process::exit(code);
}
Resolution::ServiceExec(service) => {
let executor =
build_executor(&cfg_arc, &project_root, &identity, cli.profile.as_deref()).await?;
let argv: Vec<&str> = rest.iter().map(String::as_str).collect();
let code = executor.service_exec(service, &argv, true).await?;
std::process::exit(code);
}
Resolution::Unknown { suggestion } => {
if let Some(s) = suggestion {
anyhow::bail!("no such command `{name}` — did you mean `{s}`?");
}
anyhow::bail!("no such command `{name}`");
}
}
}
fn run_lib_action(action: LibAction) -> Result<i32> {
match action {
LibAction::Ask { prompt, default } => commands::lib::ask(&prompt, default.as_deref()),
LibAction::Confirm { prompt, default } => commands::lib::confirm(&prompt, default),
LibAction::Password { prompt } => commands::lib::password(&prompt),
LibAction::Select {
prompt,
choices,
multi,
default,
from,
} => commands::lib::select(&prompt, choices, multi, default, from.as_deref()),
LibAction::Filter {
prompt,
choices,
from,
} => commands::lib::filter(&prompt, choices, from.as_deref()),
}
}
async fn dispatch_install(
config: Arc<Config>,
project_root: PathBuf,
mut args: commands::install::InstallArgs,
) -> Result<i32> {
let plan = commands::install::plan::resolve(&config, &project_root)?;
ensure_croft_gitignore(&config, &project_root).context("update .croft/.gitignore")?;
let bypass_prompt =
args.resume || args.restart || args.dry_run || args.list || args.step.is_some();
if !bypass_prompt
&& let Some(state) = commands::install::state::InstallState::load(&project_root)?
&& let Some(idx) = state.first_unresolved()
{
let name = plan
.get(idx)
.map(|s| s.name.as_str())
.unwrap_or("<unknown>");
let prompt = format!("Previous install stopped at `{name}`. Resume from there? [Y/n]");
let want_resume = if std::io::IsTerminal::is_terminal(&std::io::stdin()) {
dialoguer::Confirm::new()
.with_prompt(prompt)
.default(true)
.interact()
.unwrap_or(true)
} else {
true
};
if want_resume {
args.resume = true;
} else {
args.assume_fresh = true;
}
}
let backend = build_backend(&config).await?;
commands::install::run(config, project_root, backend, plan, args).await
}
fn ensure_croft_gitignore(config: &Config, project_root: &Path) -> Result<()> {
let rel = &config.install.gitignore;
let p = Path::new(rel);
let path = if p.is_absolute() {
p.to_path_buf()
} else {
project_root.join(p)
};
let body = "local.toml\nworktrees/\ncache/\ninstall.state.json\nagents.state.json\n";
crate::config::managed_block::write(&path, body)
.with_context(|| format!("write {}", path.display()))?;
Ok(())
}
async fn build_executor(
config: &Arc<Config>,
project_root: &Path,
identity: &crate::runtime::Identity,
profile: Option<&str>,
) -> Result<Executor> {
let backend = build_backend(config).await?;
let mut executor =
Executor::new(backend, Arc::clone(config), project_root).with_identity(identity.clone());
if let Some(dc) = build_devcontainer(config, project_root, identity)? {
executor = executor.with_devcontainer(dc);
}
if let Some(p) = profile {
executor = executor.with_profile(p);
}
Ok(executor)
}
pub(crate) fn build_devcontainer(
config: &Config,
project_root: &Path,
identity: &crate::runtime::Identity,
) -> Result<Option<Arc<DevcontainerBackend>>> {
if !config.devcontainer.enabled {
return Ok(None);
}
let override_path = config.devcontainer.path.as_deref();
let spec_path = DevcontainerSpec::discover(project_root, override_path)
.context("locate devcontainer.json (devcontainer.enabled = true)")?;
let spec = DevcontainerSpec::load(&spec_path)
.with_context(|| format!("parse {}", spec_path.display()))?;
let project_slug = project_slug_from_root(project_root);
let dc_identity = DevcontainerIdentity {
project_root: project_root.to_path_buf(),
project_slug,
worktree_slug: identity.slug.clone(),
};
Ok(Some(Arc::new(DevcontainerBackend::new(spec, dc_identity))))
}
fn project_slug_from_root(project_root: &Path) -> String {
let basename = project_root
.file_name()
.and_then(|s| s.to_str())
.unwrap_or("project");
crate::runtime::slugify(basename)
}
fn cmd_list(config: &Config) -> Result<()> {
use comfy_table::{ContentArrangement, Table, presets::UTF8_FULL};
if config.commands.is_empty() && config.scripts.is_empty() {
println!("No recipes or scripts defined.");
return Ok(());
}
let mut table = Table::new();
table
.load_preset(UTF8_FULL)
.set_content_arrangement(ContentArrangement::Dynamic)
.set_header(vec!["name", "kind", "in", "description"]);
for (name, recipe) in &config.commands {
table.add_row(vec![
name.clone(),
"recipe".into(),
recipe.service.clone().unwrap_or_else(|| "host".into()),
recipe.desc.clone().unwrap_or_default(),
]);
}
for (name, script) in &config.scripts {
table.add_row(vec![
name.clone(),
"script".into(),
script.service.clone().unwrap_or_else(|| "host".into()),
script.desc.clone().unwrap_or_default(),
]);
}
println!("{table}");
Ok(())
}
fn cmd_which(config: &Config, name: &str) -> Result<()> {
let resolver = Resolver::new(config, ResolverContext::default());
print_explain(name, &resolver.resolve(name))
}
fn print_explain(name: &str, resolution: &Resolution<'_>) -> Result<()> {
match resolution {
Resolution::Builtin(b) => println!("{name} → built-in `{b}`"),
Resolution::Recipe(_) => println!("{name} → recipe in croft.toml"),
Resolution::Script(_) => println!("{name} → script in .croft/commands/"),
Resolution::ComposePassthrough(_) => println!("{name} → docker compose passthrough"),
Resolution::ServiceExec(_) => println!("{name} → exec into compose service"),
Resolution::Unknown {
suggestion: Some(s),
} => {
println!("{name} → unknown (did you mean `{s}`?)")
}
Resolution::Unknown { suggestion: None } => println!("{name} → unknown"),
}
Ok(())
}
fn split_args(args: &[String]) -> (&str, &[String]) {
let (head, tail) = args.split_first().expect("non-empty args");
(head.as_str(), tail)
}
async fn build_backend(config: &Config) -> Result<Arc<dyn Backend>> {
use crate::config::model::Backend as B;
let container: Option<Arc<dyn Backend>> = match config.runtime.backend {
B::None => None,
B::Compose => Some(Arc::new(
ComposeBackend::detect()
.await
.context("detect compose backend")?,
)),
B::Docker | B::Podman => anyhow::bail!(
"backend `{:?}` is configured but not yet implemented; use `compose` or `none`",
config.runtime.backend
),
};
let mut entries: Vec<crate::container::custom::CustomEntry> =
Vec::with_capacity(config.services.custom.len() + config.services.systemd.len());
for svc in &config.services.custom {
entries.push(crate::runtime::services::from_custom(svc));
}
for svc in &config.services.systemd {
entries.push(crate::runtime::services::from_systemd(svc));
}
let custom = if entries.is_empty() {
None
} else {
Some(crate::container::custom::CustomBackend::new(entries))
};
Ok(Arc::new(crate::container::registry::ServiceRegistry::new(
container, custom,
)))
}
async fn run_tui(
initial_config: Arc<Config>,
initial_root: &Path,
initial_identity: &crate::runtime::Identity,
) -> Result<()> {
let mut current_root = initial_root.to_path_buf();
let mut current_config = initial_config;
let mut current_branch = branch_label(initial_identity);
let mut next_view = crate::tui::View::ControlCenter;
loop {
let backend: Arc<dyn Backend> = match build_backend(¤t_config).await {
Ok(b) => b,
Err(_) => Arc::new(crate::container::registry::ServiceRegistry::new(
Some(Arc::new(crate::container::null::NullBackend)),
None,
)),
};
let identity = crate::runtime::Identity::detect(¤t_root, ¤t_config).await;
let devcontainer = build_devcontainer(¤t_config, ¤t_root, &identity)
.context("build devcontainer backend")?;
let mut executor = crate::runtime::Executor::new(
Arc::clone(&backend),
Arc::clone(¤t_config),
¤t_root,
)
.with_identity(identity.clone());
if let Some(dc) = &devcontainer {
executor = executor.with_devcontainer(Arc::clone(dc));
}
let outcome = crate::tui::run(
Arc::clone(¤t_config),
executor,
backend,
devcontainer,
¤t_root,
next_view,
current_branch.clone(),
)
.await
.context("run TUI")?;
match outcome {
crate::tui::DriveOutcome::Quit => return Ok(()),
crate::tui::DriveOutcome::SwitchWorktree { path, view } => {
let bootstrap_cfg = crate::config::load_project_with_slug(&path, None)
.with_context(|| format!("load project at {}", path.display()))?;
let identity = crate::runtime::Identity::detect(&path, &bootstrap_cfg).await;
let slug_for_overlay = if identity.is_isolated() {
Some(identity.slug.as_str())
} else {
None
};
let new_cfg = crate::config::load_project_with_slug(&path, slug_for_overlay)
.with_context(|| format!("load project at {}", path.display()))?;
current_root = path;
current_config = Arc::new(new_cfg);
current_branch = branch_label(&identity);
next_view = view;
}
}
}
}
fn branch_label(identity: &crate::runtime::Identity) -> Option<String> {
match &identity.base_ref {
crate::runtime::BaseRef::Branch(b) => Some(b.clone()),
crate::runtime::BaseRef::DetachedSha(s) => Some(format!("det-{s}")),
crate::runtime::BaseRef::WorktreeDir(d) => Some(d.clone()),
crate::runtime::BaseRef::None => None,
}
}
fn init_tracing() {
let _ = tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("warn")),
)
.with_target(false)
.try_init();
}
fn locate_project_root(explicit: Option<&Path>) -> Result<PathBuf> {
if let Some(p) = explicit {
return Ok(p.to_path_buf());
}
let mut cur = std::env::current_dir()?;
loop {
if cur.join("croft.toml").exists() || cur.join(".croft").is_dir() {
return Ok(cur);
}
if !cur.pop() {
return Ok(std::env::current_dir()?);
}
}
}