Merge branch 'feat/cli-ux-progress'
This commit is contained in:
commit
27a1b806cd
44 changed files with 4995 additions and 106 deletions
|
|
@ -15,8 +15,10 @@ path = "src/main.rs"
|
|||
clap.workspace = true
|
||||
dialoguer.workspace = true
|
||||
console.workspace = true
|
||||
crossterm.workspace = true
|
||||
indicatif.workspace = true
|
||||
libc.workspace = true
|
||||
ratatui.workspace = true
|
||||
serde.workspace = true
|
||||
toml.workspace = true
|
||||
aim-core = { path = "../aim-core" }
|
||||
|
|
|
|||
|
|
@ -26,5 +26,6 @@ impl Cli {
|
|||
pub enum Command {
|
||||
Remove { query: String },
|
||||
List,
|
||||
Search { query: String },
|
||||
Update,
|
||||
}
|
||||
|
|
|
|||
130
crates/aim-cli/src/config.rs
Normal file
130
crates/aim-cli/src/config.rs
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
use std::env;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize)]
|
||||
pub struct CliConfig {
|
||||
#[serde(default)]
|
||||
pub search: SearchConfig,
|
||||
#[serde(default)]
|
||||
pub theme: ThemeConfig,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize)]
|
||||
pub struct SearchConfig {
|
||||
#[serde(default = "default_true")]
|
||||
pub bottom_to_top: bool,
|
||||
#[serde(default)]
|
||||
pub skip_confirmation: bool,
|
||||
}
|
||||
|
||||
impl Default for SearchConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
bottom_to_top: true,
|
||||
skip_confirmation: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize)]
|
||||
pub struct ThemeConfig {
|
||||
#[serde(default = "default_accent")]
|
||||
pub accent: String,
|
||||
#[serde(default = "default_accent_secondary")]
|
||||
pub accent_secondary: String,
|
||||
#[serde(default = "default_dim")]
|
||||
pub dim: String,
|
||||
}
|
||||
|
||||
impl Default for ThemeConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
accent: default_accent(),
|
||||
accent_secondary: default_accent_secondary(),
|
||||
dim: default_dim(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load() -> Result<CliConfig, ConfigError> {
|
||||
load_from_path(&default_path())
|
||||
}
|
||||
|
||||
pub fn load_from_path(path: &Path) -> Result<CliConfig, ConfigError> {
|
||||
match fs::read_to_string(path) {
|
||||
Ok(contents) => toml::from_str(&contents).map_err(|source| ConfigError::Parse {
|
||||
path: path.to_path_buf(),
|
||||
source,
|
||||
}),
|
||||
Err(source) if source.kind() == std::io::ErrorKind::NotFound => Ok(CliConfig::default()),
|
||||
Err(source) => Err(ConfigError::Read {
|
||||
path: path.to_path_buf(),
|
||||
source,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn default_path() -> PathBuf {
|
||||
if let Some(path) = env::var_os("AIM_CONFIG_PATH") {
|
||||
return PathBuf::from(path);
|
||||
}
|
||||
|
||||
if let Some(config_home) = env::var_os("XDG_CONFIG_HOME") {
|
||||
return PathBuf::from(config_home).join("aim/config.toml");
|
||||
}
|
||||
|
||||
let home = env::var_os("HOME").unwrap_or_else(|| ".".into());
|
||||
PathBuf::from(home).join(".config/aim/config.toml")
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ConfigError {
|
||||
Read {
|
||||
path: PathBuf,
|
||||
source: std::io::Error,
|
||||
},
|
||||
Parse {
|
||||
path: PathBuf,
|
||||
source: toml::de::Error,
|
||||
},
|
||||
}
|
||||
|
||||
fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn default_accent() -> String {
|
||||
"#b388ff".to_owned()
|
||||
}
|
||||
|
||||
fn default_accent_secondary() -> String {
|
||||
"#d5c2ff".to_owned()
|
||||
}
|
||||
|
||||
fn default_dim() -> String {
|
||||
"#7f7396".to_owned()
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ConfigError {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Read { path, source } => {
|
||||
write!(
|
||||
formatter,
|
||||
"failed to read config {}: {source}",
|
||||
path.display()
|
||||
)
|
||||
}
|
||||
Self::Parse { path, source } => {
|
||||
write!(
|
||||
formatter,
|
||||
"failed to parse config {}: {source}",
|
||||
path.display()
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ConfigError {}
|
||||
|
|
@ -1,6 +1,8 @@
|
|||
pub mod cli;
|
||||
pub mod config;
|
||||
pub mod ui;
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::env;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
|
|
@ -9,12 +11,15 @@ use aim_core::app::add::{
|
|||
resolve_requested_scope,
|
||||
};
|
||||
use aim_core::app::list::{ListRow, build_list_rows};
|
||||
use aim_core::app::progress::{NoopReporter, OperationEvent, OperationStage, ProgressReporter};
|
||||
use aim_core::app::progress::{
|
||||
NoopReporter, OperationEvent, OperationKind, OperationStage, ProgressReporter,
|
||||
};
|
||||
use aim_core::app::remove::{RemovalResult, remove_registered_app_with_reporter};
|
||||
use aim_core::app::search::build_search_results;
|
||||
use aim_core::app::update::{build_update_plan, execute_updates_with_reporter};
|
||||
use aim_core::domain::app::AppRecord;
|
||||
use aim_core::domain::search::{SearchQuery, SearchResults};
|
||||
use aim_core::domain::update::{UpdateExecutionResult, UpdatePlan};
|
||||
use aim_core::registry::model::Registry;
|
||||
use aim_core::registry::store::RegistryStore;
|
||||
|
||||
pub use cli::args::Cli;
|
||||
|
|
@ -48,30 +53,37 @@ pub fn dispatch_with_reporter(
|
|||
cli::args::Command::Remove { query } => {
|
||||
let removal =
|
||||
remove_registered_app_with_reporter(&query, &apps, &install_home, reporter)?;
|
||||
let remaining_apps = removal.remaining_apps.clone();
|
||||
reporter.report(&OperationEvent::StageChanged {
|
||||
stage: OperationStage::SaveRegistry,
|
||||
message: "saving registry".to_owned(),
|
||||
});
|
||||
store.save(&Registry {
|
||||
version: registry.version,
|
||||
apps: remaining_apps,
|
||||
store.mutate_exclusive(|latest| {
|
||||
remove_app_record(&mut latest.apps, &removal.removed.stable_id);
|
||||
})?;
|
||||
reporter.report(&OperationEvent::Finished {
|
||||
summary: format!("removed {}", removal.removed.stable_id),
|
||||
});
|
||||
Ok(DispatchResult::Removed(Box::new(removal)))
|
||||
}
|
||||
cli::args::Command::Search { query } => {
|
||||
reporter.report(&OperationEvent::Started {
|
||||
kind: OperationKind::Search,
|
||||
label: query.clone(),
|
||||
});
|
||||
let results = build_search_results(&SearchQuery::new(&query), &apps)?;
|
||||
reporter.report(&OperationEvent::Finished {
|
||||
summary: format!("search complete: {} remote hits", results.remote_hits.len()),
|
||||
});
|
||||
Ok(DispatchResult::Search(results))
|
||||
}
|
||||
cli::args::Command::Update => {
|
||||
let updates = execute_updates_with_reporter(&apps, &install_home, reporter)?;
|
||||
let updated_apps = updates.apps.clone();
|
||||
reporter.report(&OperationEvent::StageChanged {
|
||||
stage: OperationStage::SaveRegistry,
|
||||
message: "saving registry".to_owned(),
|
||||
});
|
||||
store.save(&Registry {
|
||||
version: registry.version,
|
||||
apps: updated_apps,
|
||||
store.mutate_exclusive(|latest| {
|
||||
merge_updated_app_records(&mut latest.apps, &apps, &updates.apps);
|
||||
})?;
|
||||
reporter.report(&OperationEvent::Finished {
|
||||
summary: format!(
|
||||
|
|
@ -100,15 +112,12 @@ pub fn dispatch_with_reporter(
|
|||
|
||||
let installed =
|
||||
install_app_with_reporter(&query, &plan, &install_home, requested_scope, reporter)?;
|
||||
let mut updated_apps = registry.apps.clone();
|
||||
upsert_app_record(&mut updated_apps, installed.record.clone());
|
||||
reporter.report(&OperationEvent::StageChanged {
|
||||
stage: OperationStage::SaveRegistry,
|
||||
message: "saving registry".to_owned(),
|
||||
});
|
||||
store.save(&Registry {
|
||||
version: registry.version,
|
||||
apps: updated_apps,
|
||||
store.mutate_exclusive(|latest| {
|
||||
upsert_app_record(&mut latest.apps, installed.record.clone());
|
||||
})?;
|
||||
reporter.report(&OperationEvent::Finished {
|
||||
summary: format!("installed {}", installed.record.stable_id),
|
||||
|
|
@ -121,7 +130,11 @@ pub fn dispatch_with_reporter(
|
|||
}
|
||||
|
||||
pub fn render(result: &DispatchResult) -> String {
|
||||
ui::render::render_dispatch_result(result)
|
||||
render_with_config(result, &config::CliConfig::default())
|
||||
}
|
||||
|
||||
pub fn render_with_config(result: &DispatchResult, config: &config::CliConfig) -> String {
|
||||
ui::render::render_dispatch_result_with_config(result, config)
|
||||
}
|
||||
|
||||
fn registry_path() -> PathBuf {
|
||||
|
|
@ -139,6 +152,7 @@ pub enum DispatchResult {
|
|||
List(Vec<ListRow>),
|
||||
PendingAdd(Box<AddPlan>),
|
||||
Removed(Box<RemovalResult>),
|
||||
Search(SearchResults),
|
||||
UpdatePlan(UpdatePlan),
|
||||
Updated(Box<UpdateExecutionResult>),
|
||||
Noop,
|
||||
|
|
@ -151,6 +165,7 @@ pub enum DispatchError {
|
|||
Prompt(ui::prompt::PromptError),
|
||||
RemovePlan(aim_core::app::remove::RemoveRegisteredAppError),
|
||||
Registry(aim_core::registry::store::RegistryStoreError),
|
||||
Search(aim_core::app::search::SearchError),
|
||||
UpdatePlan(aim_core::app::update::BuildUpdatePlanError),
|
||||
UpdateExecution(aim_core::app::update::ExecuteUpdatesError),
|
||||
}
|
||||
|
|
@ -190,6 +205,7 @@ impl std::fmt::Display for DispatchError {
|
|||
Self::Prompt(error) => write!(f, "prompt failed: {error:?}"),
|
||||
Self::RemovePlan(error) => write!(f, "remove failed: {error:?}"),
|
||||
Self::Registry(error) => write!(f, "registry failed: {error:?}"),
|
||||
Self::Search(error) => write!(f, "search failed: {error:?}"),
|
||||
Self::UpdatePlan(error) => write!(f, "update planning failed: {error:?}"),
|
||||
Self::UpdateExecution(error) => write!(f, "update execution failed: {error:?}"),
|
||||
}
|
||||
|
|
@ -238,6 +254,12 @@ impl From<aim_core::registry::store::RegistryStoreError> for DispatchError {
|
|||
}
|
||||
}
|
||||
|
||||
impl From<aim_core::app::search::SearchError> for DispatchError {
|
||||
fn from(value: aim_core::app::search::SearchError) -> Self {
|
||||
Self::Search(value)
|
||||
}
|
||||
}
|
||||
|
||||
fn upsert_app_record(apps: &mut Vec<AppRecord>, record: AppRecord) {
|
||||
if let Some(existing) = apps
|
||||
.iter_mut()
|
||||
|
|
@ -250,6 +272,33 @@ fn upsert_app_record(apps: &mut Vec<AppRecord>, record: AppRecord) {
|
|||
apps.push(record);
|
||||
}
|
||||
|
||||
fn remove_app_record(apps: &mut Vec<AppRecord>, stable_id: &str) {
|
||||
apps.retain(|app| app.stable_id != stable_id);
|
||||
}
|
||||
|
||||
fn merge_updated_app_records(
|
||||
latest_apps: &mut [AppRecord],
|
||||
original_apps: &[AppRecord],
|
||||
updated_apps: &[AppRecord],
|
||||
) {
|
||||
let original_ids = original_apps
|
||||
.iter()
|
||||
.map(|app| app.stable_id.as_str())
|
||||
.collect::<HashSet<_>>();
|
||||
let updated_by_id = updated_apps
|
||||
.iter()
|
||||
.map(|app| (app.stable_id.as_str(), app.clone()))
|
||||
.collect::<HashMap<_, _>>();
|
||||
|
||||
for app in latest_apps.iter_mut() {
|
||||
if original_ids.contains(app.stable_id.as_str())
|
||||
&& let Some(updated) = updated_by_id.get(app.stable_id.as_str())
|
||||
{
|
||||
*app = updated.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn install_home(registry_path: &Path) -> PathBuf {
|
||||
if env::var_os("AIM_REGISTRY_PATH").is_some() {
|
||||
return registry_path
|
||||
|
|
|
|||
|
|
@ -1,20 +1,28 @@
|
|||
fn main() {
|
||||
let loaded_config = aim_cli::cli::config::AppConfig::load();
|
||||
let loaded_theme_config = aim_cli::cli::config::AppConfig::load();
|
||||
aim_cli::ui::theme::set_active_theme(aim_cli::ui::theme::resolve_theme(
|
||||
&loaded_config.config.theme,
|
||||
&loaded_theme_config.config.theme,
|
||||
));
|
||||
for warning in loaded_config.warnings {
|
||||
for warning in loaded_theme_config.warnings {
|
||||
eprintln!(
|
||||
"{}",
|
||||
aim_cli::ui::theme::warning_text(&format!("Config warning: {warning}"))
|
||||
);
|
||||
}
|
||||
|
||||
let config = match aim_cli::config::load() {
|
||||
Ok(config) => config,
|
||||
Err(error) => {
|
||||
eprintln!("{error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
let cli = aim_cli::parse();
|
||||
let mut reporter = aim_cli::ui::progress::TerminalProgressReporter::stderr();
|
||||
match aim_cli::dispatch_with_reporter(cli, &mut reporter) {
|
||||
Ok(result) => {
|
||||
let output = aim_cli::render(&result);
|
||||
let output = aim_cli::render_with_config(&result, &config);
|
||||
if !output.is_empty() {
|
||||
if reporter.emitted_output() {
|
||||
println!();
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
pub mod progress;
|
||||
pub mod prompt;
|
||||
pub mod render;
|
||||
pub mod search_browser;
|
||||
pub mod theme;
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ pub fn byte_style() -> ProgressStyle {
|
|||
pub fn operation_label(kind: OperationKind) -> &'static str {
|
||||
match kind {
|
||||
OperationKind::Add => "Installing",
|
||||
OperationKind::Search => "Searching",
|
||||
OperationKind::UpdateBatch => "Updating",
|
||||
OperationKind::UpdateItem => "Updating",
|
||||
OperationKind::Remove => "Removing",
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
use aim_core::app::add::AddPlan;
|
||||
use aim_core::domain::search::SearchResults;
|
||||
use aim_core::domain::update::UpdateExecutionStatus;
|
||||
|
||||
use crate::DispatchResult;
|
||||
use crate::config::CliConfig;
|
||||
|
||||
pub fn render_update_summary(total: usize, selected: usize, failed: usize) -> String {
|
||||
[
|
||||
|
|
@ -14,11 +16,16 @@ pub fn render_update_summary(total: usize, selected: usize, failed: usize) -> St
|
|||
}
|
||||
|
||||
pub fn render_dispatch_result(result: &DispatchResult) -> String {
|
||||
render_dispatch_result_with_config(result, &CliConfig::default())
|
||||
}
|
||||
|
||||
pub fn render_dispatch_result_with_config(result: &DispatchResult, config: &CliConfig) -> String {
|
||||
match result {
|
||||
DispatchResult::Added(added) => render_added_app(added),
|
||||
DispatchResult::List(rows) => render_list(rows),
|
||||
DispatchResult::PendingAdd(plan) => render_pending_add(plan),
|
||||
DispatchResult::Removed(removed) => render_removed_app(removed),
|
||||
DispatchResult::Search(results) => render_search_results_with_config(results, config),
|
||||
DispatchResult::UpdatePlan(plan) => render_update_plan(plan),
|
||||
DispatchResult::Updated(result) => render_updated_apps(result),
|
||||
DispatchResult::Noop => String::new(),
|
||||
|
|
@ -207,6 +214,67 @@ fn install_file_paths(added: &aim_core::app::add::InstalledApp) -> Vec<String> {
|
|||
.collect()
|
||||
}
|
||||
|
||||
fn render_search_results(results: &SearchResults) -> String {
|
||||
let mut lines = vec![crate::ui::theme::heading("Search Results")];
|
||||
|
||||
lines.push(crate::ui::theme::heading("Remote Results"));
|
||||
if results.remote_hits.is_empty() {
|
||||
lines.push(crate::ui::theme::muted("No remote matches"));
|
||||
} else {
|
||||
for hit in &results.remote_hits {
|
||||
lines.push(crate::ui::theme::bullet(&format!(
|
||||
"[{}] {}",
|
||||
hit.provider_id, hit.display_name
|
||||
)));
|
||||
lines.push(format!("Install query: {}", hit.install_query));
|
||||
lines.push(format!("Source: {}", hit.source_locator));
|
||||
if let Some(description) = &hit.description {
|
||||
lines.push(format!("Description: {description}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
lines.push(crate::ui::theme::heading("Installed Matches"));
|
||||
if results.installed_matches.is_empty() {
|
||||
lines.push(crate::ui::theme::muted("No installed matches"));
|
||||
} else {
|
||||
for app in &results.installed_matches {
|
||||
lines.push(crate::ui::theme::bullet(&format!(
|
||||
"{} ({})",
|
||||
app.display_name, app.stable_id
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
if !results.warnings.is_empty() {
|
||||
lines.push(crate::ui::theme::heading("Warnings"));
|
||||
for warning in &results.warnings {
|
||||
match warning.provider_id.as_deref() {
|
||||
Some(provider_id) => {
|
||||
lines.push(format!("Warning: {provider_id}: {}", warning.message))
|
||||
}
|
||||
None => lines.push(format!("Warning: {}", warning.message)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
lines.join("\n")
|
||||
}
|
||||
|
||||
fn render_search_results_with_config(results: &SearchResults, config: &CliConfig) -> String {
|
||||
if crate::ui::search_browser::can_launch(results) {
|
||||
match crate::ui::search_browser::run(results, config) {
|
||||
Ok(Some(selection)) => {
|
||||
return crate::ui::search_browser::render_confirmation_summary(&selection.rows);
|
||||
}
|
||||
Ok(None) => return String::new(),
|
||||
Err(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
render_search_results(results)
|
||||
}
|
||||
|
||||
fn render_updated_apps(result: &aim_core::domain::update::UpdateExecutionResult) -> String {
|
||||
let mut lines = vec![
|
||||
crate::ui::theme::heading("Update Summary"),
|
||||
|
|
|
|||
848
crates/aim-cli/src/ui/search_browser.rs
Normal file
848
crates/aim-cli/src/ui/search_browser.rs
Normal file
|
|
@ -0,0 +1,848 @@
|
|||
use std::collections::BTreeSet;
|
||||
use std::io::IsTerminal;
|
||||
use std::time::Duration;
|
||||
|
||||
use aim_core::domain::search::{SearchInstallStatus, SearchResult, SearchResults};
|
||||
use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
|
||||
use crossterm::execute;
|
||||
use crossterm::terminal::{
|
||||
EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
|
||||
};
|
||||
use ratatui::backend::CrosstermBackend;
|
||||
use ratatui::layout::{Alignment, Constraint, Direction, Layout, Rect};
|
||||
use ratatui::style::Modifier;
|
||||
use ratatui::text::{Line, Span};
|
||||
use ratatui::widgets::{Clear, List, ListItem, Paragraph, Wrap};
|
||||
use ratatui::{Frame, Terminal};
|
||||
|
||||
use crate::config::{CliConfig, SearchConfig};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum BrowserPhase {
|
||||
Browsing,
|
||||
Confirming,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct SearchRow {
|
||||
pub status: SearchInstallStatus,
|
||||
pub provider_id: String,
|
||||
pub display_name: String,
|
||||
pub description: Option<String>,
|
||||
pub install_query: String,
|
||||
pub version: Option<String>,
|
||||
pub selectable: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct SearchSelection {
|
||||
pub rows: Vec<SearchRow>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum SubmitAction {
|
||||
None,
|
||||
Confirming,
|
||||
Confirmed(SearchSelection),
|
||||
}
|
||||
|
||||
pub struct SearchBrowserState {
|
||||
rows: Vec<SearchRow>,
|
||||
query_text: String,
|
||||
selected: BTreeSet<usize>,
|
||||
cursor: usize,
|
||||
page_size: usize,
|
||||
phase: BrowserPhase,
|
||||
numeric_buffer: String,
|
||||
status_message: Option<String>,
|
||||
}
|
||||
|
||||
impl SearchBrowserState {
|
||||
pub fn new(results: Vec<SearchResult>, config: SearchConfig, page_size: usize) -> Self {
|
||||
Self::new_with_query(results, String::new(), config, page_size)
|
||||
}
|
||||
|
||||
pub fn new_with_query(
|
||||
results: Vec<SearchResult>,
|
||||
query_text: String,
|
||||
config: SearchConfig,
|
||||
page_size: usize,
|
||||
) -> Self {
|
||||
let mut rows = results
|
||||
.into_iter()
|
||||
.map(|result| SearchRow {
|
||||
selectable: !matches!(result.install_status, SearchInstallStatus::Installed { .. }),
|
||||
status: result.install_status,
|
||||
provider_id: result.provider_id,
|
||||
display_name: result.display_name,
|
||||
description: result.description,
|
||||
install_query: result.install_query,
|
||||
version: result.version,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
if config.bottom_to_top {
|
||||
rows.reverse();
|
||||
}
|
||||
|
||||
Self {
|
||||
rows,
|
||||
query_text,
|
||||
selected: BTreeSet::new(),
|
||||
cursor: 0,
|
||||
page_size: page_size.max(1),
|
||||
phase: BrowserPhase::Browsing,
|
||||
numeric_buffer: String::new(),
|
||||
status_message: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ordered_rows(&self) -> &[SearchRow] {
|
||||
&self.rows
|
||||
}
|
||||
|
||||
pub fn query_text(&self) -> &str {
|
||||
&self.query_text
|
||||
}
|
||||
|
||||
pub fn selected_rows(&self) -> Vec<&SearchRow> {
|
||||
self.selected
|
||||
.iter()
|
||||
.filter_map(|index| self.rows.get(*index))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn selected_rows_owned(&self) -> Vec<SearchRow> {
|
||||
self.selected_rows().into_iter().cloned().collect()
|
||||
}
|
||||
|
||||
pub fn selection_expression(&self) -> String {
|
||||
compress_selection_ranges(
|
||||
&self
|
||||
.selected
|
||||
.iter()
|
||||
.map(|index| index + 1)
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn selection_prompt_value(&self) -> String {
|
||||
if self.numeric_buffer.is_empty() {
|
||||
self.selection_expression()
|
||||
} else {
|
||||
self.numeric_buffer.clone()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn phase(&self) -> BrowserPhase {
|
||||
self.phase
|
||||
}
|
||||
|
||||
pub fn cursor_position(&self) -> usize {
|
||||
self.cursor
|
||||
}
|
||||
|
||||
pub fn selection_count(&self) -> usize {
|
||||
self.selected.len()
|
||||
}
|
||||
|
||||
pub fn has_selection(&self) -> bool {
|
||||
!self.selected.is_empty()
|
||||
}
|
||||
|
||||
pub fn numeric_buffer(&self) -> &str {
|
||||
&self.numeric_buffer
|
||||
}
|
||||
|
||||
pub fn status_message(&self) -> Option<&str> {
|
||||
self.status_message.as_deref()
|
||||
}
|
||||
|
||||
pub fn page_bounds(&self) -> (usize, usize) {
|
||||
let start = (self.cursor / self.page_size) * self.page_size;
|
||||
let end = (start + self.page_size).min(self.rows.len());
|
||||
(start, end)
|
||||
}
|
||||
|
||||
pub fn move_next(&mut self) {
|
||||
if self.cursor + 1 < self.rows.len() {
|
||||
self.cursor += 1;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn move_previous(&mut self) {
|
||||
if self.cursor > 0 {
|
||||
self.cursor -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn move_to_top(&mut self) {
|
||||
self.cursor = 0;
|
||||
}
|
||||
|
||||
pub fn move_to_bottom(&mut self) {
|
||||
if !self.rows.is_empty() {
|
||||
self.cursor = self.rows.len() - 1;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn page_down(&mut self) {
|
||||
if self.rows.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let next_page = ((self.cursor / self.page_size) + 1) * self.page_size;
|
||||
self.cursor = next_page.min(self.rows.len().saturating_sub(1));
|
||||
}
|
||||
|
||||
pub fn page_up(&mut self) {
|
||||
self.cursor = self.cursor.saturating_sub(self.cursor % self.page_size);
|
||||
self.cursor = self.cursor.saturating_sub(self.page_size);
|
||||
}
|
||||
|
||||
pub fn toggle_current_selection(&mut self) {
|
||||
if self
|
||||
.rows
|
||||
.get(self.cursor)
|
||||
.is_some_and(|row| !row.selectable)
|
||||
{
|
||||
self.set_status_message("installed result is not selectable");
|
||||
return;
|
||||
}
|
||||
|
||||
if !self.selected.insert(self.cursor) {
|
||||
self.selected.remove(&self.cursor);
|
||||
}
|
||||
|
||||
self.clear_status_message();
|
||||
}
|
||||
|
||||
pub fn enter_confirmation(&mut self) -> bool {
|
||||
if self.selected.is_empty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
self.phase = BrowserPhase::Confirming;
|
||||
true
|
||||
}
|
||||
|
||||
pub fn cancel_confirmation(&mut self) {
|
||||
self.phase = BrowserPhase::Browsing;
|
||||
}
|
||||
|
||||
pub fn apply_numeric_selection(&mut self, input: &str) -> Result<(), String> {
|
||||
let parsed = parse_selection(input, self.rows.len())?;
|
||||
self.selected = parsed
|
||||
.into_iter()
|
||||
.filter(|index| self.rows.get(*index).is_some_and(|row| row.selectable))
|
||||
.collect();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn submit_selection(&mut self, skip_confirmation: bool) -> SubmitAction {
|
||||
if !self.has_selection() {
|
||||
self.set_status_message("select at least one result");
|
||||
return SubmitAction::None;
|
||||
}
|
||||
|
||||
if skip_confirmation {
|
||||
return SubmitAction::Confirmed(SearchSelection {
|
||||
rows: self.selected_rows_owned(),
|
||||
});
|
||||
}
|
||||
|
||||
self.enter_confirmation();
|
||||
SubmitAction::Confirming
|
||||
}
|
||||
|
||||
pub fn push_numeric_input(&mut self, character: char) {
|
||||
self.numeric_buffer.push(character);
|
||||
self.refresh_selection_from_numeric_buffer();
|
||||
}
|
||||
|
||||
pub fn pop_numeric_input(&mut self) {
|
||||
self.numeric_buffer.pop();
|
||||
self.refresh_selection_from_numeric_buffer();
|
||||
}
|
||||
|
||||
pub fn clear_numeric_input(&mut self) {
|
||||
self.numeric_buffer.clear();
|
||||
}
|
||||
|
||||
pub fn set_status_message(&mut self, message: impl Into<String>) {
|
||||
self.status_message = Some(message.into());
|
||||
}
|
||||
|
||||
pub fn clear_status_message(&mut self) {
|
||||
self.status_message = None;
|
||||
}
|
||||
|
||||
fn is_selected(&self, index: usize) -> bool {
|
||||
self.selected.contains(&index)
|
||||
}
|
||||
|
||||
fn refresh_selection_from_numeric_buffer(&mut self) {
|
||||
let trimmed = self.numeric_buffer.trim();
|
||||
if trimmed.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Ok(parsed) = parse_selection(trimmed, self.rows.len()) {
|
||||
self.selected = parsed
|
||||
.into_iter()
|
||||
.filter(|index| self.rows.get(*index).is_some_and(|row| row.selectable))
|
||||
.collect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum SearchBrowserError {
|
||||
Terminal(std::io::Error),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct HighlightSegment {
|
||||
pub text: String,
|
||||
pub is_match: bool,
|
||||
}
|
||||
|
||||
pub fn can_launch(results: &SearchResults) -> bool {
|
||||
!results.remote_hits.is_empty()
|
||||
&& std::io::stdin().is_terminal()
|
||||
&& std::io::stdout().is_terminal()
|
||||
}
|
||||
|
||||
pub fn run(
|
||||
results: &SearchResults,
|
||||
config: &CliConfig,
|
||||
) -> Result<Option<SearchSelection>, SearchBrowserError> {
|
||||
let mut stdout = std::io::stdout();
|
||||
enable_raw_mode().map_err(SearchBrowserError::Terminal)?;
|
||||
execute!(stdout, EnterAlternateScreen).map_err(SearchBrowserError::Terminal)?;
|
||||
|
||||
let backend = CrosstermBackend::new(stdout);
|
||||
let mut terminal = Terminal::new(backend).map_err(SearchBrowserError::Terminal)?;
|
||||
let outcome = run_loop(&mut terminal, results, config);
|
||||
|
||||
let leave_screen = execute!(terminal.backend_mut(), LeaveAlternateScreen);
|
||||
let show_cursor = terminal.show_cursor();
|
||||
let disable_raw = disable_raw_mode();
|
||||
|
||||
if let Err(error) = leave_screen {
|
||||
return Err(SearchBrowserError::Terminal(error));
|
||||
}
|
||||
if let Err(error) = show_cursor {
|
||||
return Err(SearchBrowserError::Terminal(error));
|
||||
}
|
||||
if let Err(error) = disable_raw {
|
||||
return Err(SearchBrowserError::Terminal(error));
|
||||
}
|
||||
|
||||
outcome
|
||||
}
|
||||
|
||||
pub fn format_search_row(
|
||||
index: usize,
|
||||
row: &SearchRow,
|
||||
selected: bool,
|
||||
active: bool,
|
||||
width: usize,
|
||||
) -> String {
|
||||
let cursor = if active { ">" } else { " " };
|
||||
let marker = if selected { "[*]" } else { "[ ]" };
|
||||
let status = match &row.status {
|
||||
SearchInstallStatus::Available => "",
|
||||
SearchInstallStatus::Installed { .. } => "[installed] ",
|
||||
SearchInstallStatus::UpdateAvailable { .. } => "[update] ",
|
||||
};
|
||||
let version = row
|
||||
.version
|
||||
.as_deref()
|
||||
.map(|value| format!(" v{value}"))
|
||||
.unwrap_or_default();
|
||||
let first_line = format!(
|
||||
"{cursor}{marker} {index:>2}. {status}{}{version}",
|
||||
row.display_name
|
||||
);
|
||||
let second_line = match row.description.as_deref() {
|
||||
Some(description) => format!("{} - {description}", row.provider_id),
|
||||
None => row.provider_id.clone(),
|
||||
};
|
||||
format!(
|
||||
"{}\n{}",
|
||||
truncate_line(&first_line, width),
|
||||
truncate_line(&format!(" {second_line}"), width)
|
||||
)
|
||||
}
|
||||
|
||||
pub fn highlight_segments(text: &str, query: &str) -> Vec<HighlightSegment> {
|
||||
let normalized_query = query.trim().to_ascii_lowercase();
|
||||
if normalized_query.is_empty() {
|
||||
return vec![HighlightSegment {
|
||||
text: text.to_owned(),
|
||||
is_match: false,
|
||||
}];
|
||||
}
|
||||
|
||||
let normalized_text = text.to_ascii_lowercase();
|
||||
let mut start = 0;
|
||||
let mut segments = Vec::new();
|
||||
|
||||
while let Some(relative_match) = normalized_text[start..].find(&normalized_query) {
|
||||
let match_start = start + relative_match;
|
||||
let match_end = match_start + normalized_query.len();
|
||||
|
||||
if match_start > start {
|
||||
segments.push(HighlightSegment {
|
||||
text: text[start..match_start].to_owned(),
|
||||
is_match: false,
|
||||
});
|
||||
}
|
||||
|
||||
segments.push(HighlightSegment {
|
||||
text: text[match_start..match_end].to_owned(),
|
||||
is_match: true,
|
||||
});
|
||||
start = match_end;
|
||||
}
|
||||
|
||||
if start < text.len() {
|
||||
segments.push(HighlightSegment {
|
||||
text: text[start..].to_owned(),
|
||||
is_match: false,
|
||||
});
|
||||
}
|
||||
|
||||
if segments.is_empty() {
|
||||
segments.push(HighlightSegment {
|
||||
text: text.to_owned(),
|
||||
is_match: false,
|
||||
});
|
||||
}
|
||||
|
||||
segments
|
||||
}
|
||||
|
||||
pub fn render_confirmation_summary(rows: &[SearchRow]) -> String {
|
||||
let mut lines = vec![crate::ui::theme::heading("Confirm Search Selection")];
|
||||
lines.push(format!("selected results: {}", rows.len()));
|
||||
for row in rows {
|
||||
lines.push(format!(
|
||||
"{} [{}] {}",
|
||||
crate::ui::theme::bullet(&row.display_name),
|
||||
row.provider_id,
|
||||
row.version
|
||||
.as_deref()
|
||||
.map(|value| format!("{} (v{value})", row.install_query))
|
||||
.unwrap_or_else(|| row.install_query.clone())
|
||||
));
|
||||
}
|
||||
lines.join("\n")
|
||||
}
|
||||
|
||||
fn run_loop(
|
||||
terminal: &mut Terminal<CrosstermBackend<std::io::Stdout>>,
|
||||
results: &SearchResults,
|
||||
config: &CliConfig,
|
||||
) -> Result<Option<SearchSelection>, SearchBrowserError> {
|
||||
let mut state = SearchBrowserState::new_with_query(
|
||||
results.remote_hits.clone(),
|
||||
results.query_text.clone(),
|
||||
config.search.clone(),
|
||||
10,
|
||||
);
|
||||
|
||||
loop {
|
||||
terminal
|
||||
.draw(|frame| draw_browser(frame, &state, results, config))
|
||||
.map_err(SearchBrowserError::Terminal)?;
|
||||
|
||||
if !event::poll(Duration::from_millis(250)).map_err(SearchBrowserError::Terminal)? {
|
||||
continue;
|
||||
}
|
||||
|
||||
let Event::Key(key) = event::read().map_err(SearchBrowserError::Terminal)? else {
|
||||
continue;
|
||||
};
|
||||
|
||||
if key.kind != KeyEventKind::Press {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(outcome) = handle_key_event(&mut state, key.code, key.modifiers, &config.search)
|
||||
{
|
||||
return Ok(outcome);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_browser(
|
||||
frame: &mut Frame<'_>,
|
||||
state: &SearchBrowserState,
|
||||
_results: &SearchResults,
|
||||
config: &CliConfig,
|
||||
) {
|
||||
let palette = crate::ui::theme::search_browser_palette(&config.theme);
|
||||
|
||||
if state.phase() == BrowserPhase::Confirming {
|
||||
let area = centered_rect(frame.area(), 70, 40);
|
||||
frame.render_widget(Clear, area);
|
||||
frame.render_widget(
|
||||
Paragraph::new(render_confirmation_summary(&state.selected_rows_owned()))
|
||||
.style(palette.text_style()),
|
||||
area,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let layout = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([
|
||||
Constraint::Length(4),
|
||||
Constraint::Min(5),
|
||||
Constraint::Length(3),
|
||||
])
|
||||
.split(frame.area());
|
||||
|
||||
let header = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([Constraint::Length(2), Constraint::Min(1)])
|
||||
.split(layout[0]);
|
||||
let header_top = Layout::default()
|
||||
.direction(Direction::Horizontal)
|
||||
.constraints([Constraint::Min(10), Constraint::Length(24)])
|
||||
.split(header[0]);
|
||||
let (start, end) = state.page_bounds();
|
||||
|
||||
frame.render_widget(
|
||||
Paragraph::new(Line::styled("Search Results", palette.heading_style())),
|
||||
header_top[0],
|
||||
);
|
||||
frame.render_widget(
|
||||
Paragraph::new(vec![
|
||||
Line::styled(
|
||||
format!(
|
||||
"Showing {}-{} of {}",
|
||||
start + 1,
|
||||
end,
|
||||
state.ordered_rows().len()
|
||||
),
|
||||
palette.muted_style(),
|
||||
),
|
||||
Line::styled(
|
||||
format!("Selected {}", state.selection_count()),
|
||||
palette.muted_style(),
|
||||
),
|
||||
])
|
||||
.alignment(Alignment::Right),
|
||||
header_top[1],
|
||||
);
|
||||
frame.render_widget(
|
||||
Paragraph::new(Line::styled(
|
||||
"Enter confirm Space toggle j/k move PgUp/PgDn page g/G jump q cancel",
|
||||
palette.hint_style(),
|
||||
))
|
||||
.wrap(Wrap { trim: true }),
|
||||
header[1],
|
||||
);
|
||||
|
||||
let width = layout[1].width as usize;
|
||||
let items = state.ordered_rows()[start..end]
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(offset, row)| {
|
||||
let absolute = start + offset;
|
||||
ListItem::new(render_search_row_lines(
|
||||
absolute + 1,
|
||||
row,
|
||||
state.is_selected(absolute),
|
||||
state.cursor_position() == absolute,
|
||||
width,
|
||||
palette,
|
||||
state.query_text(),
|
||||
))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
frame.render_widget(List::new(items), layout[1]);
|
||||
|
||||
let status = state.status_message().unwrap_or("");
|
||||
frame.render_widget(
|
||||
Paragraph::new(vec![
|
||||
Line::from(vec![
|
||||
Span::styled("Apps to install: ", palette.text_style()),
|
||||
Span::styled(state.selection_prompt_value(), palette.text_style()),
|
||||
Span::styled(" eg. 1 2 3, 1-3", palette.hint_style()),
|
||||
]),
|
||||
Line::styled(status, palette.muted_style()),
|
||||
])
|
||||
.wrap(Wrap { trim: true }),
|
||||
layout[2],
|
||||
);
|
||||
}
|
||||
|
||||
fn render_search_row_lines(
|
||||
index: usize,
|
||||
row: &SearchRow,
|
||||
selected: bool,
|
||||
active: bool,
|
||||
width: usize,
|
||||
palette: crate::ui::theme::SearchBrowserPalette,
|
||||
query_text: &str,
|
||||
) -> Vec<Line<'static>> {
|
||||
let cursor = if active { ">" } else { " " };
|
||||
let checkbox = if selected { "[*]" } else { "[ ]" };
|
||||
let checkbox_style = if selected {
|
||||
palette.checkbox_selected_style()
|
||||
} else {
|
||||
palette.checkbox_idle_style()
|
||||
};
|
||||
let name_style = if !row.selectable {
|
||||
palette.disabled_style()
|
||||
} else if active {
|
||||
palette.active_name_style()
|
||||
} else {
|
||||
palette.text_style()
|
||||
};
|
||||
let index_style = if row.selectable {
|
||||
palette.text_style()
|
||||
} else {
|
||||
palette.disabled_style()
|
||||
};
|
||||
|
||||
let mut first_line = vec![
|
||||
Span::styled(cursor.to_owned(), palette.cursor_style()),
|
||||
Span::raw(" "),
|
||||
Span::styled(checkbox.to_owned(), checkbox_style),
|
||||
Span::styled(format!(" {index:>2}. "), index_style),
|
||||
];
|
||||
|
||||
match row.status {
|
||||
SearchInstallStatus::Available => {}
|
||||
SearchInstallStatus::Installed { .. } => {
|
||||
first_line.push(Span::styled(
|
||||
"[installed] ".to_owned(),
|
||||
name_style.add_modifier(Modifier::BOLD),
|
||||
));
|
||||
}
|
||||
SearchInstallStatus::UpdateAvailable { .. } => {
|
||||
first_line.push(Span::styled(
|
||||
"[update] ".to_owned(),
|
||||
name_style.add_modifier(Modifier::BOLD),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
push_highlighted_spans(&mut first_line, &row.display_name, query_text, name_style);
|
||||
if let Some(version) = &row.version {
|
||||
first_line.push(Span::raw(" "));
|
||||
first_line.push(Span::styled(format!("v{version}"), palette.version_style()));
|
||||
}
|
||||
|
||||
let detail_text = match row.description.as_deref() {
|
||||
Some(description) => format!("{} - {description}", row.provider_id),
|
||||
None => row.provider_id.clone(),
|
||||
};
|
||||
let detail_text = truncate_line(&detail_text, width.saturating_sub(7));
|
||||
let provider_len = row.provider_id.len().min(detail_text.len());
|
||||
let (provider_text, remainder) = detail_text.split_at(provider_len);
|
||||
let mut second_line = vec![Span::raw(" ")];
|
||||
second_line.push(Span::styled(
|
||||
provider_text.to_owned(),
|
||||
palette.dim_style().add_modifier(Modifier::BOLD),
|
||||
));
|
||||
if !remainder.is_empty() {
|
||||
push_highlighted_spans(&mut second_line, remainder, query_text, palette.dim_style());
|
||||
}
|
||||
|
||||
vec![Line::from(first_line), Line::from(second_line)]
|
||||
}
|
||||
|
||||
fn handle_key_event(
|
||||
state: &mut SearchBrowserState,
|
||||
code: KeyCode,
|
||||
modifiers: KeyModifiers,
|
||||
config: &SearchConfig,
|
||||
) -> Option<Option<SearchSelection>> {
|
||||
if state.phase() == BrowserPhase::Confirming {
|
||||
return match code {
|
||||
KeyCode::Enter | KeyCode::Char('y') => Some(Some(SearchSelection {
|
||||
rows: state.selected_rows_owned(),
|
||||
})),
|
||||
KeyCode::Esc | KeyCode::Char('q') | KeyCode::Char('n') => {
|
||||
state.cancel_confirmation();
|
||||
state.set_status_message("confirmation cancelled");
|
||||
None
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
|
||||
match code {
|
||||
KeyCode::Up | KeyCode::Char('k') => {
|
||||
state.move_previous();
|
||||
state.clear_status_message();
|
||||
}
|
||||
KeyCode::Down | KeyCode::Char('j') => {
|
||||
state.move_next();
|
||||
state.clear_status_message();
|
||||
}
|
||||
KeyCode::PageDown => state.page_down(),
|
||||
KeyCode::PageUp => state.page_up(),
|
||||
KeyCode::Char('d') if modifiers.contains(KeyModifiers::CONTROL) => state.page_down(),
|
||||
KeyCode::Char('u') if modifiers.contains(KeyModifiers::CONTROL) => state.page_up(),
|
||||
KeyCode::Char('g') => state.move_to_top(),
|
||||
KeyCode::Char('G') => state.move_to_bottom(),
|
||||
KeyCode::Char(' ') => {
|
||||
if state.numeric_buffer().is_empty() {
|
||||
state.toggle_current_selection();
|
||||
} else if !state.numeric_buffer().ends_with(' ') {
|
||||
state.push_numeric_input(' ');
|
||||
}
|
||||
}
|
||||
KeyCode::Char(character)
|
||||
if character.is_ascii_digit() || character == ',' || character == '-' =>
|
||||
{
|
||||
state.push_numeric_input(character);
|
||||
}
|
||||
KeyCode::Backspace => state.pop_numeric_input(),
|
||||
KeyCode::Enter => match state.submit_selection(config.skip_confirmation) {
|
||||
SubmitAction::None | SubmitAction::Confirming => {}
|
||||
SubmitAction::Confirmed(selection) => return Some(Some(selection)),
|
||||
},
|
||||
KeyCode::Esc | KeyCode::Char('q') => return Some(None),
|
||||
_ => {}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn parse_selection(input: &str, row_count: usize) -> Result<BTreeSet<usize>, String> {
|
||||
let mut selected = BTreeSet::new();
|
||||
|
||||
for token in input
|
||||
.split(|character: char| character == ',' || character.is_ascii_whitespace())
|
||||
.map(str::trim)
|
||||
.filter(|token| !token.is_empty())
|
||||
{
|
||||
if let Some((start, end)) = token.split_once('-') {
|
||||
let start = parse_one_based(start, row_count, input)?;
|
||||
let end = parse_one_based(end, row_count, input)?;
|
||||
let (from, to) = if start <= end {
|
||||
(start, end)
|
||||
} else {
|
||||
(end, start)
|
||||
};
|
||||
for index in from..=to {
|
||||
selected.insert(index);
|
||||
}
|
||||
} else {
|
||||
selected.insert(parse_one_based(token, row_count, input)?);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(selected)
|
||||
}
|
||||
|
||||
fn parse_one_based(token: &str, row_count: usize, original: &str) -> Result<usize, String> {
|
||||
let parsed = token
|
||||
.parse::<usize>()
|
||||
.map_err(|_| format!("invalid selection '{original}'"))?;
|
||||
|
||||
if parsed == 0 || parsed > row_count {
|
||||
return Err(format!("invalid selection '{original}'"));
|
||||
}
|
||||
|
||||
Ok(parsed - 1)
|
||||
}
|
||||
|
||||
fn push_highlighted_spans(
|
||||
target: &mut Vec<Span<'static>>,
|
||||
text: &str,
|
||||
query: &str,
|
||||
base_style: ratatui::style::Style,
|
||||
) {
|
||||
for segment in highlight_segments(text, query) {
|
||||
let style = if segment.is_match {
|
||||
base_style.add_modifier(Modifier::BOLD)
|
||||
} else {
|
||||
base_style
|
||||
};
|
||||
target.push(Span::styled(segment.text, style));
|
||||
}
|
||||
}
|
||||
|
||||
fn truncate_line(line: &str, width: usize) -> String {
|
||||
if width == 0 {
|
||||
return String::new();
|
||||
}
|
||||
|
||||
let length = line.chars().count();
|
||||
if length <= width {
|
||||
return line.to_owned();
|
||||
}
|
||||
|
||||
if width == 1 {
|
||||
return ".".to_owned();
|
||||
}
|
||||
|
||||
if width <= 3 {
|
||||
return ".".repeat(width);
|
||||
}
|
||||
|
||||
let mut truncated = line.chars().take(width - 3).collect::<String>();
|
||||
truncated.push_str("...");
|
||||
truncated
|
||||
}
|
||||
|
||||
fn compress_selection_ranges(indices: &[usize]) -> String {
|
||||
if indices.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
|
||||
let mut ranges = Vec::new();
|
||||
let mut start = indices[0];
|
||||
let mut end = indices[0];
|
||||
|
||||
for &index in &indices[1..] {
|
||||
if index == end + 1 {
|
||||
end = index;
|
||||
continue;
|
||||
}
|
||||
|
||||
ranges.push(format_range(start, end));
|
||||
start = index;
|
||||
end = index;
|
||||
}
|
||||
|
||||
ranges.push(format_range(start, end));
|
||||
ranges.join(",")
|
||||
}
|
||||
|
||||
fn format_range(start: usize, end: usize) -> String {
|
||||
if start == end {
|
||||
start.to_string()
|
||||
} else {
|
||||
format!("{start}-{end}")
|
||||
}
|
||||
}
|
||||
|
||||
fn centered_rect(area: Rect, width_percent: u16, height_percent: u16) -> Rect {
|
||||
let vertical = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([
|
||||
Constraint::Percentage((100 - height_percent) / 2),
|
||||
Constraint::Percentage(height_percent),
|
||||
Constraint::Percentage((100 - height_percent) / 2),
|
||||
])
|
||||
.split(area);
|
||||
|
||||
Layout::default()
|
||||
.direction(Direction::Horizontal)
|
||||
.constraints([
|
||||
Constraint::Percentage((100 - width_percent) / 2),
|
||||
Constraint::Percentage(width_percent),
|
||||
Constraint::Percentage((100 - width_percent) / 2),
|
||||
])
|
||||
.split(vertical[1])[1]
|
||||
}
|
||||
|
|
@ -1,9 +1,11 @@
|
|||
use std::sync::OnceLock;
|
||||
|
||||
use console::{Style, true_colors_enabled};
|
||||
use console::{Style as ConsoleStyle, true_colors_enabled};
|
||||
use dialoguer::theme::ColorfulTheme;
|
||||
use ratatui::style::{Color, Modifier, Style as TuiStyle};
|
||||
|
||||
use crate::cli::config::ThemeConfig;
|
||||
use crate::cli::config::ThemeConfig as AppThemeConfig;
|
||||
use crate::config::ThemeConfig as SearchThemeConfig;
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum ColorValue {
|
||||
|
|
@ -54,7 +56,7 @@ impl Default for Theme {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn resolve_theme(config: &ThemeConfig) -> Theme {
|
||||
pub fn resolve_theme(config: &AppThemeConfig) -> Theme {
|
||||
let mut theme = Theme::default();
|
||||
override_spec(&mut theme.heading, config.heading.as_deref());
|
||||
override_spec(&mut theme.accent, config.accent.as_deref());
|
||||
|
|
@ -153,7 +155,7 @@ pub fn parse_style_spec(input: &str) -> Result<StyleSpec, String> {
|
|||
}
|
||||
|
||||
pub fn apply_style_spec(message: &str, spec: &StyleSpec) -> String {
|
||||
let mut style = Style::new();
|
||||
let mut style = ConsoleStyle::new();
|
||||
if spec.bold {
|
||||
style = style.bold();
|
||||
}
|
||||
|
|
@ -214,7 +216,7 @@ fn is_named_color(token: &str) -> bool {
|
|||
)
|
||||
}
|
||||
|
||||
fn apply_color(style: Style, color: &ColorValue) -> Style {
|
||||
fn apply_color(style: ConsoleStyle, color: &ColorValue) -> ConsoleStyle {
|
||||
match color {
|
||||
ColorValue::Named(name) => apply_named_color(style, name),
|
||||
ColorValue::Rgb(red, green, blue) => {
|
||||
|
|
@ -227,7 +229,7 @@ fn apply_color(style: Style, color: &ColorValue) -> Style {
|
|||
}
|
||||
}
|
||||
|
||||
fn apply_named_color(style: Style, name: &str) -> Style {
|
||||
fn apply_named_color(style: ConsoleStyle, name: &str) -> ConsoleStyle {
|
||||
match name {
|
||||
"black" => style.black(),
|
||||
"red" => style.red(),
|
||||
|
|
@ -304,9 +306,9 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn invalid_override_falls_back_to_default_theme() {
|
||||
let theme = resolve_theme(&ThemeConfig {
|
||||
let theme = resolve_theme(&AppThemeConfig {
|
||||
heading: Some("bogus".to_owned()),
|
||||
..ThemeConfig::default()
|
||||
..AppThemeConfig::default()
|
||||
});
|
||||
|
||||
assert_eq!(theme.heading, Theme::default().heading);
|
||||
|
|
@ -327,3 +329,87 @@ mod tests {
|
|||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct SearchBrowserPalette {
|
||||
accent: Color,
|
||||
accent_secondary: Color,
|
||||
dim: Color,
|
||||
}
|
||||
|
||||
pub fn search_browser_palette(config: &SearchThemeConfig) -> SearchBrowserPalette {
|
||||
SearchBrowserPalette {
|
||||
accent: parse_color(&config.accent).unwrap_or(Color::Rgb(179, 136, 255)),
|
||||
accent_secondary: parse_color(&config.accent_secondary)
|
||||
.unwrap_or(Color::Rgb(213, 194, 255)),
|
||||
dim: parse_color(&config.dim).unwrap_or(Color::Rgb(127, 115, 150)),
|
||||
}
|
||||
}
|
||||
|
||||
impl SearchBrowserPalette {
|
||||
pub fn heading_style(self) -> TuiStyle {
|
||||
TuiStyle::default()
|
||||
.fg(self.accent)
|
||||
.add_modifier(Modifier::BOLD)
|
||||
}
|
||||
|
||||
pub fn hint_style(self) -> TuiStyle {
|
||||
TuiStyle::default().fg(self.dim)
|
||||
}
|
||||
|
||||
pub fn muted_style(self) -> TuiStyle {
|
||||
TuiStyle::default().fg(self.dim)
|
||||
}
|
||||
|
||||
pub fn text_style(self) -> TuiStyle {
|
||||
TuiStyle::default().fg(Color::White)
|
||||
}
|
||||
|
||||
pub fn dim_style(self) -> TuiStyle {
|
||||
TuiStyle::default().fg(self.dim)
|
||||
}
|
||||
|
||||
pub fn checkbox_selected_style(self) -> TuiStyle {
|
||||
TuiStyle::default()
|
||||
.fg(self.accent)
|
||||
.add_modifier(Modifier::BOLD)
|
||||
}
|
||||
|
||||
pub fn checkbox_idle_style(self) -> TuiStyle {
|
||||
TuiStyle::default().fg(self.dim)
|
||||
}
|
||||
|
||||
pub fn version_style(self) -> TuiStyle {
|
||||
TuiStyle::default().fg(self.accent_secondary)
|
||||
}
|
||||
|
||||
pub fn tag_style(self) -> TuiStyle {
|
||||
TuiStyle::default().add_modifier(Modifier::BOLD)
|
||||
}
|
||||
|
||||
pub fn cursor_style(self) -> TuiStyle {
|
||||
TuiStyle::default()
|
||||
.fg(self.accent)
|
||||
.add_modifier(Modifier::BOLD)
|
||||
}
|
||||
|
||||
pub fn active_name_style(self) -> TuiStyle {
|
||||
self.text_style().add_modifier(Modifier::BOLD)
|
||||
}
|
||||
|
||||
pub fn disabled_style(self) -> TuiStyle {
|
||||
self.dim_style()
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_color(value: &str) -> Option<Color> {
|
||||
let hex = value.trim().strip_prefix('#')?;
|
||||
if hex.len() != 6 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let red = u8::from_str_radix(&hex[0..2], 16).ok()?;
|
||||
let green = u8::from_str_radix(&hex[2..4], 16).ok()?;
|
||||
let blue = u8::from_str_radix(&hex[4..6], 16).ok()?;
|
||||
Some(Color::Rgb(red, green, blue))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ fn help_lists_expected_commands() {
|
|||
cmd.arg("--help")
|
||||
.assert()
|
||||
.success()
|
||||
.stdout(contains("search"))
|
||||
.stdout(contains("remove"))
|
||||
.stdout(contains("list"))
|
||||
.stdout(contains("update"));
|
||||
|
|
|
|||
64
crates/aim-cli/tests/config_loading.rs
Normal file
64
crates/aim-cli/tests/config_loading.rs
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
use aim_cli::config::{CliConfig, ConfigError, SearchConfig, load_from_path};
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn missing_config_file_returns_defaults() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("config.toml");
|
||||
|
||||
let config = load_from_path(&path).unwrap();
|
||||
|
||||
assert_eq!(config, CliConfig::default());
|
||||
assert_eq!(config.search, SearchConfig::default());
|
||||
assert!(config.search.bottom_to_top);
|
||||
assert!(!config.search.skip_confirmation);
|
||||
assert_eq!(config.theme.accent, "#b388ff");
|
||||
assert_eq!(config.theme.accent_secondary, "#d5c2ff");
|
||||
assert_eq!(config.theme.dim, "#7f7396");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_section_overrides_defaults() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("config.toml");
|
||||
std::fs::write(
|
||||
&path,
|
||||
"[search]\nbottom_to_top = false\nskip_confirmation = true\n\n[theme]\naccent = \"#9f6bff\"\naccent_secondary = \"#efe7ff\"\ndim = \"#6b6480\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let config = load_from_path(&path).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
config,
|
||||
CliConfig {
|
||||
search: SearchConfig {
|
||||
bottom_to_top: false,
|
||||
skip_confirmation: true,
|
||||
},
|
||||
theme: aim_cli::config::ThemeConfig {
|
||||
accent: "#9f6bff".to_owned(),
|
||||
accent_secondary: "#efe7ff".to_owned(),
|
||||
dim: "#6b6480".to_owned(),
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_toml_returns_path_aware_error() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("config.toml");
|
||||
std::fs::write(&path, "[search\nskip_confirmation = true\n").unwrap();
|
||||
|
||||
let error = load_from_path(&path).unwrap_err();
|
||||
|
||||
match error {
|
||||
ConfigError::Parse {
|
||||
path: error_path, ..
|
||||
} => {
|
||||
assert_eq!(error_path, path);
|
||||
}
|
||||
other => panic!("expected parse error, got {other:?}"),
|
||||
}
|
||||
}
|
||||
234
crates/aim-cli/tests/search_browser.rs
Normal file
234
crates/aim-cli/tests/search_browser.rs
Normal file
|
|
@ -0,0 +1,234 @@
|
|||
use aim_cli::config::SearchConfig;
|
||||
use aim_cli::ui::search_browser::{BrowserPhase, SearchBrowserState, SubmitAction};
|
||||
use aim_core::domain::search::{SearchInstallStatus, SearchResult};
|
||||
|
||||
#[test]
|
||||
fn browser_defaults_to_bottom_to_top_ordering() {
|
||||
let state = SearchBrowserState::new(sample_results(), SearchConfig::default(), 3);
|
||||
|
||||
assert_eq!(
|
||||
visible_names(&state),
|
||||
vec!["charlie/app", "bravo/app", "alpha/app"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browser_moves_cursor_and_pages() {
|
||||
let mut state = SearchBrowserState::new(sample_results(), SearchConfig::default(), 2);
|
||||
|
||||
state.move_next();
|
||||
assert_eq!(state.cursor_position(), 1);
|
||||
|
||||
state.page_down();
|
||||
assert_eq!(state.cursor_position(), 2);
|
||||
|
||||
state.page_up();
|
||||
assert_eq!(state.cursor_position(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browser_supports_single_and_multiple_numeric_selection() {
|
||||
let mut state = SearchBrowserState::new(sample_results(), SearchConfig::default(), 3);
|
||||
|
||||
state.apply_numeric_selection("1,3").unwrap();
|
||||
|
||||
assert_eq!(selected_names(&state), vec!["charlie/app", "alpha/app"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browser_supports_numeric_ranges() {
|
||||
let mut state = SearchBrowserState::new(sample_results(), SearchConfig::default(), 3);
|
||||
|
||||
state.apply_numeric_selection("1-2").unwrap();
|
||||
|
||||
assert_eq!(selected_names(&state), vec!["charlie/app", "bravo/app"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browser_supports_space_separated_numeric_selection() {
|
||||
let mut state = SearchBrowserState::new(sample_results(), SearchConfig::default(), 3);
|
||||
|
||||
state.apply_numeric_selection("1 3").unwrap();
|
||||
|
||||
assert_eq!(selected_names(&state), vec!["charlie/app", "alpha/app"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typing_numeric_input_updates_selection_immediately() {
|
||||
let mut state = SearchBrowserState::new(sample_results(), SearchConfig::default(), 3);
|
||||
|
||||
state.push_numeric_input('1');
|
||||
assert_eq!(selected_names(&state), vec!["charlie/app"]);
|
||||
|
||||
state.push_numeric_input(' ');
|
||||
state.push_numeric_input('3');
|
||||
|
||||
assert_eq!(selected_names(&state), vec!["charlie/app", "alpha/app"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_numeric_input_keeps_last_good_selection_visible() {
|
||||
let mut state = SearchBrowserState::new(sample_results(), SearchConfig::default(), 3);
|
||||
|
||||
state.push_numeric_input('1');
|
||||
assert_eq!(selected_names(&state), vec!["charlie/app"]);
|
||||
|
||||
state.push_numeric_input('-');
|
||||
|
||||
assert_eq!(selected_names(&state), vec!["charlie/app"]);
|
||||
assert_eq!(state.numeric_buffer(), "1-");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn highlight_segments_marks_matching_query_fragments() {
|
||||
let fragments = aim_cli::ui::search_browser::highlight_segments("pingdotgg/t3code", "dotgg");
|
||||
|
||||
assert_eq!(fragments.len(), 3);
|
||||
assert_eq!(fragments[1].text, "dotgg");
|
||||
assert!(fragments[1].is_match);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_numeric_selection_preserves_existing_selection() {
|
||||
let mut state = SearchBrowserState::new(sample_results(), SearchConfig::default(), 3);
|
||||
state.apply_numeric_selection("2").unwrap();
|
||||
|
||||
let error = state.apply_numeric_selection("2-z").unwrap_err();
|
||||
|
||||
assert!(error.contains("2-z"));
|
||||
assert_eq!(selected_names(&state), vec!["bravo/app"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn confirmation_requires_selection_before_transition() {
|
||||
let mut state = SearchBrowserState::new(sample_results(), SearchConfig::default(), 3);
|
||||
|
||||
assert!(!state.enter_confirmation());
|
||||
assert_eq!(state.phase(), BrowserPhase::Browsing);
|
||||
|
||||
state.toggle_current_selection();
|
||||
assert!(state.enter_confirmation());
|
||||
assert_eq!(state.phase(), BrowserPhase::Confirming);
|
||||
|
||||
state.cancel_confirmation();
|
||||
assert_eq!(state.phase(), BrowserPhase::Browsing);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn submit_selection_can_skip_confirmation_from_config() {
|
||||
let mut state = SearchBrowserState::new(sample_results(), SearchConfig::default(), 3);
|
||||
state.toggle_current_selection();
|
||||
|
||||
let action = state.submit_selection(true);
|
||||
|
||||
assert_eq!(
|
||||
action,
|
||||
SubmitAction::Confirmed(aim_cli::ui::search_browser::SearchSelection {
|
||||
rows: vec![aim_cli::ui::search_browser::SearchRow {
|
||||
status: SearchInstallStatus::Available,
|
||||
provider_id: "github".to_owned(),
|
||||
display_name: "charlie/app".to_owned(),
|
||||
description: None,
|
||||
install_query: "charlie/app".to_owned(),
|
||||
version: Some("1.0.0".to_owned()),
|
||||
selectable: true,
|
||||
}],
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installed_rows_are_visible_but_not_selectable() {
|
||||
let mut state = SearchBrowserState::new(installed_first_results(), SearchConfig::default(), 3);
|
||||
|
||||
state.toggle_current_selection();
|
||||
|
||||
assert!(state.selected_rows().is_empty());
|
||||
assert_eq!(
|
||||
state.status_message(),
|
||||
Some("installed result is not selectable")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_rows_remain_selectable() {
|
||||
let mut state = SearchBrowserState::new(update_first_results(), SearchConfig::default(), 3);
|
||||
|
||||
state.toggle_current_selection();
|
||||
|
||||
assert_eq!(selected_names(&state), vec!["charlie/app"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_expression_prefills_from_checklist_selection() {
|
||||
let mut state = SearchBrowserState::new(sample_results(), SearchConfig::default(), 5);
|
||||
|
||||
state.toggle_current_selection();
|
||||
state.move_to_bottom();
|
||||
state.toggle_current_selection();
|
||||
|
||||
assert_eq!(state.selection_expression(), "1,3");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_expression_compacts_adjacent_ranges() {
|
||||
let mut state = SearchBrowserState::new(sample_results(), SearchConfig::default(), 5);
|
||||
|
||||
state.apply_numeric_selection("1-3").unwrap();
|
||||
|
||||
assert_eq!(state.selection_expression(), "1-3");
|
||||
}
|
||||
|
||||
fn sample_results() -> Vec<SearchResult> {
|
||||
vec![
|
||||
sample_result("alpha/app"),
|
||||
sample_result("bravo/app"),
|
||||
sample_result("charlie/app"),
|
||||
]
|
||||
}
|
||||
|
||||
fn sample_result(name: &str) -> SearchResult {
|
||||
SearchResult {
|
||||
provider_id: "github".to_owned(),
|
||||
display_name: name.to_owned(),
|
||||
description: None,
|
||||
source_locator: name.to_owned(),
|
||||
install_query: name.to_owned(),
|
||||
canonical_locator: name.to_owned(),
|
||||
version: Some("1.0.0".to_owned()),
|
||||
install_status: SearchInstallStatus::Available,
|
||||
}
|
||||
}
|
||||
|
||||
fn installed_first_results() -> Vec<SearchResult> {
|
||||
let mut results = sample_results();
|
||||
results[2].install_status = SearchInstallStatus::Installed {
|
||||
installed_version: Some("1.0.0".to_owned()),
|
||||
};
|
||||
results
|
||||
}
|
||||
|
||||
fn update_first_results() -> Vec<SearchResult> {
|
||||
let mut results = sample_results();
|
||||
results[2].install_status = SearchInstallStatus::UpdateAvailable {
|
||||
installed_version: Some("0.9.0".to_owned()),
|
||||
latest_version: Some("1.0.0".to_owned()),
|
||||
};
|
||||
results
|
||||
}
|
||||
|
||||
fn visible_names(state: &SearchBrowserState) -> Vec<&str> {
|
||||
state
|
||||
.ordered_rows()
|
||||
.iter()
|
||||
.map(|row| row.display_name.as_str())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn selected_names(state: &SearchBrowserState) -> Vec<&str> {
|
||||
state
|
||||
.selected_rows()
|
||||
.iter()
|
||||
.map(|row| row.display_name.as_str())
|
||||
.collect()
|
||||
}
|
||||
153
crates/aim-cli/tests/search_cli.rs
Normal file
153
crates/aim-cli/tests/search_cli.rs
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
use assert_cmd::Command;
|
||||
use predicates::prelude::PredicateBooleanExt;
|
||||
use predicates::str::contains;
|
||||
use tempfile::tempdir;
|
||||
|
||||
const FIXTURE_MODE_ENV: &str = "AIM_GITHUB_FIXTURE_MODE";
|
||||
|
||||
#[test]
|
||||
fn search_command_renders_remote_github_results() {
|
||||
let dir = tempdir().unwrap();
|
||||
let registry_path = dir.path().join("registry.toml");
|
||||
let mut cmd = Command::cargo_bin("aim").unwrap();
|
||||
|
||||
cmd.args(["search", "bat"])
|
||||
.env("AIM_REGISTRY_PATH", ®istry_path)
|
||||
.env(FIXTURE_MODE_ENV, "1")
|
||||
.assert()
|
||||
.success()
|
||||
.stdout(contains("Search Results"))
|
||||
.stdout(contains("Remote Results"))
|
||||
.stdout(contains("[github] sharkdp/bat"))
|
||||
.stdout(contains("Install query: sharkdp/bat"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_command_renders_local_matches_in_deterministic_order() {
|
||||
let dir = tempdir().unwrap();
|
||||
let registry_path = dir.path().join("registry.toml");
|
||||
std::fs::write(
|
||||
®istry_path,
|
||||
concat!(
|
||||
"version = 1\n",
|
||||
"[[apps]]\n",
|
||||
"stable_id = \"bat\"\n",
|
||||
"display_name = \"Bat\"\n",
|
||||
"[[apps]]\n",
|
||||
"stable_id = \"bat-tools\"\n",
|
||||
"display_name = \"Bat Tools\"\n",
|
||||
"[[apps]]\n",
|
||||
"stable_id = \"acrobat-reader\"\n",
|
||||
"display_name = \"Acrobat Reader\"\n",
|
||||
"[[apps]]\n",
|
||||
"stable_id = \"combat-viewer\"\n",
|
||||
"display_name = \"Combat Viewer\"\n"
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let mut cmd = Command::cargo_bin("aim").unwrap();
|
||||
|
||||
cmd.args(["search", "bat"])
|
||||
.env("AIM_REGISTRY_PATH", ®istry_path)
|
||||
.env(FIXTURE_MODE_ENV, "1")
|
||||
.assert()
|
||||
.success()
|
||||
.stdout(contains("Installed Matches"))
|
||||
.stdout(
|
||||
contains("- Bat (bat)")
|
||||
.and(contains("- Bat Tools (bat-tools)"))
|
||||
.and(contains("- Acrobat Reader (acrobat-reader)"))
|
||||
.and(contains("- Combat Viewer (combat-viewer)")),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_command_is_read_only_for_registry_contents() {
|
||||
let dir = tempdir().unwrap();
|
||||
let registry_path = dir.path().join("registry.toml");
|
||||
let original = "version = 1\n[[apps]]\nstable_id = \"bat\"\ndisplay_name = \"Bat\"\n";
|
||||
std::fs::write(®istry_path, original).unwrap();
|
||||
|
||||
let mut cmd = Command::cargo_bin("aim").unwrap();
|
||||
|
||||
cmd.args(["search", "bat"])
|
||||
.env("AIM_REGISTRY_PATH", ®istry_path)
|
||||
.env(FIXTURE_MODE_ENV, "1")
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let persisted = std::fs::read_to_string(®istry_path).unwrap();
|
||||
assert_eq!(persisted, original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_command_fails_fast_on_malformed_config() {
|
||||
let dir = tempdir().unwrap();
|
||||
let registry_path = dir.path().join("registry.toml");
|
||||
let config_path = dir.path().join("config.toml");
|
||||
std::fs::write(&config_path, "[search\nskip_confirmation = true\n").unwrap();
|
||||
|
||||
let mut cmd = Command::cargo_bin("aim").unwrap();
|
||||
|
||||
cmd.args(["search", "bat"])
|
||||
.env("AIM_REGISTRY_PATH", ®istry_path)
|
||||
.env("AIM_CONFIG_PATH", &config_path)
|
||||
.env(FIXTURE_MODE_ENV, "1")
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains(config_path.to_string_lossy().as_ref()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_command_uses_plain_text_output_when_not_on_a_tty() {
|
||||
let dir = tempdir().unwrap();
|
||||
let registry_path = dir.path().join("registry.toml");
|
||||
let config_path = dir.path().join("config.toml");
|
||||
std::fs::write(
|
||||
&config_path,
|
||||
"[search]\nbottom_to_top = false\nskip_confirmation = true\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let mut cmd = Command::cargo_bin("aim").unwrap();
|
||||
|
||||
cmd.args(["search", "bat"])
|
||||
.env("AIM_REGISTRY_PATH", ®istry_path)
|
||||
.env("AIM_CONFIG_PATH", &config_path)
|
||||
.env(FIXTURE_MODE_ENV, "1")
|
||||
.assert()
|
||||
.success()
|
||||
.stdout(contains("Search Results"))
|
||||
.stdout(contains("Remote Results"))
|
||||
.stdout(contains("[github] sharkdp/bat"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_command_reports_loading_status_to_stderr() {
|
||||
let dir = tempdir().unwrap();
|
||||
let registry_path = dir.path().join("registry.toml");
|
||||
let mut cmd = Command::cargo_bin("aim").unwrap();
|
||||
|
||||
cmd.args(["search", "bat"])
|
||||
.env("AIM_REGISTRY_PATH", ®istry_path)
|
||||
.env(FIXTURE_MODE_ENV, "1")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(contains("Searching bat"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_command_keeps_empty_results_in_plain_text_mode() {
|
||||
let dir = tempdir().unwrap();
|
||||
let registry_path = dir.path().join("registry.toml");
|
||||
let mut cmd = Command::cargo_bin("aim").unwrap();
|
||||
|
||||
cmd.args(["search", "no-such-app-image-query"])
|
||||
.env("AIM_REGISTRY_PATH", ®istry_path)
|
||||
.env(FIXTURE_MODE_ENV, "1")
|
||||
.assert()
|
||||
.success()
|
||||
.stdout(contains("Search Results"))
|
||||
.stdout(contains("No remote matches"));
|
||||
}
|
||||
|
|
@ -1,11 +1,13 @@
|
|||
use aim_cli::DispatchResult;
|
||||
use aim_cli::ui::prompt::render_interaction;
|
||||
use aim_cli::ui::render::{render_dispatch_result, render_update_summary};
|
||||
use aim_cli::ui::search_browser::{SearchRow, format_search_row, render_confirmation_summary};
|
||||
use aim_core::app::add::InstalledApp;
|
||||
use aim_core::app::interaction::{InteractionKind, InteractionRequest};
|
||||
use aim_core::app::list::ListRow;
|
||||
use aim_core::app::remove::{RemovalPlan, RemovalResult};
|
||||
use aim_core::domain::app::{AppRecord, InstallMetadata, InstallScope};
|
||||
use aim_core::domain::search::SearchInstallStatus;
|
||||
use aim_core::domain::source::{NormalizedSourceKind, SourceInputKind, SourceKind, SourceRef};
|
||||
use aim_core::domain::update::ArtifactCandidate;
|
||||
use aim_core::domain::update::{ChannelPreference, PlannedUpdate, UpdateChannelKind, UpdatePlan};
|
||||
|
|
@ -146,6 +148,7 @@ fn install_summary_omits_completed_steps_recap() {
|
|||
.to_owned(),
|
||||
version: "0.25.0".to_owned(),
|
||||
arch: Some("x86_64".to_owned()),
|
||||
trusted_checksum: None,
|
||||
selection_reason: "heuristic-match".to_owned(),
|
||||
},
|
||||
artifact_size_bytes: 173_015_040,
|
||||
|
|
@ -177,3 +180,78 @@ fn install_summary_omits_completed_steps_recap() {
|
|||
assert!(output.contains("Installed files"));
|
||||
assert!(!output.contains("Completed steps"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_browser_row_uses_status_tag_version_and_description_layout() {
|
||||
let row = SearchRow {
|
||||
status: SearchInstallStatus::Installed {
|
||||
installed_version: Some("0.0.12".to_owned()),
|
||||
},
|
||||
provider_id: "github".to_owned(),
|
||||
display_name: "pingdotgg/t3code".to_owned(),
|
||||
description: Some("The T3 desktop app.".to_owned()),
|
||||
install_query: "pingdotgg/t3code".to_owned(),
|
||||
version: Some("0.0.12".to_owned()),
|
||||
selectable: false,
|
||||
};
|
||||
|
||||
let output = format_search_row(1, &row, true, true, 120);
|
||||
|
||||
assert!(output.contains('\n'));
|
||||
assert!(output.contains("[installed]"));
|
||||
assert!(output.contains("v0.0.12"));
|
||||
assert!(output.contains("pingdotgg/t3code"));
|
||||
assert!(output.contains("github - The T3 desktop app."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_browser_row_without_description_shows_provider_only() {
|
||||
let row = SearchRow {
|
||||
status: SearchInstallStatus::Available,
|
||||
provider_id: "github".to_owned(),
|
||||
display_name: "pingdotgg/t3code".to_owned(),
|
||||
description: None,
|
||||
install_query: "pingdotgg/t3code".to_owned(),
|
||||
version: Some("0.0.12".to_owned()),
|
||||
selectable: true,
|
||||
};
|
||||
|
||||
let output = format_search_row(1, &row, false, false, 120);
|
||||
|
||||
assert!(output.contains("github"));
|
||||
assert!(!output.contains(" - "));
|
||||
assert!(!output.contains("No description available"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_confirmation_summary_lists_selected_rows() {
|
||||
let rows = vec![
|
||||
SearchRow {
|
||||
status: SearchInstallStatus::UpdateAvailable {
|
||||
installed_version: Some("0.0.11".to_owned()),
|
||||
latest_version: Some("0.0.12".to_owned()),
|
||||
},
|
||||
provider_id: "github".to_owned(),
|
||||
display_name: "pingdotgg/t3code".to_owned(),
|
||||
description: Some("The T3 desktop app.".to_owned()),
|
||||
install_query: "pingdotgg/t3code".to_owned(),
|
||||
version: Some("0.0.12".to_owned()),
|
||||
selectable: true,
|
||||
},
|
||||
SearchRow {
|
||||
status: SearchInstallStatus::Available,
|
||||
provider_id: "github".to_owned(),
|
||||
display_name: "sharkdp/bat".to_owned(),
|
||||
description: Some("A cat(1) clone with wings.".to_owned()),
|
||||
install_query: "sharkdp/bat".to_owned(),
|
||||
version: Some("1.0.0".to_owned()),
|
||||
selectable: true,
|
||||
},
|
||||
];
|
||||
|
||||
let output = render_confirmation_summary(&rows);
|
||||
|
||||
assert!(output.contains("Confirm Search Selection"));
|
||||
assert!(output.contains("pingdotgg/t3code"));
|
||||
assert!(output.contains("sharkdp/bat"));
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue