systemprompt_logging/services/cli/
service.rs1use std::io::Write;
2use std::time::Duration;
3
4use crate::models::LoggingError;
5type Result<T> = std::result::Result<T, LoggingError>;
6use indicatif::{ProgressBar, ProgressStyle};
7use serde::Serialize;
8use systemprompt_traits::LogEventLevel;
9
10use super::display::{CollectionDisplay, Display, DisplayUtils};
11use super::module::{BatchModuleOperations, ModuleDisplay, ModuleInstall, ModuleUpdate};
12use super::output::publish_log;
13use super::prompts::{PromptBuilder, Prompts};
14use super::summary::{OperationResult, ProgressSummary, ValidationSummary};
15use super::theme::{EmphasisType, ItemStatus, MessageLevel, ModuleType, Theme};
16
17#[derive(Copy, Clone, Debug)]
18pub struct CliService;
19
20impl CliService {
21 pub fn success(message: &str) {
22 publish_log(LogEventLevel::Info, "cli", message);
23 DisplayUtils::message(MessageLevel::Success, message);
24 }
25
26 pub fn warning(message: &str) {
27 publish_log(LogEventLevel::Warn, "cli", message);
28 DisplayUtils::message(MessageLevel::Warning, message);
29 }
30
31 pub fn error(message: &str) {
32 publish_log(LogEventLevel::Error, "cli", message);
33 DisplayUtils::message(MessageLevel::Error, message);
34 }
35
36 pub fn info(message: &str) {
37 publish_log(LogEventLevel::Info, "cli", message);
38 DisplayUtils::message(MessageLevel::Info, message);
39 }
40
41 pub fn debug(message: &str) {
42 let debug_msg = format!("DEBUG: {message}");
43 publish_log(LogEventLevel::Debug, "cli", &debug_msg);
44 DisplayUtils::message(MessageLevel::Info, &debug_msg);
45 }
46
47 pub fn verbose(message: &str) {
48 publish_log(LogEventLevel::Debug, "cli", message);
49 DisplayUtils::message(MessageLevel::Info, message);
50 }
51
52 pub fn fatal(message: &str, exit_code: i32) -> ! {
53 let fatal_msg = format!("FATAL: {message}");
54 DisplayUtils::message(MessageLevel::Error, &fatal_msg);
55 std::process::exit(exit_code);
56 }
57
58 pub fn section(title: &str) {
59 DisplayUtils::section_header(title);
60 }
61
62 pub fn subsection(title: &str) {
63 DisplayUtils::subsection_header(title);
64 }
65
66 pub fn clear_screen() {
67 let mut stdout = std::io::stdout();
68 write!(stdout, "\x1B[2J\x1B[1;1H").ok();
69 }
70
71 pub fn output(content: &str) {
72 let mut stdout = std::io::stdout();
73 writeln!(stdout, "{content}").ok();
74 }
75
76 pub fn json<T: Serialize>(value: &T) {
77 match serde_json::to_string_pretty(value) {
78 Ok(json) => {
79 let mut stdout = std::io::stdout();
80 writeln!(stdout, "{json}").ok();
81 },
82 Err(e) => Self::error(&format!("Failed to format log entry: {e}")),
83 }
84 }
85
86 pub fn json_compact<T: Serialize>(value: &T) {
87 match serde_json::to_string(value) {
88 Ok(json) => {
89 let mut stdout = std::io::stdout();
90 writeln!(stdout, "{json}").ok();
91 },
92 Err(e) => Self::error(&format!("Failed to format log entry: {e}")),
93 }
94 }
95
96 pub fn yaml<T: Serialize>(value: &T) {
97 match serde_yaml::to_string(value) {
98 Ok(yaml) => {
99 let mut stdout = std::io::stdout();
100 write!(stdout, "{yaml}").ok();
101 },
102 Err(e) => Self::error(&format!("Failed to format log entry: {e}")),
103 }
104 }
105
106 pub fn key_value(label: &str, value: &str) {
107 let mut stdout = std::io::stdout();
108 writeln!(
109 stdout,
110 "{}: {}",
111 Theme::color(label, EmphasisType::Bold),
112 Theme::color(value, EmphasisType::Highlight)
113 )
114 .ok();
115 }
116
117 pub fn status_line(label: &str, value: &str, status: ItemStatus) {
118 let mut stdout = std::io::stdout();
119 writeln!(
120 stdout,
121 "{} {}: {}",
122 Theme::icon(status),
123 Theme::color(label, EmphasisType::Bold),
124 Theme::color(value, status)
125 )
126 .ok();
127 }
128
129 pub fn spinner(message: &str) -> ProgressBar {
130 let pb = ProgressBar::new_spinner();
131 pb.set_style(
132 ProgressStyle::default_spinner()
133 .template("{spinner:.cyan} {msg}")
134 .unwrap_or_else(|_| ProgressStyle::default_spinner()),
135 );
136 pb.set_message(message.to_string());
137 pb.enable_steady_tick(Duration::from_millis(100));
138 pb
139 }
140
141 pub fn progress_bar(total: u64) -> ProgressBar {
142 let pb = ProgressBar::new(total);
143 pb.set_style(
144 ProgressStyle::default_bar()
145 .template(
146 "{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len} {msg}",
147 )
148 .unwrap_or_else(|_| ProgressStyle::default_bar())
149 .progress_chars("#>-"),
150 );
151 pb
152 }
153
154 pub fn timed<F, R>(label: &str, f: F) -> R
155 where
156 F: FnOnce() -> R,
157 {
158 let start = std::time::Instant::now();
159 let result = f();
160 let duration = start.elapsed();
161 let duration_secs = duration.as_secs_f64();
162 let info_msg = format!("{label} completed in {duration_secs:.2}s");
163 Self::info(&info_msg);
164 result
165 }
166
167 pub fn prompt_schemas(module_name: &str, schemas: &[(String, String)]) -> Result<bool> {
168 ModuleDisplay::prompt_apply_schemas(module_name, schemas)
169 }
170
171 pub fn prompt_seeds(module_name: &str, seeds: &[(String, String)]) -> Result<bool> {
172 ModuleDisplay::prompt_apply_seeds(module_name, seeds)
173 }
174
175 pub fn prompt_install(modules: &[String]) -> Result<bool> {
176 Prompts::confirm_install(modules)
177 }
178
179 pub fn prompt_update(updates: &[(String, String, String)]) -> Result<bool> {
180 Prompts::confirm_update(updates)
181 }
182
183 pub fn confirm(question: &str) -> Result<bool> {
184 Prompts::confirm(question, false)
185 }
186
187 pub fn confirm_default_yes(question: &str) -> Result<bool> {
188 Prompts::confirm(question, true)
189 }
190
191 pub fn display_validation_summary(summary: &ValidationSummary) {
192 summary.display();
193 }
194
195 pub fn display_result(result: &OperationResult) {
196 result.display();
197 }
198
199 pub fn display_progress(progress: &ProgressSummary) {
200 progress.display();
201 }
202
203 pub fn prompt_builder(message: &str) -> PromptBuilder {
204 PromptBuilder::new(message)
205 }
206
207 pub fn collection<T: Display>(title: &str, items: Vec<T>) -> CollectionDisplay<T> {
208 CollectionDisplay::new(title, items)
209 }
210
211 pub fn module_status(module_name: &str, message: &str) {
212 DisplayUtils::module_status(module_name, message);
213 }
214
215 pub fn relationship(from: &str, to: &str, status: ItemStatus, module_type: ModuleType) {
216 DisplayUtils::relationship(module_type, from, to, status);
217 }
218
219 pub fn item(status: ItemStatus, name: &str, detail: Option<&str>) {
220 DisplayUtils::item(status, name, detail);
221 }
222
223 pub fn batch_install(modules: &[ModuleInstall]) -> Result<bool> {
224 BatchModuleOperations::prompt_install_multiple(modules)
225 }
226
227 pub fn batch_update(updates: &[ModuleUpdate]) -> Result<bool> {
228 BatchModuleOperations::prompt_update_multiple(updates)
229 }
230
231 pub fn table(headers: &[&str], rows: &[Vec<String>]) {
232 super::table::render_table(headers, rows);
233 }
234}