Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 3 additions & 13 deletions cli/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ struct AppRuntime {
telemetry_enabled: bool,
fs: services::capabilities::StdFsOps,
git: services::capabilities::ProcessGitOps,
registry: services::command_registry::CommandRegistry,
startup_diagnostic: Option<String>,
}

Expand Down Expand Up @@ -377,7 +376,6 @@ fn initialize_runtime(startup: StartupContext) -> Result<AppRuntime, CliError> {
.telemetry_enabled(),
fs: services::capabilities::StdFsOps,
git: services::capabilities::ProcessGitOps,
registry: services::command_registry::build_default_registry(),
startup_diagnostic: startup.startup_diagnostic,
})
}
Expand All @@ -396,7 +394,6 @@ where
let context = runtime.context();
run_command_lifecycle_with_context(
args,
&runtime.registry,
&context,
runtime.startup_diagnostic.as_deref(),
stdout,
Expand All @@ -407,7 +404,6 @@ where

async fn run_command_lifecycle_with_context<I, L, T, StdoutW, StderrW>(
args: I,
registry: &services::command_registry::CommandRegistry,
context: &AppContext<'_, L, T>,
startup_diagnostic: Option<&str>,
stdout: &mut StdoutW,
Expand Down Expand Up @@ -436,7 +432,7 @@ where
let Some((command_args, (stdout, stderr))) = command_inputs else {
return Err(repeated_dispatch_error());
};
let result = dispatch_command(command_args, registry, context, stderr).await;
let result = dispatch_command(command_args, context, stderr).await;
app_support::render_command_result(
result,
Some(context.logger()),
Expand All @@ -456,7 +452,6 @@ fn repeated_dispatch_error() -> CliError {

async fn dispatch_command<L, T, StderrW>(
args: Vec<String>,
registry: &services::command_registry::CommandRegistry,
context: &AppContext<'_, L, T>,
stderr: &mut StderrW,
) -> Result<String, CliError>
Expand All @@ -465,22 +460,20 @@ where
T: TelemetryTrait,
StderrW: Write,
{
let command = parse_command_phase(args, registry, context)?;
let command = parse_command_phase(args, context)?;
services::managed_telemetry::trace_export::record_command_name(&command.name());
app_support::execute_command_phase(&command, context, stderr).await
}

fn parse_command_phase<I>(
args: I,
registry: &services::command_registry::CommandRegistry,
context: &impl HasLogger,
) -> Result<services::command_registry::RuntimeCommand, CliError>
where
I: IntoIterator<Item = String>,
{
let logger = context.logger();
let command =
services::parse::command_runtime::parse_runtime_command(args, registry, Some(logger))?;
let command = services::parse::command_runtime::parse_runtime_command(args, Some(logger))?;
logger.info(
"sce.command.parsed",
"Command parsed",
Expand Down Expand Up @@ -679,7 +672,6 @@ pub(crate) mod tests {
let mut stdout = Vec::new();
let result = Box::pin(run_command_lifecycle_with_context(
args.into_iter().map(String::from),
&services::command_registry::CommandRegistry::default(),
&context,
None,
&mut stdout,
Expand Down Expand Up @@ -739,7 +731,6 @@ pub(crate) mod tests {
let context = AppContext::new(&logger, &telemetry, &fs, &git, None);
let result = Box::pin(run_command_lifecycle_with_context(
args.iter().map(|arg| (*arg).to_string()),
&services::command_registry::CommandRegistry::default(),
&context,
None,
stdout,
Expand Down Expand Up @@ -849,7 +840,6 @@ pub(crate) mod tests {

let result = Box::pin(run_command_lifecycle_with_context(
["sce", "help"].map(String::from),
&services::command_registry::CommandRegistry::default(),
&context,
None,
&mut FailingWriter,
Expand Down
6 changes: 0 additions & 6 deletions cli/src/command_surface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,6 @@ const SCE_BANNER_VISIT_SUFFIX: &str = " to learn more.";
const HELP_COMMAND_NAME: &str = "help";
const HELP_COMMAND_PURPOSE: &str = "Show help for the current CLI surface";

pub fn is_known_command(name: &str) -> bool {
name == HELP_COMMAND_NAME
|| cli_schema::TOP_LEVEL_COMMANDS
.iter()
.any(|command| command.name == name)
}
enum HelpSectionBodyLine {
Text(&'static str),
Command {
Expand Down
114 changes: 0 additions & 114 deletions cli/src/services/command_registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,6 @@ use crate::app::{ContextWithRepoRoot, HasLogger};
use crate::services;
use crate::services::error::CliError;

const DEFAULT_COMMAND_NAMES: &[&str] = &[
services::auth_command::NAME,
services::completion::NAME,
services::config::NAME,
services::doctor::NAME,
services::help::NAME,
services::hooks::NAME,
services::bash_policy::NAME,
services::setup::NAME,
services::sync::NAME,
services::version::NAME,
];

pub enum RuntimeCommand {
Help(services::help::command::HelpCommand),
HelpText(services::help::command::HelpTextCommand),
Expand Down Expand Up @@ -73,104 +60,3 @@ impl RuntimeCommand {
}
}
}

pub struct CommandRegistry {
names: &'static [&'static str],
}

impl CommandRegistry {
pub fn contains(&self, name: &str) -> bool {
self.names.contains(&name)
}
}

impl Default for CommandRegistry {
fn default() -> Self {
build_default_registry()
}
}

pub fn build_default_registry() -> CommandRegistry {
CommandRegistry {
names: DEFAULT_COMMAND_NAMES,
}
}

pub fn default_runtime_command(name: &str) -> Option<RuntimeCommand> {
match name {
services::help::NAME => Some(RuntimeCommand::Help(services::help::command::HelpCommand)),
services::auth_command::NAME => Some(RuntimeCommand::Auth(
services::auth_command::command::AuthCommand {
request: services::auth_command::AuthRequest {
subcommand: services::auth_command::AuthSubcommand::Whoami {
format: services::auth_command::AuthFormat::Text,
},
},
},
)),
services::config::NAME => Some(RuntimeCommand::Config(
services::config::command::ConfigCommand {
subcommand: services::config::ConfigSubcommand::Show(
services::config::ConfigRequest {
report_format: services::config::ReportFormat::Text,
config_path: None,
log_level: None,
},
),
},
)),
services::setup::NAME => Some(RuntimeCommand::Setup(
services::setup::command::SetupCommand {
request: services::setup::SetupRequest {
config_mode: Some(services::setup::SetupMode::Interactive),
install_hooks: true,
hooks_repo_path: None,
context_only: false,
optional_workflows: None,
reconfigure: false,
},
},
)),
services::doctor::NAME => Some(RuntimeCommand::Doctor(
services::doctor::command::DoctorCommand {
request: services::doctor::DoctorRequest {
mode: services::doctor::DoctorMode::Diagnose,
format: services::doctor::DoctorFormat::Text,
},
},
)),
services::hooks::NAME => Some(RuntimeCommand::Hooks(
services::hooks::command::HooksCommand {
subcommand: services::hooks::HookSubcommand::PreCommit,
},
)),
services::bash_policy::NAME => Some(RuntimeCommand::Policy(
services::bash_policy::command::PolicyCommand {
request: services::bash_policy::BashPolicyRequest {
input: services::bash_policy::PolicyInputMode::ClaudePreToolUse,
output: services::bash_policy::PolicyOutputMode::ClaudeHook,
},
},
)),
services::version::NAME => Some(RuntimeCommand::Version(
services::version::command::VersionCommand {
request: services::version::VersionRequest {
format: services::version::VersionFormat::Text,
},
},
)),
services::completion::NAME => Some(RuntimeCommand::Completion(
services::completion::command::CompletionCommand {
request: services::completion::CompletionRequest {
shell: services::completion::CompletionShell::Bash,
},
},
)),
services::sync::NAME => Some(RuntimeCommand::Sync(services::sync::command::SyncCommand {
request: services::sync::SyncRequest {
format: services::output_format::OutputFormat::Text,
},
})),
_ => None,
}
}
66 changes: 32 additions & 34 deletions cli/src/services/parse/command_runtime.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
use crate::{cli_schema, command_surface, services};
use crate::{cli_schema, services};
use clap::{ArgAction, CommandFactory};
use services::command_registry::{CommandRegistry, RuntimeCommand};
use services::command_registry::RuntimeCommand;
use services::error::{CliError, FailureClass};
use services::observability::traits::Logger as LoggerTrait;

pub fn parse_runtime_command<I>(
args: I,
registry: &CommandRegistry,
logger: Option<&dyn LoggerTrait>,
) -> Result<RuntimeCommand, CliError>
where
Expand All @@ -29,34 +28,30 @@ where
}

if args_vec.len() <= 1 {
return registry_command(registry, services::help::NAME);
return Ok(help_command());
}

let cli = match cli_schema::Cli::try_parse_from(&args_vec) {
Ok(cli) => cli,
Err(error) => return handle_clap_error(&args_vec, registry, &error),
Err(error) => return handle_clap_error(&args_vec, &error),
};

let Some(command) = cli.command else {
return registry_command(registry, services::help::NAME);
return Ok(help_command());
};

convert_clap_command(command)
}

fn handle_clap_error(
args: &[String],
registry: &CommandRegistry,
error: &clap::Error,
) -> Result<RuntimeCommand, CliError> {
fn handle_clap_error(args: &[String], error: &clap::Error) -> Result<RuntimeCommand, CliError> {
if error.kind() == clap::error::ErrorKind::DisplayHelp {
if let Some((name, text)) = render_subcommand_help_from_args(args) {
return Ok(RuntimeCommand::HelpText(
services::help::command::HelpTextCommand { name, text },
));
}

return registry_command(registry, services::help::NAME);
return Ok(help_command());
}

if error.kind() == clap::error::ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand {
Expand All @@ -76,28 +71,20 @@ fn handle_clap_error(
));
}

return registry_command(registry, services::help::NAME);
return Ok(help_command());
}

if error.kind() == clap::error::ErrorKind::DisplayVersion {
return registry_command(registry, services::version::NAME);
return convert_clap_command(cli_schema::Commands::Version {
format: services::output_format::OutputFormat::Text,
});
}

Err(classify_clap_error(error))
}

fn registry_command(registry: &CommandRegistry, name: &str) -> Result<RuntimeCommand, CliError> {
if !registry.contains(name) {
return Err(CliError::runtime(anyhow::Error::msg(format!(
"Command '{name}' is not registered. Try: run 'sce --help' to see available commands."
))));
}

services::command_registry::default_runtime_command(name).ok_or_else(|| {
CliError::runtime(anyhow::Error::msg(format!(
"Command '{name}' is not registered. Try: run 'sce --help' to see available commands."
)))
})
fn help_command() -> RuntimeCommand {
RuntimeCommand::Help(services::help::command::HelpCommand)
}

fn classify_clap_error(error: &clap::Error) -> CliError {
Expand Down Expand Up @@ -225,7 +212,11 @@ fn clean_clap_error_message(message: &str, kind: clap::error::ErrorKind) -> Stri
match kind {
ErrorKind::InvalidSubcommand => {
if let Some(subcommand) = extract_quoted_value(message) {
if command_surface::is_known_command(&subcommand) {
if subcommand == services::help::NAME
|| cli_schema::Cli::command()
.find_subcommand(&subcommand)
.is_some()
{
format!(
"Command '{subcommand}' is currently unavailable in this build. Try: run 'sce --help' to see available commands in this build."
)
Expand Down Expand Up @@ -566,12 +557,8 @@ mod tests {
use std::process::ExitCode;

fn parse(args: &[&str]) -> RuntimeCommand {
parse_runtime_command(
args.iter().map(|arg| (*arg).to_string()),
&CommandRegistry::default(),
None,
)
.expect("command should parse")
parse_runtime_command(args.iter().map(|arg| (*arg).to_string()), None)
.expect("command should parse")
}

fn help_payload(command: RuntimeCommand) -> String {
Expand All @@ -582,6 +569,18 @@ mod tests {
}
}

#[test]
fn global_version_flag_uses_version_command() {
let RuntimeCommand::Version(command) = parse(&["sce", "--version"]) else {
panic!("expected version command");
};

assert_eq!(
command.request.format,
services::output_format::OutputFormat::Text
);
}

#[test]
fn sync_parses_to_sync_request_with_default_text_format() {
let command = parse(&["sce", "sync"]);
Expand Down Expand Up @@ -818,7 +817,6 @@ mod tests {

let Err(error) = parse_runtime_command(
["sce", "--not-an-option"].into_iter().map(String::from),
&CommandRegistry::default(),
None,
) else {
panic!("unknown option should remain an error");
Expand Down
Loading
Loading