use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use clap::{Parser, Subcommand};
use motabhai_core::{Database, Error, Project};
mod starter;
#[derive(Debug, Parser)]
#[command(name = "motabhai", version, about)]
struct Cli {
#[arg(short, long, global = true, value_name = "PATH")]
project: Option<PathBuf>,
#[command(subcommand)]
command: Command,
}
#[derive(Debug, Subcommand)]
enum Command {
Build {
#[arg(short, long, value_name = "DIR")]
output: Option<PathBuf>,
#[arg(long)]
execute: bool,
},
Serve {
#[arg(long, default_value_t = 5000)]
port: u16,
#[arg(long, default_value = "127.0.0.1", value_name = "ADDRESS")]
host: std::net::IpAddr,
#[arg(short, long, value_name = "DIR")]
output: Option<PathBuf>,
},
New {
path: PathBuf,
#[arg(long)]
tailwind: bool,
#[arg(
long,
value_enum,
value_name = "THEME",
default_value_t,
conflicts_with = "tailwind"
)]
theme: starter::Theme,
},
Deploy {
target: Option<String>,
#[arg(short, long, value_name = "DIR")]
output: Option<PathBuf>,
},
Check,
Clean {
#[arg(short, long, value_name = "DIR")]
output: Option<PathBuf>,
},
}
fn main() -> ExitCode {
install_error_hook();
let cli = Cli::parse();
match run(&cli) {
Ok(()) => ExitCode::SUCCESS,
Err(report) => {
eprintln!("{report:?}");
ExitCode::FAILURE
}
}
}
fn run(cli: &Cli) -> miette::Result<()> {
let project = cli.project.as_deref();
match &cli.command {
Command::Check => check(project),
Command::Build { output, execute } => build(project, output.as_deref(), *execute),
Command::Deploy { target, output } => deploy(project, target.as_deref(), output.as_deref()),
Command::Serve { port, host, output } => serve(project, *host, *port, output.as_deref()),
Command::New {
path,
tailwind,
theme,
} => starter::create(path, *tailwind, *theme),
Command::Clean { output } => clean(project, output.as_deref()),
}
}
fn load_project(path: Option<&Path>) -> miette::Result<Project> {
if let Some(path) = path {
return Ok(Project::open(path)?);
}
let cwd = std::env::current_dir().map_err(|e| Error::io(".", e))?;
Ok(Project::discover(&cwd)?)
}
fn check(path: Option<&Path>) -> miette::Result<()> {
let project = load_project(path)?;
let db = Database::load(&project)?;
let config = project.config();
let primary = || db.records().filter(|r| r.alt() == config.primary().code);
let attachments: usize = primary().map(|r| r.attachments().len()).sum();
let hidden = primary().filter(|r| r.is_hidden()).count();
println!(
"ok: {} ({})",
config.project.name,
project.config_path().display()
);
let mut summary = plural(db.models().len(), "model");
let blocks = db.models().block_count();
if blocks > 0 {
let _ = write!(summary, ", {}", plural(blocks, "flow block"));
}
let _ = write!(summary, ", {}", plural(primary().count(), "record"));
if config.is_multilingual() {
let _ = write!(summary, " in {} languages", config.alternatives.len());
}
println!(
"{summary} ({hidden} hidden), {}",
plural(attachments, "attachment")
);
Ok(())
}
fn build(path: Option<&Path>, output: Option<&Path>, execute: bool) -> miette::Result<()> {
let project = load_project(path)?;
let output = output_dir(&project, output)?;
build_with_hooks(&project, &output, execute)
}
fn build_with_hooks(project: &Project, output: &Path, execute: bool) -> miette::Result<()> {
let hooks = &project.config().hooks;
for command in &hooks.before_build {
eprintln!("running {command}");
motabhai_build::hooks::run(project, command, output)?;
}
let options = motabhai_build::Options::new().with_execute(execute);
let build = motabhai_build::build_with(project, output, &options)?;
for unfinished in &build.unfinished {
eprintln!("warning: {unfinished}");
}
println!("{}", summary(&build, &relative(output)));
for command in &hooks.after_build {
eprintln!("running {command}");
motabhai_build::hooks::run(project, command, output)?;
}
Ok(())
}
fn deploy(path: Option<&Path>, target: Option<&str>, output: Option<&Path>) -> miette::Result<()> {
let project = load_project(path)?;
let config = project.config();
let names = || {
config
.deploy
.iter()
.map(|t| t.name.clone())
.collect::<Vec<_>>()
};
let target = match target {
Some(name) => config
.deploy_target(name)
.ok_or_else(|| Error::UnknownDeployTarget {
name: name.to_owned(),
help: if config.deploy.is_empty() {
"the site has no deploy targets; add a `[deploy.<name>]` table to `motabhai.toml`".to_owned()
} else {
format!("the site's targets are: {}", names().join(", "))
},
})?,
None => match config.deploy.as_slice() {
[only] => only,
_ => return Err(Error::NoDeployTarget { names: names() }.into()),
},
};
motabhai_deploy::check(target)?;
let output = output_dir(&project, output)?;
build_with_hooks(&project, &output, false)?;
let deployed = motabhai_deploy::deploy(&project, target, &output)?;
println!("deployed to {}: {deployed}", target.name);
Ok(())
}
fn summary(build: &motabhai_build::Build, output: &Path) -> String {
let counts = build.counts();
let mut changes = format!("{} rebuilt", build.rebuilt().count());
if !build.removed.is_empty() {
let _ = write!(changes, ", {} removed", build.removed.len());
}
let mut kinds = vec![
plural(counts.pages, "page"),
plural(counts.attachments, "attachment"),
];
if counts.redirects > 0 {
kinds.push(plural(counts.redirects, "redirect"));
}
if counts.thumbnails > 0 {
kinds.push(plural(counts.thumbnails, "thumbnail"));
}
kinds.push(plural(counts.assets, "asset"));
let last = kinds.pop().unwrap_or_default();
format!(
"built {} and {last} into {} ({changes})",
kinds.join(", "),
output.display()
)
}
fn serve(
path: Option<&Path>,
host: std::net::IpAddr,
port: u16,
output: Option<&Path>,
) -> miette::Result<()> {
let project = load_project(path)?;
let output = output_dir(&project, output)?;
let options = motabhai_server::Options::new(host, port, output);
Ok(motabhai_server::serve(&project, &options)?)
}
fn clean(path: Option<&Path>, output: Option<&Path>) -> miette::Result<()> {
let project = load_project(path)?;
let output = output_dir(&project, output)?;
let cleaned = motabhai_build::clean(&project, &output)?;
if cleaned.output {
println!("removed {}", relative(&output).display());
} else if cleaned.state {
println!("removed the build state");
} else {
println!(
"nothing to clean: {} does not exist",
relative(&output).display()
);
}
Ok(())
}
fn output_dir(project: &Project, output: Option<&Path>) -> miette::Result<PathBuf> {
match output {
Some(dir) => Ok(std::path::absolute(dir).map_err(|e| Error::io(dir, e))?),
None => Ok(project.root().join(motabhai_build::OUTPUT_DIR)),
}
}
fn relative(path: &Path) -> PathBuf {
std::env::current_dir()
.ok()
.and_then(|cwd| path.strip_prefix(cwd).ok().map(Path::to_path_buf))
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or_else(|| path.to_path_buf())
}
fn plural(n: usize, noun: &str) -> String {
if n == 1 {
format!("1 {noun}")
} else {
format!("{n} {noun}s")
}
}
fn install_error_hook() {
let _ = miette::set_hook(Box::new(|_| {
Box::new(
miette::MietteHandlerOpts::new()
.context_lines(2)
.tab_width(4)
.build(),
)
}));
}