diff --git a/src/lib.rs b/src/lib.rs index f9f1828..49eafad 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -54,6 +54,13 @@ pub struct PluginHelp { // Host-to-Plugin Communication // ============================================================================ +/// The host honors the execution policy included with a plugin's plan response. +/// +/// Plugins can require this capability before returning a plan whose execution +/// policy differs from the legacy host behavior. The version suffix allows the +/// policy contract to evolve without changing the protocol shape. +pub const HOST_CAPABILITY_PLAN_EXECUTION_POLICY_V1: &str = "plan-execution-policy-v1"; + /// A request from the meta CLI host to a plugin, sent as JSON on stdin. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PluginRequest { @@ -68,6 +75,38 @@ pub struct PluginRequest { pub options: PluginRequestOptions, } +/// A capability-aware request from a newer host to a plugin. +/// +/// This is a separate type so adding capability negotiation does not break +/// source compatibility for plugins that construct [`PluginRequest`] values. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PluginRequestWithCapabilities { + pub command: String, + #[serde(default)] + pub args: Vec, + #[serde(default)] + pub projects: Vec, + #[serde(default)] + pub cwd: String, + /// Host behavior guarantees available to this request. + /// + /// This is a string list so newer hosts can add capabilities without + /// making older plugins reject otherwise-compatible request JSON. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub host_capabilities: Vec, + #[serde(default)] + pub options: PluginRequestOptions, +} + +impl PluginRequestWithCapabilities { + /// Whether the host advertised a specific behavior guarantee. + pub fn host_supports_capability(&self, capability: &str) -> bool { + self.host_capabilities + .iter() + .any(|advertised| advertised == capability) + } +} + /// Options passed from the host to the plugin as part of the request. #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct PluginRequestOptions { @@ -144,12 +183,62 @@ pub struct PlannedCommand { pub env: Option>, } +/// Controls which host transformations are applied to an execution plan. +/// +/// The default preserves the behavior used before execution policies were +/// added to the protocol, so responses from older plugins remain unchanged. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct PlanExecutionPolicy { + /// Whether the host expands its command aliases before execution. + pub expand_loop_aliases: bool, + /// Whether the host applies its configured project filters to the plan. + pub apply_host_filters: bool, +} + +impl PlanExecutionPolicy { + /// The execution behavior used for plan responses that predate this policy. + pub const fn legacy_defaults() -> Self { + Self { + expand_loop_aliases: true, + apply_host_filters: true, + } + } + + fn is_legacy_default(&self) -> bool { + *self == Self::legacy_defaults() + } +} + +impl Default for PlanExecutionPolicy { + fn default() -> Self { + Self::legacy_defaults() + } +} + /// Wrapper for the execution plan response (the JSON envelope plugins emit). #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PlanResponse { pub plan: ExecutionPlan, } +/// A plan response carrying behavior selected by a capability-aware plugin. +/// +/// Legacy hosts ignore the additional JSON field, while newer hosts can +/// deserialize legacy responses because the policy defaults to legacy behavior. +/// Keeping this separate preserves source compatibility for `PlanResponse` +/// struct literals in existing plugins. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PlanResponseWithPolicy { + pub plan: ExecutionPlan, + /// Host transformations to apply while executing this plan. + #[serde( + default, + skip_serializing_if = "PlanExecutionPolicy::is_legacy_default" + )] + pub execution_policy: PlanExecutionPolicy, +} + // ============================================================================ // Command Result // ============================================================================ @@ -168,6 +257,28 @@ pub enum CommandResult { ShowHelp(Option), } +/// The result of a capability-aware plugin command execution. +/// +/// This mirrors [`CommandResult`] and adds policy-bearing plan variants without +/// adding variants to the legacy public enum, which would break exhaustive +/// matches in existing plugins. +pub enum CommandResultWithPolicy { + /// A simple plan using legacy host execution behavior. + Plan(Vec, Option), + /// A simple plan with an explicit host execution policy. + PlanWithPolicy(Vec, Option, PlanExecutionPolicy), + /// A full execution plan using legacy host execution behavior. + FullPlan(ExecutionPlan), + /// A full execution plan with an explicit host execution policy. + FullPlanWithPolicy(ExecutionPlan, PlanExecutionPolicy), + /// A message to display (no commands to execute). + Message(String), + /// An error occurred. + Error(String), + /// Show help text (optionally with an error message prefix). + ShowHelp(Option), +} + // ============================================================================ // Helper Functions // ============================================================================ @@ -177,6 +288,23 @@ pub fn output_execution_plan(commands: Vec, parallel: Option, + parallel: Option, + execution_policy: PlanExecutionPolicy, +) { + output_execution_plan_full_with_policy( + vec![], + commands, + vec![], + parallel, + None, + None, + execution_policy, + ); +} + /// Serialize and print a full execution plan with pre/post commands to stdout. pub fn output_execution_plan_full( pre_commands: Vec, @@ -199,6 +327,30 @@ pub fn output_execution_plan_full( println!("{}", serde_json::to_string(&response).unwrap()); } +/// Serialize and print a full execution plan with an explicit host execution policy. +pub fn output_execution_plan_full_with_policy( + pre_commands: Vec, + commands: Vec, + post_commands: Vec, + parallel: Option, + max_parallel: Option, + spawn_stagger_ms: Option, + execution_policy: PlanExecutionPolicy, +) { + let response = PlanResponseWithPolicy { + plan: ExecutionPlan { + pre_commands, + commands, + post_commands, + parallel, + max_parallel, + spawn_stagger_ms, + }, + execution_policy, + }; + println!("{}", serde_json::to_string(&response).unwrap()); +} + /// Read and parse a `PluginRequest` from stdin. pub fn read_request_from_stdin() -> anyhow::Result { let mut input = String::new(); @@ -207,6 +359,14 @@ pub fn read_request_from_stdin() -> anyhow::Result { Ok(request) } +/// Read and parse a capability-aware plugin request from stdin. +pub fn read_capability_request_from_stdin() -> anyhow::Result { + let mut input = String::new(); + std::io::stdin().read_to_string(&mut input)?; + let request: PluginRequestWithCapabilities = serde_json::from_str(&input)?; + Ok(request) +} + /// Write plugin help text to a writer. fn write_plugin_help(info: &PluginInfo, w: &mut dyn std::io::Write) { if let Some(help) = &info.help { @@ -344,3 +504,210 @@ pub fn run_plugin(plugin: PluginDefinition) { } } } + +/// Definition of a plugin that negotiates host capabilities. +pub struct PluginDefinitionWithCapabilities { + pub info: PluginInfo, + /// Command roots whose bare invocation is side-effect-free help. + pub bare_help_commands: Vec, + /// The execute function receives the capability-aware request. + pub execute: fn(PluginRequestWithCapabilities) -> CommandResultWithPolicy, +} + +#[derive(Serialize)] +struct CapabilityPluginInfo<'a> { + #[serde(flatten)] + info: &'a PluginInfo, + bare_help_commands: &'a [String], +} + +/// Run a capability-aware plugin while retaining the legacy plugin harness API. +pub fn run_plugin_with_capabilities(plugin: PluginDefinitionWithCapabilities) { + env_logger::init(); + + let args: Vec = std::env::args().collect(); + + if args.len() < 2 { + eprintln!( + "This binary is a meta plugin. Use via: meta {}", + plugin.info.name + ); + std::process::exit(1); + } + + match args[1].as_str() { + "--meta-plugin-info" => { + let json = serde_json::to_string_pretty(&CapabilityPluginInfo { + info: &plugin.info, + bare_help_commands: &plugin.bare_help_commands, + }) + .unwrap(); + println!("{json}"); + } + "--meta-plugin-exec" => { + let request = match read_capability_request_from_stdin() { + Ok(req) => req, + Err(e) => { + eprintln!("Failed to parse plugin request: {e}"); + std::process::exit(1); + } + }; + + match (plugin.execute)(request) { + CommandResultWithPolicy::Plan(commands, parallel) => { + output_execution_plan(commands, parallel); + } + CommandResultWithPolicy::PlanWithPolicy(commands, parallel, execution_policy) => { + output_execution_plan_with_policy(commands, parallel, execution_policy); + } + CommandResultWithPolicy::FullPlan(plan) => { + let response = PlanResponse { plan }; + println!("{}", serde_json::to_string(&response).unwrap()); + } + CommandResultWithPolicy::FullPlanWithPolicy(plan, execution_policy) => { + let response = PlanResponseWithPolicy { + plan, + execution_policy, + }; + println!("{}", serde_json::to_string(&response).unwrap()); + } + CommandResultWithPolicy::Message(msg) => { + if !msg.is_empty() { + println!("{msg}"); + } + } + CommandResultWithPolicy::Error(e) => { + eprintln!("Error: {e}"); + std::process::exit(1); + } + CommandResultWithPolicy::ShowHelp(maybe_error) => { + if let Some(ref err) = maybe_error { + eprintln!("error: {err}"); + eprintln!(); + eprint_plugin_help(&plugin.info); + std::process::exit(1); + } else { + print_plugin_help(&plugin.info); + std::process::exit(0); + } + } + } + } + "--help" | "-h" => { + print_plugin_help(&plugin.info); + } + _ => { + eprintln!("Unknown flag: {}. This binary is a meta plugin.", args[1]); + eprintln!("Use via: meta {}", plugin.info.name); + std::process::exit(1); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn legacy_request_shape_remains_unchanged() { + let request: PluginRequest = serde_json::from_str( + r#"{ + "command": "demo build", + "args": ["demo", "build"], + "projects": [], + "cwd": ".", + "options": {} + }"#, + ) + .unwrap(); + + let encoded = serde_json::to_value(&request).unwrap(); + assert!(encoded.get("host_capabilities").is_none()); + } + + #[test] + fn host_capabilities_round_trip_and_remain_extensible() { + let request = PluginRequestWithCapabilities { + command: "demo".to_string(), + args: vec!["build".to_string()], + projects: vec![], + cwd: ".".to_string(), + host_capabilities: vec![ + HOST_CAPABILITY_PLAN_EXECUTION_POLICY_V1.to_string(), + "future-host-capability-v9".to_string(), + ], + options: PluginRequestOptions::default(), + }; + + let json = serde_json::to_string(&request).unwrap(); + let decoded: PluginRequestWithCapabilities = serde_json::from_str(&json).unwrap(); + + assert!(decoded.host_supports_capability(HOST_CAPABILITY_PLAN_EXECUTION_POLICY_V1)); + assert!(decoded.host_supports_capability("future-host-capability-v9")); + } + + #[test] + fn legacy_plan_response_shape_and_policy_defaults_are_compatible() { + let legacy_json = r#"{ + "plan": { + "commands": [{"dir": ".", "cmd": "demo build"}], + "parallel": false + } + }"#; + let legacy_value: serde_json::Value = serde_json::from_str(legacy_json).unwrap(); + + let response: PlanResponse = serde_json::from_str(legacy_json).unwrap(); + let policy_response: PlanResponseWithPolicy = serde_json::from_str(legacy_json).unwrap(); + + assert_eq!( + policy_response.execution_policy, + PlanExecutionPolicy::legacy_defaults() + ); + assert_eq!(response.plan.commands[0].cmd, "demo build"); + + let encoded = serde_json::to_value(&response).unwrap(); + assert_eq!(encoded, legacy_value); + } + + #[test] + fn explicit_plan_execution_policy_round_trips() { + let response = PlanResponseWithPolicy { + plan: ExecutionPlan { + pre_commands: vec![], + commands: vec![PlannedCommand { + dir: ".".to_string(), + cmd: "demo build".to_string(), + env: None, + }], + post_commands: vec![], + parallel: Some(false), + max_parallel: None, + spawn_stagger_ms: None, + }, + execution_policy: PlanExecutionPolicy { + expand_loop_aliases: false, + apply_host_filters: false, + }, + }; + + let json = serde_json::to_string(&response).unwrap(); + let decoded: PlanResponseWithPolicy = serde_json::from_str(&json).unwrap(); + + assert_eq!(decoded.execution_policy, response.execution_policy); + assert!(json.contains("execution_policy")); + } + + #[test] + fn partial_execution_policy_uses_legacy_field_defaults() { + let response: PlanResponseWithPolicy = serde_json::from_str( + r#"{ + "plan": {"commands": []}, + "execution_policy": {"expand_loop_aliases": false} + }"#, + ) + .unwrap(); + + assert!(!response.execution_policy.expand_loop_aliases); + assert!(response.execution_policy.apply_host_filters); + } +}