use anyhow::{bail, Context, Result};
use clap::{Args, Parser, Subcommand};
use intentional_core::{
check_workspace, initialize_with, ApplyResult, Bump, BumpTranslation, Config, InitOptions,
InitState, IntentDraft, ReleasePlan, Severity, StampResult, TagPhase, TagResult,
WorkspaceStatus, CONFIG_PATH, MISSING_BASELINE_CODE, MISSING_BASELINE_NEXT_ACTION,
};
use semver::Version;
use std::collections::{BTreeMap, BTreeSet};
use std::io::{self, Write};
use std::path::PathBuf;
const SKILL_DOCUMENT: &str = include_str!("../skills/intentional/SKILL.md");
#[derive(Debug, Parser)]
#[command(
name = "intentional",
version,
about = "Intent-driven polyglot releases"
)]
struct Cli {
#[arg(short = 'C', long, default_value = ".", global = true)]
directory: PathBuf,
#[command(subcommand)]
command: Command,
}
#[derive(Debug, Subcommand)]
enum Command {
Init(InitArgs),
Model(ModelArgs),
Add(AddArgs),
Status {
#[arg(long)]
json: bool,
},
Plan(ChannelArgs),
Apply(ChannelDryRunArgs),
Stamp(StampArgs),
Tag(TagArgs),
Check,
Verify(VerifyArgs),
Skill,
}
#[derive(Debug, Args)]
struct DryRun {
#[arg(long)]
dry_run: bool,
}
#[derive(Debug, Args)]
struct InitArgs {
#[arg(long)]
take_over: bool,
#[arg(long, value_name = "parity|significance")]
bump_translation: Option<BumpTranslation>,
#[arg(long)]
json: bool,
#[arg(long)]
dry_run: bool,
}
#[derive(Debug, Args)]
struct ModelArgs {
#[arg(long)]
dry_run: bool,
#[arg(long)]
stdout: bool,
#[arg(long, conflicts_with = "stdout")]
json: bool,
}
#[derive(Debug, Args)]
struct AddArgs {
#[arg(long = "release-unit")]
release_units: Vec<String>,
#[arg(long = "graduate", value_name = "ID")]
graduates: Vec<String>,
#[arg(long)]
message: Option<String>,
#[arg(long)]
dry_run: bool,
}
#[derive(Debug, Args)]
struct ChannelArgs {
#[arg(long)]
channel: Option<String>,
}
#[derive(Debug, Args)]
struct ChannelDryRunArgs {
#[arg(long)]
channel: Option<String>,
#[arg(long)]
dry_run: bool,
}
#[derive(Debug, Args)]
struct TagArgs {
#[arg(long)]
channel: Option<String>,
#[arg(long)]
baseline: bool,
#[arg(long = "version")]
versions: Vec<String>,
#[arg(long)]
phase: Option<String>,
#[arg(long, value_name = "PATH")]
plan: Option<PathBuf>,
#[arg(long)]
dry_run: bool,
}
#[derive(Debug, Args)]
struct VerifyArgs {
tag: String,
#[arg(long)]
json: bool,
}
#[derive(Debug, Args)]
struct StampArgs {
#[arg(long)]
prerelease: Option<String>,
#[arg(long)]
dry_run: bool,
}
fn main() -> std::process::ExitCode {
match run() {
Ok(code) => std::process::ExitCode::from(code),
Err(error) => {
eprintln!("{error:#}");
std::process::ExitCode::FAILURE
}
}
}
fn run() -> Result<u8> {
let cli = Cli::parse();
match cli.command {
Command::Init(args) => return init(&cli.directory, args),
Command::Verify(args) => return verify(&cli.directory, args),
Command::Add(args) => add(&cli.directory, args),
Command::Status { json } => status(&cli.directory, json),
Command::Model(args) => model(&cli.directory, args),
Command::Plan(args) => plan(&cli.directory, args.channel.as_deref()),
Command::Apply(args) => apply(&cli.directory, args.channel.as_deref(), args.dry_run),
Command::Stamp(args) => stamp(&cli.directory, args.prerelease.as_deref(), args.dry_run),
Command::Tag(args) => tag(&cli.directory, args),
Command::Check => check(&cli.directory),
Command::Skill => skill(),
}?;
Ok(0)
}
fn verify(root: &std::path::Path, args: VerifyArgs) -> Result<u8> {
let verification = intentional_core::verify_release(root, &args.tag)?;
if args.json {
println!("{}", verification.to_json()?);
} else {
match &verification.target {
Some(target) if verification.verified => {
println!("verified {} at {target}", verification.tag)
}
_ => println!("verification failed for {}", verification.tag),
}
for guarantee in &verification.guarantees {
println!("guarantee: {guarantee}");
}
for tag in &verification.identity_tags {
println!("identity tag: {tag}");
}
for diagnostic in &verification.diagnostics {
let severity = match diagnostic.severity {
Severity::Error => "error",
Severity::Advisory => "advisory",
};
println!("{severity} [{}] {}", diagnostic.code, diagnostic.message);
}
}
Ok(if verification.verified { 0 } else { 1 })
}
fn skill() -> Result<()> {
print!("{SKILL_DOCUMENT}");
Ok(())
}
fn check(root: &std::path::Path) -> Result<()> {
check_workspace(root)?;
println!("check passed");
Ok(())
}
fn tag(root: &std::path::Path, args: TagArgs) -> Result<()> {
let phase = args.phase.as_deref().map(parse_phase).transpose()?;
let mut explicit = BTreeMap::new();
for value in args.versions {
let (id, version) = value
.split_once('=')
.with_context(|| format!("baseline version must be id=X.Y.Z; got {value}"))?;
let version = Version::parse(version)?;
if explicit.insert(id.to_owned(), version).is_some() {
bail!("baseline version {id} was specified more than once");
}
}
if args.baseline && args.channel.is_some() {
bail!("--baseline and --channel cannot be combined");
}
if args.baseline && args.plan.is_some() {
bail!("--baseline and --plan cannot be combined");
}
if !args.baseline && !explicit.is_empty() {
bail!("--version is valid only with --baseline");
}
let result = if args.baseline {
TagResult::build_baseline(root, &explicit)?
} else {
let plan_path = args.plan.as_ref().map(|path| {
if path.is_absolute() {
path.clone()
} else {
root.join(path)
}
});
TagResult::build_with_plan(root, args.channel.as_deref(), phase, plan_path.as_deref())?
};
for operation in result.operations() {
println!("{operation}");
}
result.apply(root, args.dry_run)?;
Ok(())
}
fn stamp(root: &std::path::Path, prerelease: Option<&str>, dry_run: bool) -> Result<()> {
let result = StampResult::build(root, prerelease)?;
for operation in result.operations() {
println!("{operation}");
}
result.apply(root, dry_run)?;
Ok(())
}
fn apply(root: &std::path::Path, channel: Option<&str>, dry_run: bool) -> Result<()> {
let result = ApplyResult::build(root, channel)?;
for operation in result.operations() {
println!("{operation}");
}
result.apply(root, dry_run)?;
Ok(())
}
fn plan(root: &std::path::Path, channel: Option<&str>) -> Result<()> {
let plan = ReleasePlan::build(root, channel)?;
println!("{}", plan.encode()?);
Ok(())
}
fn init(root: &std::path::Path, args: InitArgs) -> Result<u8> {
let result = initialize_with(
root,
InitOptions {
take_over: args.take_over,
bump_translation: args.bump_translation,
},
)?;
if args.json {
println!("{}", result.to_json()?);
} else {
let state = match result.state {
InitState::NeedsInput => "needs-input",
InitState::Ready | InitState::Success => "ready",
};
println!("initialization state: {state}");
for operation in &result.operations {
println!("{operation}");
}
let plan = result
.plan
.as_ref()
.filter(|_| result.path == std::path::Path::new(intentional_core::INIT_PLAN_PATH))
.filter(|_| !args.take_over);
if let Some(plan) = plan {
println!("plan: {}", result.path.display());
if let Some(translation) = plan.bump_translation {
println!("bump translation: {translation}");
if plan.source_kind == "contract-1" && plan.parity.status == "blocked" {
println!(
"bump translation {translation} cannot keep every contract-1 version; see parity in the plan, then run intentional init --bump-translation significance or change the pending intents"
);
} else if plan.source_kind == "contract-1" && result.state == InitState::Ready {
println!(
"review the bump translation and rewritten intents in the plan, then run intentional init again to upgrade"
);
}
}
}
for action in result.next_actions(root) {
println!("next: {action}");
}
}
result.apply(root, args.dry_run)?;
Ok(if result.state == InitState::NeedsInput {
2
} else {
0
})
}
fn add(root: &std::path::Path, args: AddArgs) -> Result<()> {
let config = Config::load(root)
.with_context(|| format!("load {CONFIG_PATH} before adding an intent"))?;
let release_unit_values = if args.release_units.is_empty() {
let ids = config.release_units.keys().cloned().collect::<Vec<_>>();
println!("Release units: {}", ids.join(", "));
vec![prompt("Release unit (id): ")? + ":" + &prompt("Bump (major|minor|patch): ")?]
} else {
args.release_units
};
let mut release_units = BTreeMap::new();
for value in release_unit_values {
let (id, bump) = value
.split_once(':')
.with_context(|| format!("release-unit bump must be id:bump; got {value}"))?;
let bump = bump.parse::<Bump>().map_err(anyhow::Error::msg)?;
if release_units.insert(id.to_owned(), bump).is_some() {
bail!("release unit {id} was specified more than once");
}
}
let mut graduates = BTreeSet::new();
for id in args.graduates {
if !graduates.insert(id.clone()) {
bail!("release unit {id} was given to --graduate more than once");
}
}
let message = match args.message {
Some(message) => message,
None => prompt("Changelog message: ")?,
};
let write = IntentDraft {
release_units,
graduates,
message,
}
.plan(root, &config)?;
println!("write {}", write.path.display());
write.apply(root, args.dry_run)?;
Ok(())
}
fn status(root: &std::path::Path, json: bool) -> Result<()> {
let status = WorkspaceStatus::load(root)?;
if json {
println!("{}", serde_json::to_string(&status)?);
return Ok(());
}
if status.release_model_stale {
println!("{}", intentional_core::release_model_stale_message());
}
if status.intents.is_empty() {
println!("Pending intents: none");
} else {
println!("Pending intents: {}", status.intents.join(", "));
}
if !status.missing_baselines.is_empty() {
println!(
"[{MISSING_BASELINE_CODE}] Missing baseline tags: {}; run {MISSING_BASELINE_NEXT_ACTION}",
status.missing_baselines.join(", "),
);
}
for issue in &status.tag_record_issues {
println!("Tag record: {issue}");
}
for release_unit in status.release_units {
let graduation = if release_unit.graduates {
", graduates to 1.0.0"
} else {
""
};
println!(
"{}: {} -> {} ({}{graduation})",
release_unit.id, release_unit.current, release_unit.next, release_unit.bump
);
}
if status.drift.is_empty() {
println!("Drift: none");
} else {
println!("Drift:");
for drift in status.drift {
println!(
" {} {}: manifest {} != tag {}",
drift.release_unit,
drift.file.display(),
drift.actual,
drift.expected
);
}
}
Ok(())
}
fn parse_phase(value: &str) -> Result<TagPhase> {
match value {
"before-publication" => Ok(TagPhase::BeforePublication),
"after-publication" => Ok(TagPhase::AfterPublication),
_ => bail!("phase must be before-publication or after-publication; got {value}"),
}
}
fn prompt(label: &str) -> Result<String> {
print!("{label}");
io::stdout().flush()?;
let mut value = String::new();
io::stdin().read_line(&mut value)?;
Ok(value.trim().to_owned())
}
fn model(root: &std::path::Path, args: ModelArgs) -> Result<()> {
if args.stdout {
print!("{}", intentional_core::ReleaseModel::build(root)?.encode()?);
return Ok(());
}
let written = intentional_core::write_release_model(root, args.dry_run)?;
let operation = if written { "written" } else { "unchanged" };
if args.json {
println!(
"{}",
format_args!(
r#"{{"dry_run":{},"operation":"{}","path":"{}"}}"#,
args.dry_run,
operation,
intentional_core::RELEASE_MODEL_PATH
)
);
} else {
println!(
"{}{} {}",
if args.dry_run { "dry-run: " } else { "" },
operation,
intentional_core::RELEASE_MODEL_PATH
);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::Cli;
use clap::CommandFactory;
use std::collections::BTreeSet;
fn long_flags(command: &clap::Command) -> BTreeSet<String> {
command
.get_arguments()
.filter(|argument| !argument.is_global_set())
.filter(|argument| !matches!(argument.get_id().as_str(), "help" | "version"))
.filter_map(|argument| argument.get_long())
.map(|long| format!("--{long}"))
.collect()
}
fn specified_flags(options: &serde_yaml::Value) -> BTreeSet<String> {
options
.as_sequence()
.map(|options| {
options
.iter()
.flat_map(|option| option["flags"].as_sequence().cloned().unwrap_or_default())
.filter_map(|flag| flag.as_str().map(str::to_owned))
.filter(|flag| flag.starts_with("--"))
.collect()
})
.unwrap_or_default()
}
#[test]
fn commands_and_flags_match_the_cli_specification() {
let specification: serde_yaml::Value = serde_yaml::from_str(include_str!(
"../../../docs/specifications/command-line-interface.spec.yml"
))
.expect("CLI specification parses");
let cli = Cli::command();
let shipped = cli
.get_subcommands()
.map(|command| command.get_name().to_owned())
.collect::<BTreeSet<_>>();
let specified = specification["commands"]
.as_sequence()
.expect("commands")
.iter()
.filter_map(|command| command["name"].as_str().map(str::to_owned))
.collect::<BTreeSet<_>>();
assert_eq!(shipped, specified);
for command in specification["commands"].as_sequence().expect("commands") {
let name = command["name"].as_str().expect("command name");
let Some(subcommand) = cli.find_subcommand(name) else {
continue;
};
assert_eq!(
long_flags(subcommand),
specified_flags(&command["options"]),
"{name}"
);
}
assert_eq!(
specified_flags(&specification["global-options"]),
BTreeSet::from(["--directory".to_owned()])
);
}
}