1use colored::{ColoredString, Colorize};
2use serde::Serialize;
3use std::io::Write as IoWrite;
4
5use crate::core::{Priority, Status, Ticket};
6use crate::error::Result;
7
8#[derive(Debug, Clone, Copy)]
10pub enum MessageLevel {
11 Success,
12 Error,
13 Warning,
14 Info,
15}
16
17#[derive(Clone)]
19pub struct OutputFormatter {
20 json: bool,
21}
22
23impl OutputFormatter {
24 #[must_use]
26 pub fn new(json: bool, no_color: bool) -> Self {
27 if no_color {
28 colored::control::set_override(false);
29 }
30 Self { json }
31 }
32
33 #[must_use]
35 pub const fn is_json(&self) -> bool {
36 self.json
37 }
38
39 pub fn json<T: Serialize>(&self, data: &T) -> Result<()> {
41 if self.json {
42 self.print_json(data)?;
43 }
44 Ok(())
45 }
46
47 #[must_use]
53 pub fn progress_bar(&self, message: &str) -> indicatif::ProgressBar {
54 if self.json {
55 let pb = indicatif::ProgressBar::hidden();
57 pb.set_message(message.to_string());
58 pb
59 } else {
60 let pb = indicatif::ProgressBar::new_spinner();
61 pb.set_style(
62 indicatif::ProgressStyle::default_spinner()
63 .template("{spinner:.green} {msg}")
64 .unwrap()
65 .tick_strings(&["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]),
66 );
67 pb.set_message(message.to_string());
68 pb.enable_steady_tick(std::time::Duration::from_millis(100));
69 pb
70 }
71 }
72
73 pub fn success(&self, message: &str) {
75 self.print_message(message, MessageLevel::Success);
76 }
77
78 pub fn error(&self, message: &str) {
80 self.print_message(message, MessageLevel::Error);
81 }
82
83 pub fn warning(&self, message: &str) {
85 self.print_message(message, MessageLevel::Warning);
86 }
87
88 pub fn info(&self, message: &str) {
90 self.print_message(message, MessageLevel::Info);
91 }
92
93 fn print_message(&self, message: &str, level: MessageLevel) {
95 if self.json {
96 return;
97 }
98
99 match level {
100 MessageLevel::Success => println!("{} {}", "✓".green(), message),
101 MessageLevel::Error => eprintln!("{} {}", "✗".red(), message),
102 MessageLevel::Warning => eprintln!("{} {}", "⚠".yellow(), message),
103 MessageLevel::Info => println!("{} {}", "ℹ".blue(), message),
104 }
105 }
106
107 pub fn print_ticket(&self, ticket: &Ticket) -> Result<()> {
109 if self.json {
110 self.print_json(ticket)?;
111 } else {
112 Self::print_ticket_formatted(ticket);
113 }
114 Ok(())
115 }
116
117 pub fn print_tickets(&self, tickets: &[Ticket]) -> Result<()> {
119 if self.json {
120 self.print_json(tickets)?;
121 } else {
122 Self::print_tickets_table(tickets);
123 }
124 Ok(())
125 }
126
127 pub fn print_json<T: Serialize + ?Sized>(&self, data: &T) -> Result<()> {
129 let json = serde_json::to_string_pretty(data)?;
130 println!("{json}");
131 Ok(())
132 }
133
134 fn print_ticket_formatted(ticket: &Ticket) {
136 println!("{}", "─".repeat(80).bright_black());
137 println!(
138 "{} {} {}",
139 ticket.status.emoji(),
140 ticket.title.bold(),
141 format!("({})", ticket.slug).bright_black()
142 );
143 println!("{}", "─".repeat(80).bright_black());
144
145 println!("{:<12} {}", "ID:".bright_black(), ticket.id.short());
146 println!(
147 "{:<12} {}",
148 "Status:".bright_black(),
149 Self::format_status(ticket.status)
150 );
151 println!(
152 "{:<12} {}",
153 "Priority:".bright_black(),
154 Self::format_priority(ticket.priority)
155 );
156
157 if let Some(assignee) = &ticket.assignee {
158 println!("{:<12} {}", "Assignee:".bright_black(), assignee);
159 }
160
161 if !ticket.tags.is_empty() {
162 println!(
163 "{:<12} {}",
164 "Tags:".bright_black(),
165 ticket.tags.join(", ").cyan()
166 );
167 }
168
169 println!(
170 "{:<12} {}",
171 "Created:".bright_black(),
172 ticket.created_at.format("%Y-%m-%d %H:%M")
173 );
174
175 if let Some(started) = ticket.started_at {
176 println!(
177 "{:<12} {}",
178 "Started:".bright_black(),
179 started.format("%Y-%m-%d %H:%M")
180 );
181 }
182
183 if !ticket.description.is_empty() {
184 println!("\n{}", "Description:".bright_black());
185 println!("{}", ticket.description);
186 }
187
188 if !ticket.tasks.is_empty() {
189 println!("\n{}", "Tasks:".bright_black());
190 for task in &ticket.tasks {
191 let checkbox = if task.completed {
192 "✓".green()
193 } else {
194 "☐".white()
195 };
196 println!(" {} {}", checkbox, task.title);
197 }
198
199 let completed = ticket.completed_tasks_count();
200 let total = ticket.total_tasks_count();
201 let percentage = ticket.completion_percentage();
202
203 println!(
204 "\n{} {}/{} ({:.0}%)",
205 "Progress:".bright_black(),
206 completed,
207 total,
208 percentage
209 );
210 }
211
212 println!("{}", "─".repeat(80).bright_black());
213 }
214
215 fn print_tickets_table(tickets: &[Ticket]) {
217 if tickets.is_empty() {
218 println!("No tickets found.");
219 return;
220 }
221
222 println!(
224 "{:<8} {:<10} {:<10} {:<40} {}",
225 "ID".bold(),
226 "Status".bold(),
227 "Priority".bold(),
228 "Title".bold(),
229 "Tasks".bold()
230 );
231 println!("{}", "─".repeat(90).bright_black());
232
233 for ticket in tickets {
235 let tasks = format!(
236 "{}/{}",
237 ticket.completed_tasks_count(),
238 ticket.total_tasks_count()
239 );
240
241 println!(
242 "{:<8} {:<10} {:<10} {:<40} {}",
243 ticket.id.short(),
244 Self::format_status(ticket.status),
245 Self::format_priority(ticket.priority),
246 truncate(&ticket.title, 40),
247 tasks
248 );
249 }
250
251 println!("{}", "─".repeat(90).bright_black());
252 println!("Total: {} tickets", tickets.len());
253 }
254
255 fn format_status(status: Status) -> ColoredString {
257 match status {
258 Status::Todo => "Todo".blue(),
259 Status::Doing => "Doing".yellow(),
260 Status::Done => "Done".green(),
261 Status::Blocked => "Blocked".red(),
262 Status::Review => "Review".cyan(),
263 }
264 }
265
266 fn format_priority(priority: Priority) -> ColoredString {
268 match priority {
269 Priority::Low => "Low".green(),
270 Priority::Medium => "Medium".yellow(),
271 Priority::High => "High".magenta(),
272 Priority::Critical => "Critical".red(),
273 }
274 }
275}
276
277fn truncate(s: &str, max_len: usize) -> String {
279 if s.chars().count() <= max_len {
280 s.to_string()
281 } else {
282 let truncated: String = s.chars().take(max_len - 3).collect();
283 format!("{truncated}...")
284 }
285}
286
287pub struct ProgressBar {
289 message: String,
290 total: usize,
291 current: usize,
292}
293
294impl ProgressBar {
295 #[must_use]
297 pub fn new(message: &str, total: usize) -> Self {
298 Self {
299 message: message.to_string(),
300 total,
301 current: 0,
302 }
303 }
304
305 pub fn update(&mut self, current: usize) {
307 self.current = current;
308 self.draw();
309 }
310
311 pub fn increment(&mut self) {
313 self.current += 1;
314 self.draw();
315 }
316
317 pub fn finish(&self) {
319 println!();
320 }
321
322 fn draw(&self) {
324 #[allow(
325 clippy::cast_possible_truncation,
326 clippy::cast_sign_loss,
327 clippy::cast_precision_loss
328 )]
329 let percentage = (self.current as f32 / self.total as f32 * 100.0) as u32;
330 let filled = (percentage as usize * 30) / 100;
331 let empty = 30 - filled;
332
333 print!(
334 "\r{}: [{}{}] {}% ({}/{})",
335 self.message,
336 "█".repeat(filled).green(),
337 "░".repeat(empty).bright_black(),
338 percentage,
339 self.current,
340 self.total
341 );
342
343 std::io::stdout().flush().unwrap();
344 }
345}
346
347#[cfg(test)]
348mod tests {
349 use super::*;
350
351 #[test]
352 fn test_truncate_ascii() {
353 assert_eq!(truncate("hello", 10), "hello");
354 assert_eq!(truncate("hello world", 8), "hello...");
355 assert_eq!(truncate("short", 5), "short");
356 assert_eq!(truncate("exactly", 7), "exactly");
357 }
358
359 #[test]
360 fn test_truncate_unicode() {
361 assert_eq!(truncate("こんにちは", 10), "こんにちは");
363 assert_eq!(truncate("こんにちは世界", 5), "こん...");
364
365 assert_eq!(truncate("Hello世界", 7), "Hello世界");
367 assert_eq!(truncate("Hello世界", 6), "Hel...");
368
369 assert_eq!(truncate("🚀🎉🔥💻🎯", 3), "...");
371 assert_eq!(truncate("🚀 Rocket", 5), "🚀 ...");
372
373 assert_eq!(
375 truncate("Specs管理システムの中核機能実装", 37),
376 "Specs管理システムの中核機能実装"
377 );
378 assert_eq!(
379 truncate("Specs管理システムの中核機能実装", 10),
380 "Specs管理..."
381 );
382 }
383
384 #[test]
385 fn test_truncate_edge_cases() {
386 assert_eq!(truncate("", 10), "");
387 assert_eq!(truncate("a", 1), "a");
388 assert_eq!(truncate("ab", 2), "ab");
389 assert_eq!(truncate("abc", 3), "abc");
390 assert_eq!(truncate("abcd", 3), "...");
391 }
392}