-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathuser_output.rs
More file actions
681 lines (605 loc) · 22.9 KB
/
Copy pathuser_output.rs
File metadata and controls
681 lines (605 loc) · 22.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
//! `UserOutput` struct and implementation
//!
//! This module provides the main `UserOutput` struct which handles user-facing output
//! formatting and routing. It implements a sink-based architecture with support for
//! multiple output destinations, themes, verbosity levels, and custom formatters.
//!
//! The `UserOutput` struct is the primary interface for displaying messages to users,
//! following Unix conventions with dual-channel output (stdout for results, stderr
//! for progress and status messages).
// Standard library imports
use std::io::Write;
// Internal crate imports
use super::messages::{
BlankLineMessage, ErrorMessage, InfoBlockMessage, ProgressMessage, ResultMessage, StepsMessage,
SuccessMessage, WarningMessage,
};
use super::sinks::StandardSink;
use super::verbosity::VerbosityFilter;
use super::{FormatterOverride, OutputMessage, OutputSink, Theme, VerbosityLevel};
/// User-facing output handler with sink-based architecture
///
/// `UserOutput` provides a clean interface for displaying messages to users with support for:
/// - Multiple output sinks (console, file, telemetry, etc.)
/// - Verbosity levels (quiet, normal, verbose, debug)
/// - Customizable themes (emoji, plain text, ASCII)
/// - Optional formatter overrides (JSON, colored output)
/// - Dual-channel routing (stdout for results, stderr for progress)
///
/// # Examples
///
/// Basic usage:
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::views::{UserOutput, VerbosityLevel};
///
/// let mut output = UserOutput::new(VerbosityLevel::Normal);
/// output.progress("Starting operation...");
/// output.success("Operation completed successfully");
/// output.result(r#"{"status": "completed"}"#);
/// ```
///
/// With custom theme:
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::views::{UserOutput, VerbosityLevel, Theme};
///
/// let mut output = UserOutput::with_theme(VerbosityLevel::Normal, Theme::plain());
/// output.progress("Processing...");
/// ```
pub struct UserOutput {
theme: Theme,
verbosity_filter: VerbosityFilter,
sink: Box<dyn OutputSink>,
formatter_override: Option<Box<dyn FormatterOverride>>,
}
impl UserOutput {
/// Create new `UserOutput` with default stdout/stderr channels and emoji theme
///
/// Uses `StandardSink` for backward compatibility with existing console output.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::views::{UserOutput, VerbosityLevel};
///
/// let output = UserOutput::new(VerbosityLevel::Normal);
/// ```
#[must_use]
pub fn new(verbosity: VerbosityLevel) -> Self {
Self::with_theme(verbosity, Theme::default())
}
/// Create `UserOutput` with a specific theme
///
/// Allows customization of output symbols while using default stdout/stderr channels.
/// Uses `StandardSink` internally for backward compatibility.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::views::{UserOutput, VerbosityLevel, Theme};
///
/// // Use plain text theme for CI/CD
/// let output = UserOutput::with_theme(VerbosityLevel::Normal, Theme::plain());
///
/// // Use ASCII theme for limited terminals
/// let output = UserOutput::with_theme(VerbosityLevel::Normal, Theme::ascii());
/// ```
#[must_use]
pub fn with_theme(verbosity: VerbosityLevel, theme: Theme) -> Self {
Self::with_sink(verbosity, Box::new(StandardSink::default_console()))
.with_theme_applied(theme)
}
/// Create `UserOutput` with theme and custom writers (for testing)
///
/// This constructor allows full customization including theme and writers,
/// primarily used for testing where output needs to be captured.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::views::{UserOutput, VerbosityLevel, Theme};
/// use std::io::Cursor;
///
/// let stdout_buf = Vec::new();
/// let stderr_buf = Vec::new();
///
/// let output = UserOutput::with_theme_and_writers(
/// VerbosityLevel::Normal,
/// Theme::plain(),
/// Box::new(Cursor::new(stdout_buf)),
/// Box::new(Cursor::new(stderr_buf)),
/// );
/// ```
#[must_use]
pub fn with_theme_and_writers(
verbosity: VerbosityLevel,
theme: Theme,
stdout_writer: Box<dyn Write + Send + Sync>,
stderr_writer: Box<dyn Write + Send + Sync>,
) -> Self {
Self {
theme,
verbosity_filter: VerbosityFilter::new(verbosity),
sink: Box::new(StandardSink::new(stdout_writer, stderr_writer)),
formatter_override: None,
}
}
/// Display progress message to stderr (Normal level and above)
///
/// Progress messages go to stderr following cargo/docker patterns.
/// This keeps stdout clean for result data that may be piped.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::views::{UserOutput, VerbosityLevel};
///
/// let mut output = UserOutput::new(VerbosityLevel::Normal);
/// output.progress("Destroying environment...");
/// // Output to stderr: ⏳ Destroying environment...
/// ```
pub fn progress(&mut self, message: &str) {
self.write(&ProgressMessage {
text: message.to_string(),
});
}
/// Display success message to stderr (Normal level and above)
///
/// Success status goes to stderr to allow clean result piping.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::views::{UserOutput, VerbosityLevel};
///
/// let mut output = UserOutput::new(VerbosityLevel::Normal);
/// output.success("Environment destroyed successfully");
/// // Output to stderr: ✅ Environment destroyed successfully
/// ```
pub fn success(&mut self, message: &str) {
self.write(&SuccessMessage {
text: message.to_string(),
});
}
/// Display warning message to stderr (Normal level and above)
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::views::{UserOutput, VerbosityLevel};
///
/// let mut output = UserOutput::new(VerbosityLevel::Normal);
/// output.warn("Infrastructure may already be destroyed");
/// // Output to stderr: ⚠️ Infrastructure may already be destroyed
/// ```
pub fn warn(&mut self, message: &str) {
self.write(&WarningMessage {
text: message.to_string(),
});
}
/// Display error message to stderr (all levels)
///
/// Errors are always shown regardless of verbosity level.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::views::{UserOutput, VerbosityLevel};
///
/// let mut output = UserOutput::new(VerbosityLevel::Quiet);
/// output.error("Failed to destroy environment");
/// // Output to stderr: ❌ Failed to destroy environment
/// ```
pub fn error(&mut self, message: &str) {
self.write(&ErrorMessage {
text: message.to_string(),
});
}
/// Output final results to stdout for piping/redirection
///
/// This is where deployment results, configuration summaries, etc. go.
/// Since this goes to stdout, it can be cleanly piped to other commands.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::views::{UserOutput, VerbosityLevel};
///
/// let mut output = UserOutput::new(VerbosityLevel::Normal);
/// output.result("Deployment complete");
/// // Output to stdout: Deployment complete
/// ```
pub fn result(&mut self, message: &str) {
self.write(&ResultMessage {
text: message.to_string(),
});
}
/// Output structured data to stdout (JSON, etc.)
///
/// For machine-readable output that should be piped or processed.
/// This is equivalent to `result()` but exists for semantic clarity.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::views::{UserOutput, VerbosityLevel};
///
/// let mut output = UserOutput::new(VerbosityLevel::Normal);
/// output.data(r#"{"status": "destroyed", "environment": "test"}"#);
/// // Output to stdout: {"status": "destroyed", "environment": "test"}
/// ```
pub fn data(&mut self, data: &str) {
self.result(data);
}
/// Display a blank line to stderr (Normal level and above)
///
/// Used for spacing between sections of output to improve readability.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::views::{UserOutput, VerbosityLevel};
///
/// let mut output = UserOutput::new(VerbosityLevel::Normal);
/// output.success("Configuration template generated");
/// output.blank_line();
/// output.progress("Starting next steps...");
/// ```
pub fn blank_line(&mut self) {
self.write(&BlankLineMessage);
}
/// Display a numbered list of steps to stderr (Normal level and above)
///
/// Useful for displaying sequential instructions or action items.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::views::{UserOutput, VerbosityLevel};
///
/// let mut output = UserOutput::new(VerbosityLevel::Normal);
/// output.steps("Next steps:", &[
/// "Edit the configuration file",
/// "Review the settings",
/// "Run the deploy command",
/// ]);
/// // Output to stderr:
/// // Next steps:
/// // 1. Edit the configuration file
/// // 2. Review the settings
/// // 3. Run the deploy command
/// ```
pub fn steps(&mut self, title: &str, steps: &[&str]) {
self.write(&StepsMessage {
title: title.to_string(),
items: steps.iter().map(|s| (*s).to_string()).collect(),
});
}
/// Display a multi-line information block to stderr (Normal level and above)
///
/// Useful for displaying grouped information or detailed messages.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::views::{UserOutput, VerbosityLevel};
///
/// let mut output = UserOutput::new(VerbosityLevel::Normal);
/// output.info_block("Configuration options:", &[
/// " - username: 'torrust' (default)",
/// " - port: 22 (default SSH port)",
/// " - key_path: path/to/key",
/// ]);
/// // Output to stderr:
/// // Configuration options:
/// // - username: 'torrust' (default)
/// // - port: 22 (default SSH port)
/// // - key_path: path/to/key
/// ```
pub fn info_block(&mut self, title: &str, lines: &[&str]) {
self.write(&InfoBlockMessage {
title: title.to_string(),
lines: lines.iter().map(|s| (*s).to_string()).collect(),
});
}
/// Create `UserOutput` with a custom sink
///
/// This constructor enables the use of alternative output destinations,
/// including composite sinks for multi-destination output.
///
/// # Examples
///
/// ```rust,ignore
/// use torrust_tracker_deployer_lib::presentation::views::{
/// UserOutput, VerbosityLevel, CompositeSink, StandardSink, FileSink
/// };
///
/// // Console + File output
/// let composite = CompositeSink::new(vec![
/// Box::new(StandardSink::default_console()),
/// Box::new(FileSink::new("output.log").unwrap()),
/// ]);
/// let output = UserOutput::with_sink(VerbosityLevel::Normal, Box::new(composite));
/// ```
#[must_use]
fn with_sink(verbosity: VerbosityLevel, sink: Box<dyn OutputSink>) -> Self {
Self {
theme: Theme::default(),
verbosity_filter: VerbosityFilter::new(verbosity),
sink,
formatter_override: None,
}
}
/// Internal helper to apply theme to an existing `UserOutput`
fn with_theme_applied(mut self, theme: Theme) -> Self {
self.theme = theme;
self
}
/// Write a message to the appropriate channel using trait dispatch
///
/// This is the core method for extensible message handling. It uses the
/// `OutputMessage` trait to determine formatting, verbosity requirements,
/// and channel routing. Messages are routed through the configured sink,
/// enabling multi-destination output.
///
/// # Examples
///
/// ```rust,ignore
/// use torrust_tracker_deployer_lib::presentation::views::{UserOutput, VerbosityLevel, ProgressMessage};
///
/// let mut output = UserOutput::new(VerbosityLevel::Normal);
/// output.write(&ProgressMessage {
/// text: "Processing...".to_string(),
/// });
/// ```
fn write(&mut self, message: &dyn OutputMessage) {
if !self
.verbosity_filter
.should_show(message.required_verbosity())
{
return;
}
let mut formatted = message.format(&self.theme);
// Apply optional format override
if let Some(override_formatter) = &self.formatter_override {
formatted = override_formatter.transform(&formatted, message);
}
// Write through sink
self.sink.write_message(message, &formatted);
}
}
#[cfg(test)]
mod tests {
use super::*;
mod verbosity {
use super::*;
use crate::presentation::views::testing::TestUserOutput;
use crate::presentation::views::Channel;
/// Test message that requires Verbose level
struct TestVerboseMessage {
text: String,
}
impl OutputMessage for TestVerboseMessage {
fn format(&self, _theme: &Theme) -> String {
format!("TEST: {}\n", self.text)
}
fn required_verbosity(&self) -> VerbosityLevel {
VerbosityLevel::Verbose
}
fn channel(&self) -> Channel {
Channel::Stderr
}
fn type_name(&self) -> &'static str {
"TestVerboseMessage"
}
}
#[test]
fn it_should_ignore_message_when_verbosity_level_is_below_required() {
// Create UserOutput with Normal verbosity
let mut test_output = TestUserOutput::new(VerbosityLevel::Normal);
// Create a message that requires Verbose level (higher than Normal)
let message = TestVerboseMessage {
text: "This should not appear".to_string(),
};
// Try to write the message - should be ignored due to insufficient verbosity
test_output.output.write(&message);
// Both stdout and stderr should be empty since message was filtered out
assert_eq!(test_output.stdout(), "");
assert_eq!(test_output.stderr(), "");
}
}
mod formatter {
use super::*;
use crate::presentation::views::formatters::JsonFormatter;
use crate::presentation::views::testing::TestWriter;
use crate::presentation::views::Channel;
use parking_lot::Mutex;
use std::sync::Arc;
/// Test message with Normal verbosity for formatter testing
struct TestNormalMessage {
text: String,
}
impl OutputMessage for TestNormalMessage {
fn format(&self, _theme: &Theme) -> String {
format!("MSG: {}\n", self.text)
}
fn required_verbosity(&self) -> VerbosityLevel {
VerbosityLevel::Normal
}
fn channel(&self) -> Channel {
Channel::Stderr
}
fn type_name(&self) -> &'static str {
"TestNormalMessage"
}
}
#[test]
fn it_should_apply_formatter_override_to_transform_message() {
// Create buffers for capturing output
let stderr_buffer = Arc::new(Mutex::new(Vec::new()));
let stdout_buffer = Arc::new(Mutex::new(Vec::new()));
// Create UserOutput with JsonFormatter
let mut output = UserOutput {
theme: Theme::default(),
verbosity_filter: VerbosityFilter::new(VerbosityLevel::Normal),
sink: Box::new(StandardSink::new(
Box::new(TestWriter::new(Arc::clone(&stdout_buffer))),
Box::new(TestWriter::new(Arc::clone(&stderr_buffer))),
)),
formatter_override: Some(Box::new(JsonFormatter)),
};
// Create and write a test message
let message = TestNormalMessage {
text: "test message".to_string(),
};
output.write(&message);
// Verify the formatter transformed the output to JSON format
let stderr_output = String::from_utf8(stderr_buffer.lock().clone()).unwrap();
// Parse JSON to verify structure (timestamp is dynamic, so we check fields exist)
let json: serde_json::Value = serde_json::from_str(&stderr_output).unwrap();
assert_eq!(json["type"], "TestNormalMessage");
assert_eq!(json["channel"], "Stderr");
assert_eq!(json["content"], "MSG: test message");
assert!(json["timestamp"].is_string());
// Stdout should be empty (message goes to stderr)
let stdout_output = String::from_utf8(stdout_buffer.lock().clone()).unwrap();
assert_eq!(stdout_output, "");
}
}
mod theme {
use super::*;
use crate::presentation::views::testing::TestUserOutput;
use crate::presentation::views::Channel;
use rstest::rstest;
/// Test message that uses theme symbols in formatting
struct TestThemedMessage {
text: String,
}
impl OutputMessage for TestThemedMessage {
fn format(&self, theme: &Theme) -> String {
format!("{} {}\n", theme.success_symbol(), self.text)
}
fn required_verbosity(&self) -> VerbosityLevel {
VerbosityLevel::Normal
}
fn channel(&self) -> Channel {
Channel::Stderr
}
fn type_name(&self) -> &'static str {
"TestThemedMessage"
}
}
#[rstest]
#[case(Theme::emoji(), "✅ Operation completed\n")]
#[case(Theme::plain(), "[OK] Operation completed\n")]
#[case(Theme::ascii(), "[+] Operation completed\n")]
fn it_should_format_message_differently_with_different_themes(
#[case] theme: Theme,
#[case] expected_output: &str,
) {
let mut test_output = TestUserOutput::with_theme(VerbosityLevel::Normal, theme);
let message = TestThemedMessage {
text: "Operation completed".to_string(),
};
test_output.output.write(&message);
assert_eq!(test_output.stderr(), expected_output);
}
}
mod sink {
use super::*;
use crate::presentation::views::testing::TestWriter;
use crate::presentation::views::Channel;
use parking_lot::Mutex;
use std::sync::Arc;
/// Test message for sink redirection testing
struct TestSinkMessage {
text: String,
}
impl OutputMessage for TestSinkMessage {
fn format(&self, _theme: &Theme) -> String {
format!("SINK_TEST: {}\n", self.text)
}
fn required_verbosity(&self) -> VerbosityLevel {
VerbosityLevel::Normal
}
fn channel(&self) -> Channel {
Channel::Stderr
}
fn type_name(&self) -> &'static str {
"TestSinkMessage"
}
}
#[test]
fn it_should_write_output_to_custom_sink() {
// Create custom buffers to capture output
let stderr_buffer = Arc::new(Mutex::new(Vec::new()));
let stdout_buffer = Arc::new(Mutex::new(Vec::new()));
// Create UserOutput with custom sink using TestWriter
let mut output = UserOutput {
theme: Theme::default(),
verbosity_filter: VerbosityFilter::new(VerbosityLevel::Normal),
sink: Box::new(StandardSink::new(
Box::new(TestWriter::new(Arc::clone(&stdout_buffer))),
Box::new(TestWriter::new(Arc::clone(&stderr_buffer))),
)),
formatter_override: None,
};
// Write a message
let message = TestSinkMessage {
text: "custom sink output".to_string(),
};
output.write(&message);
// Verify output was captured in custom sink (stderr buffer)
let stderr_output = String::from_utf8(stderr_buffer.lock().clone()).unwrap();
assert_eq!(stderr_output, "SINK_TEST: custom sink output\n");
// Stdout should be empty (message goes to stderr)
let stdout_output = String::from_utf8(stdout_buffer.lock().clone()).unwrap();
assert_eq!(stdout_output, "");
}
}
mod channel_routing {
use super::*;
use crate::presentation::views::testing::TestUserOutput;
use crate::presentation::views::Channel;
use rstest::rstest;
/// Test message that can be configured to go to either channel
struct TestChannelMessage {
text: String,
target_channel: Channel,
}
impl OutputMessage for TestChannelMessage {
fn format(&self, _theme: &Theme) -> String {
format!("CHANNEL: {}\n", self.text)
}
fn required_verbosity(&self) -> VerbosityLevel {
VerbosityLevel::Normal
}
fn channel(&self) -> Channel {
self.target_channel
}
fn type_name(&self) -> &'static str {
"TestChannelMessage"
}
}
#[rstest]
#[case(Channel::Stdout, "CHANNEL: stdout message\n", "")]
#[case(Channel::Stderr, "", "CHANNEL: stderr message\n")]
fn it_should_route_message_to_correct_channel(
#[case] channel: Channel,
#[case] expected_stdout: &str,
#[case] expected_stderr: &str,
) {
let mut test_output = TestUserOutput::new(VerbosityLevel::Normal);
let message_text = match channel {
Channel::Stdout => "stdout message",
Channel::Stderr => "stderr message",
};
let message = TestChannelMessage {
text: message_text.to_string(),
target_channel: channel,
};
test_output.output.write(&message);
assert_eq!(test_output.stdout(), expected_stdout);
assert_eq!(test_output.stderr(), expected_stderr);
}
}
}