| 1 | //! `/model` command. |
| 2 | |
| 3 | use codewhale_command_contract::handler::{CommandCapabilities, CommandContexts, CommandHandler}; |
| 4 | use codewhale_command_contract::metadata::{CommandInfo, RegisterCommand}; |
| 5 | use codewhale_command_contract::model_setup::resolve_action; |
| 6 | use codewhale_command_contract::model_setup::{ModelAction, ModelSelection}; |
| 7 | use codewhale_command_contract::outcome::CommandResult; |
| 8 | |
| 9 | const COMMAND_INFO: CommandInfo = CommandInfo { |
| 10 | name: "model", |
| 11 | aliases: &["moxing", "route"], |
| 12 | usage: "/model [name|refresh|router]", |
| 13 | description_key: "cmd_model_description", |
| 14 | }; |
| 15 | |
| 16 | pub struct ModelCmd; |
| 17 | |
| 18 | impl<A: for<'a> TryFrom<ModelAction<'a>, Error = String>> RegisterCommand<CommandResult<A>> |
| 19 | for ModelCmd |
| 20 | { |
| 21 | fn info() -> &'static CommandInfo { |
| 22 | &COMMAND_INFO |
| 23 | } |
| 24 | fn handler() -> CommandHandler<CommandResult<A>> { |
| 25 | CommandHandler::Contextual { |
| 26 | capabilities: CommandCapabilities::MODEL_SELECTION, |
| 27 | handler: model, |
| 28 | } |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | fn model<A: for<'a> TryFrom<ModelAction<'a>, Error = String>>( |
| 33 | mut contexts: CommandContexts<'_>, |
| 34 | arg: Option<&str>, |
| 35 | ) -> CommandResult<A> { |
| 36 | let Some(name) = arg else { |
| 37 | return resolve_action(ModelAction::OpenPicker, None); |
| 38 | }; |
| 39 | let trimmed = name.trim(); |
| 40 | let (head, rest) = trimmed |
| 41 | .split_once(char::is_whitespace) |
| 42 | .unwrap_or((trimmed, "")); |
| 43 | if head.eq_ignore_ascii_case("router") { |
| 44 | return resolve_action(ModelAction::Router(rest), None); |
| 45 | } |
| 46 | if trimmed.eq_ignore_ascii_case("refresh") { |
| 47 | return resolve_action(ModelAction::RefreshCatalog, None); |
| 48 | } |
| 49 | let Some(model) = contexts.take_model_selection() else { |
| 50 | return CommandResult::error("Command capability unavailable: model"); |
| 51 | }; |
| 52 | if name.eq_ignore_ascii_case("save-default") { |
| 53 | return CommandResult::message(model.save_session_route_default()); |
| 54 | } |
| 55 | let selection = if trimmed.eq_ignore_ascii_case("auto") { |
| 56 | ModelSelection::Auto |
| 57 | } else { |
| 58 | ModelSelection::Named(name) |
| 59 | }; |
| 60 | match model.select_session_model(selection) { |
| 61 | Ok(receipt) => resolve_action( |
| 62 | ModelAction::UpdateCompaction(receipt.compaction), |
| 63 | Some(receipt.message), |
| 64 | ), |
| 65 | Err(reason) => CommandResult::error(reason), |
| 66 | } |
| 67 | } |
| 68 |