-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathuser_output.rs
More file actions
4226 lines (3657 loc) · 143 KB
/
Copy pathuser_output.rs
File metadata and controls
4226 lines (3657 loc) · 143 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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! User-facing output handling
//!
//! This module provides user-facing output functionality separate from internal logging.
//! It implements a dual-channel strategy following Unix conventions and modern CLI best practices
//! (similar to cargo, docker, npm):
//!
//! - **stdout (Results Channel)**: Final results, structured data, output for piping/redirection
//! - **stderr (Progress/Operational Channel)**: Progress updates, status messages, warnings, errors
//!
//! This separation enables:
//! - Clean piping: `torrust-tracker-deployer destroy env | jq .status` works correctly
//! - Automation friendly: Scripts can redirect progress to /dev/null while capturing results
//! - Unix convention compliance: Follows established patterns from modern CLI tools
//! - Better UX: Progress feedback doesn't interfere with result data
//!
//! ## Type-Safe Channel Routing
//!
//! The module uses newtype wrappers (`StdoutWriter` and `StderrWriter`) to provide compile-time
//! guarantees that messages are routed to the correct output channel. This prevents accidental
//! channel confusion and makes the code more maintainable by catching routing errors at compile
//! time rather than runtime.
//!
//! The newtype pattern is a zero-cost abstraction - it has the same memory layout and performance
//! characteristics as the wrapped type, but provides type safety benefits.
//!
//! ## Buffering Behavior
//!
//! Output is line-buffered by default. Messages are typically flushed automatically
//! after each newline. For cases where immediate output is critical (e.g., before
//! long-running operations), call `flush()` explicitly:
//!
//! ```rust,ignore
//! output.progress("Starting long operation...");
//! output.flush()?; // Ensure message appears before operation starts
//! perform_long_operation();
//! ```
//!
//! ## Example Usage
//!
//! ```rust
//! use torrust_tracker_deployer_lib::presentation::user_output::{UserOutput, VerbosityLevel};
//!
//! let mut output = UserOutput::new(VerbosityLevel::Normal);
//!
//! // Progress messages go to stderr
//! output.progress("Destroying environment...");
//!
//! // Success status goes to stderr
//! output.success("Environment destroyed successfully");
//!
//! // Results go to stdout for piping
//! output.result(r#"{"status": "destroyed"}"#);
//! ```
//!
//! ## Channel Strategy
//!
//! Based on research from [`docs/research/UX/console-app-output-patterns.md`](../../docs/research/UX/console-app-output-patterns.md):
//!
//! - **stdout**: Deployment results, configuration summaries, structured data (JSON)
//! - **stderr**: Step progress, status updates, warnings, error messages with actionable guidance
//!
//! See also: [`docs/research/UX/user-output-vs-logging-separation.md`](../../docs/research/UX/user-output-vs-logging-separation.md)
use std::io::Write;
/// Output theme controlling symbols and formatting
///
/// A theme defines the visual appearance of user-facing messages through
/// configurable symbols. Themes enable consistent styling across all output
/// and support different environments (terminals, CI/CD, accessibility needs).
///
/// # Predefined Themes
///
/// - **Emoji** (default): Unicode emoji symbols for interactive terminals
/// - **Plain**: Text labels like `[INFO]`, `[OK]` for CI/CD environments
/// - **ASCII**: Basic ASCII characters for limited terminal support
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::Theme;
///
/// // Use emoji theme (default)
/// let theme = Theme::emoji();
/// assert_eq!(theme.progress_symbol(), "⏳");
///
/// // Use plain text theme for CI/CD
/// let theme = Theme::plain();
/// assert_eq!(theme.success_symbol(), "[OK]");
///
/// // Use ASCII theme for limited terminals
/// let theme = Theme::ascii();
/// assert_eq!(theme.error_symbol(), "[x]");
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[allow(clippy::struct_field_names)]
pub struct Theme {
progress_symbol: String,
success_symbol: String,
warning_symbol: String,
error_symbol: String,
}
impl Theme {
/// Create emoji theme with Unicode symbols (default)
///
/// Best for interactive terminals with good Unicode support.
/// Uses emoji characters that are visually distinctive and widely supported.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::Theme;
///
/// let theme = Theme::emoji();
/// assert_eq!(theme.progress_symbol(), "⏳");
/// assert_eq!(theme.success_symbol(), "✅");
/// assert_eq!(theme.warning_symbol(), "⚠️");
/// assert_eq!(theme.error_symbol(), "❌");
/// ```
#[must_use]
pub fn emoji() -> Self {
Self {
progress_symbol: "⏳".to_string(),
success_symbol: "✅".to_string(),
warning_symbol: "⚠️".to_string(),
error_symbol: "❌".to_string(),
}
}
/// Create plain text theme for CI/CD environments
///
/// Uses text labels like `[INFO]`, `[OK]`, `[WARN]`, `[ERROR]` that work
/// in any environment without Unicode support. Ideal for CI/CD pipelines
/// and log aggregation systems.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::Theme;
///
/// let theme = Theme::plain();
/// assert_eq!(theme.progress_symbol(), "[INFO]");
/// assert_eq!(theme.success_symbol(), "[OK]");
/// assert_eq!(theme.warning_symbol(), "[WARN]");
/// assert_eq!(theme.error_symbol(), "[ERROR]");
/// ```
#[must_use]
pub fn plain() -> Self {
Self {
progress_symbol: "[INFO]".to_string(),
success_symbol: "[OK]".to_string(),
warning_symbol: "[WARN]".to_string(),
error_symbol: "[ERROR]".to_string(),
}
}
/// Create ASCII-only theme using basic characters
///
/// Uses simple ASCII characters that work on any terminal.
/// Good for environments with limited character set support or
/// when maximum compatibility is required.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::Theme;
///
/// let theme = Theme::ascii();
/// assert_eq!(theme.progress_symbol(), "=>");
/// assert_eq!(theme.success_symbol(), "[+]");
/// assert_eq!(theme.warning_symbol(), "[!]");
/// assert_eq!(theme.error_symbol(), "[x]");
/// ```
#[must_use]
pub fn ascii() -> Self {
Self {
progress_symbol: "=>".to_string(),
success_symbol: "[+]".to_string(),
warning_symbol: "[!]".to_string(),
error_symbol: "[x]".to_string(),
}
}
/// Get the progress symbol for this theme
#[must_use]
pub fn progress_symbol(&self) -> &str {
&self.progress_symbol
}
/// Get the success symbol for this theme
#[must_use]
pub fn success_symbol(&self) -> &str {
&self.success_symbol
}
/// Get the warning symbol for this theme
#[must_use]
pub fn warning_symbol(&self) -> &str {
&self.warning_symbol
}
/// Get the error symbol for this theme
#[must_use]
pub fn error_symbol(&self) -> &str {
&self.error_symbol
}
}
impl Default for Theme {
/// Create the default theme (emoji)
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::Theme;
///
/// let theme = Theme::default();
/// assert_eq!(theme.progress_symbol(), "⏳");
/// ```
fn default() -> Self {
Self::emoji()
}
}
/// Output channel for routing messages
///
/// Determines whether a message should be written to stdout or stderr.
/// Following Unix conventions:
/// - **stdout**: Final results and structured data for piping/redirection
/// - **stderr**: Progress updates, status messages, operational info, errors
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::Channel;
///
/// let channel = Channel::Stdout;
/// assert_eq!(channel, Channel::Stdout);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Channel {
/// Standard output stream for final results and data
Stdout,
/// Standard error stream for progress and operational messages
Stderr,
}
/// Trait for output messages that can be written to user-facing channels
///
/// This trait enables extensibility following the Open/Closed Principle.
/// Each message type encapsulates its own:
/// - Formatting logic (how it appears to users)
/// - Verbosity requirements (when it should be shown)
/// - Channel routing (stdout vs stderr)
///
/// # Design Philosophy
///
/// By implementing this trait, message types become self-contained and can be
/// added without modifying the `UserOutput` struct. This makes the system
/// extensible - new message types can be defined in external modules.
///
/// # Examples
///
/// ```rust,ignore
/// use torrust_tracker_deployer_lib::presentation::user_output::{OutputMessage, Theme, VerbosityLevel, Channel};
///
/// struct CustomMessage {
/// text: String,
/// }
///
/// impl OutputMessage for CustomMessage {
/// fn format(&self, theme: &Theme) -> String {
/// format!("🎉 {}", self.text)
/// }
///
/// fn required_verbosity(&self) -> VerbosityLevel {
/// VerbosityLevel::Normal
/// }
///
/// fn channel(&self) -> Channel {
/// Channel::Stderr
/// }
///
/// fn type_name(&self) -> &'static str {
/// "CustomMessage"
/// }
/// }
/// ```
pub trait OutputMessage {
/// Format this message using the given theme
///
/// This method defines how the message appears to users. It should
/// incorporate theme symbols and any necessary formatting.
///
/// # Arguments
///
/// * `theme` - The theme providing symbols for formatting
///
/// # Returns
///
/// A formatted string ready for display to users
fn format(&self, theme: &Theme) -> String;
/// Get the minimum verbosity level required to show this message
///
/// Messages are only displayed if the current verbosity level is
/// greater than or equal to the required level.
///
/// # Returns
///
/// The minimum verbosity level needed to display this message
fn required_verbosity(&self) -> VerbosityLevel;
/// Get the output channel for this message
///
/// Determines whether the message goes to stdout or stderr following
/// Unix conventions.
///
/// # Returns
///
/// The channel (Stdout or Stderr) where this message should be written
fn channel(&self) -> Channel;
/// Get the type name of this message
///
/// Returns a human-readable type identifier for this message type.
/// This is primarily used by formatter overrides (e.g., JSON formatter)
/// to include type information in the output.
///
/// # Returns
///
/// A static string representing the message type name
fn type_name(&self) -> &'static str;
}
/// Optional trait for post-processing message output
///
/// This allows transforming the standard message format without
/// modifying individual message types. Use sparingly - prefer
/// extending the message trait or using themes for most cases.
///
/// # When to Use
///
/// - **Machine-readable formats**: JSON, XML, structured logs
/// - **Additional decoration**: ANSI colors, markup codes
/// - **Output wrapping**: Adding metadata, timestamps, process info
///
/// # When NOT to Use
///
/// - **Symbol changes**: Use `Theme` instead
/// - **New message types**: Implement `OutputMessage` trait instead
/// - **Channel routing changes**: Define in message type's `channel()` method
///
/// # Examples
///
/// ```rust,ignore
/// use torrust_tracker_deployer_lib::presentation::user_output::{FormatterOverride, OutputMessage};
///
/// struct JsonFormatter;
///
/// impl FormatterOverride for JsonFormatter {
/// fn transform(&self, formatted: &str, message: &dyn OutputMessage) -> String {
/// // Transform to JSON representation
/// format!(r#"{{"content": "{}"}}"#, formatted.trim())
/// }
/// }
/// ```
pub trait FormatterOverride: Send + Sync {
/// Transform formatted message output
///
/// This method receives the already-formatted message (with theme applied)
/// and the original message object for context. It should return the
/// transformed output.
///
/// # Arguments
///
/// * `formatted` - The message already formatted with theme
/// * `message` - The original message object (for metadata/context)
///
/// # Returns
///
/// The transformed message string
fn transform(&self, formatted: &str, message: &dyn OutputMessage) -> String;
}
/// Trait for output destinations
///
/// An output sink receives formatted messages and writes them to a destination.
/// Sinks handle the mechanics of where output goes, not how it's formatted.
///
/// # Design Philosophy
///
/// Sinks receive already-formatted messages (with theme applied) and route them
/// to appropriate destinations. They don't handle formatting or verbosity filtering -
/// those concerns are handled by message types and filters respectively.
///
/// # Examples
///
/// ```rust,ignore
/// use torrust_tracker_deployer_lib::presentation::user_output::{OutputSink, OutputMessage};
/// use std::fs::File;
///
/// struct FileSink {
/// file: File,
/// }
///
/// impl OutputSink for FileSink {
/// fn write_message(&mut self, message: &dyn OutputMessage, formatted: &str) {
/// use std::io::Write;
/// writeln!(self.file, "{}", formatted).ok();
/// }
/// }
/// ```
pub trait OutputSink: Send + Sync {
/// Write a formatted message to this sink
///
/// # Arguments
///
/// * `message` - The message object (for metadata like channel)
/// * `formatted` - The already-formatted message text
fn write_message(&mut self, message: &dyn OutputMessage, formatted: &str);
}
/// Verbosity levels for user output
///
/// Controls the amount of detail shown to users. Higher verbosity levels include
/// all output from lower levels.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::VerbosityLevel;
///
/// let level = VerbosityLevel::Normal;
/// assert!(level >= VerbosityLevel::Quiet);
/// assert!(level < VerbosityLevel::Verbose);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
pub enum VerbosityLevel {
/// Minimal output - only errors and final results
Quiet,
/// Default level - essential progress and results
#[default]
Normal,
/// Detailed progress including intermediate steps
Verbose,
/// Very detailed including decisions and retries
VeryVerbose,
/// Maximum detail for troubleshooting
Debug,
}
// ============================================================================
// Formatter Override Implementations
// ============================================================================
/// JSON formatter for machine-readable output
///
/// Transforms messages into JSON objects with metadata including:
/// - Message type (for programmatic filtering)
/// - Channel (stdout/stderr)
/// - Content (the formatted message)
/// - Timestamp (ISO 8601 format)
///
/// # Examples
///
/// ```rust,ignore
/// use torrust_tracker_deployer_lib::presentation::user_output::{JsonFormatter, UserOutput, VerbosityLevel};
///
/// let formatter = JsonFormatter;
/// let mut output = UserOutput::with_formatter_override(
/// VerbosityLevel::Normal,
/// Box::new(formatter)
/// );
///
/// output.progress("Starting process");
/// // Output: {"type":"ProgressMessage","channel":"Stderr","content":"⏳ Starting process","timestamp":"2025-11-04T12:34:56Z"}
/// ```
pub struct JsonFormatter;
impl FormatterOverride for JsonFormatter {
fn transform(&self, formatted: &str, message: &dyn OutputMessage) -> String {
let json = serde_json::json!({
"type": message.type_name(),
"channel": format!("{:?}", message.channel()),
"content": formatted.trim(), // Remove trailing newlines for cleaner JSON
"timestamp": chrono::Utc::now().to_rfc3339(),
})
.to_string();
format!("{json}\n")
}
}
// ============================================================================
// Concrete Message Type Implementations
// ============================================================================
/// Progress message for ongoing operations
///
/// Progress messages indicate that work is in progress. They are displayed
/// during operations to provide feedback to users.
///
/// # Examples
///
/// ```rust,ignore
/// use torrust_tracker_deployer_lib::presentation::user_output::ProgressMessage;
///
/// let message = ProgressMessage {
/// text: "Destroying environment...".to_string(),
/// };
/// ```
pub struct ProgressMessage {
/// The progress message text
pub text: String,
}
impl OutputMessage for ProgressMessage {
fn format(&self, theme: &Theme) -> String {
format!("{} {}\n", theme.progress_symbol(), self.text)
}
fn required_verbosity(&self) -> VerbosityLevel {
VerbosityLevel::Normal
}
fn channel(&self) -> Channel {
Channel::Stderr
}
fn type_name(&self) -> &'static str {
"ProgressMessage"
}
}
/// Success message for completed operations
///
/// Success messages indicate that an operation completed successfully.
/// They provide positive feedback to users.
///
/// # Examples
///
/// ```rust,ignore
/// use torrust_tracker_deployer_lib::presentation::user_output::SuccessMessage;
///
/// let message = SuccessMessage {
/// text: "Environment destroyed successfully".to_string(),
/// };
/// ```
pub struct SuccessMessage {
/// The success message text
pub text: String,
}
impl OutputMessage for SuccessMessage {
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 {
"SuccessMessage"
}
}
/// Warning message for non-critical issues
///
/// Warning messages alert users to potential issues that don't prevent
/// operation completion but may need attention.
///
/// # Examples
///
/// ```rust,ignore
/// use torrust_tracker_deployer_lib::presentation::user_output::WarningMessage;
///
/// let message = WarningMessage {
/// text: "Infrastructure may already be destroyed".to_string(),
/// };
/// ```
pub struct WarningMessage {
/// The warning message text
pub text: String,
}
impl OutputMessage for WarningMessage {
fn format(&self, theme: &Theme) -> String {
format!("{} {}\n", theme.warning_symbol(), self.text)
}
fn required_verbosity(&self) -> VerbosityLevel {
VerbosityLevel::Normal
}
fn channel(&self) -> Channel {
Channel::Stderr
}
fn type_name(&self) -> &'static str {
"WarningMessage"
}
}
/// Error message for critical failures
///
/// Error messages indicate critical failures that prevent operation completion.
/// They are always shown regardless of verbosity level.
///
/// # Examples
///
/// ```rust,ignore
/// use torrust_tracker_deployer_lib::presentation::user_output::ErrorMessage;
///
/// let message = ErrorMessage {
/// text: "Failed to destroy environment".to_string(),
/// };
/// ```
pub struct ErrorMessage {
/// The error message text
pub text: String,
}
impl OutputMessage for ErrorMessage {
fn format(&self, theme: &Theme) -> String {
format!("{} {}\n", theme.error_symbol(), self.text)
}
fn required_verbosity(&self) -> VerbosityLevel {
VerbosityLevel::Quiet // Always shown
}
fn channel(&self) -> Channel {
Channel::Stderr
}
fn type_name(&self) -> &'static str {
"ErrorMessage"
}
}
/// Result message for final output data
///
/// Result messages contain final output data that can be piped or redirected.
/// They go to stdout without any symbols or formatting.
///
/// # Examples
///
/// ```rust,ignore
/// use torrust_tracker_deployer_lib::presentation::user_output::ResultMessage;
///
/// let message = ResultMessage {
/// text: "Deployment complete".to_string(),
/// };
/// ```
pub struct ResultMessage {
/// The result message text
pub text: String,
}
impl OutputMessage for ResultMessage {
fn format(&self, _theme: &Theme) -> String {
format!("{}\n", self.text)
}
fn required_verbosity(&self) -> VerbosityLevel {
VerbosityLevel::Quiet
}
fn channel(&self) -> Channel {
Channel::Stdout
}
fn type_name(&self) -> &'static str {
"ResultMessage"
}
}
/// Steps message for sequential instructions
///
/// Steps messages display numbered lists of sequential items.
/// Useful for showing action items or instructions.
///
/// # Examples
///
/// Simple constructor for cases where you have all items upfront:
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::StepsMessage;
///
/// let message = StepsMessage::new("Next steps:", vec![
/// "Edit the configuration file".to_string(),
/// "Review the settings".to_string(),
/// ]);
/// ```
///
/// Builder pattern for dynamic construction or better readability:
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::StepsMessage;
///
/// let message = StepsMessage::builder("Next steps:")
/// .add("Edit the configuration file")
/// .add("Review the settings")
/// .build();
/// ```
pub struct StepsMessage {
/// The title for the steps list
pub title: String,
/// The list of step items
pub items: Vec<String>,
}
impl StepsMessage {
/// Create a new steps message with the given title and items
///
/// This is a convenience constructor for simple cases where you have
/// all items upfront. For dynamic construction or better readability,
/// consider using `StepsMessage::builder()` instead.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::StepsMessage;
///
/// let msg = StepsMessage::new("Next steps:", vec![
/// "Edit config".to_string(),
/// "Run tests".to_string(),
/// ]);
/// ```
#[must_use]
pub fn new(title: impl Into<String>, items: Vec<String>) -> Self {
Self {
title: title.into(),
items,
}
}
/// Create a builder for constructing steps messages with a fluent API
///
/// The builder pattern is useful when:
/// - Adding items dynamically
/// - You want self-documenting, readable code
/// - Building the message in multiple steps
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::StepsMessage;
///
/// let msg = StepsMessage::builder("Next steps:")
/// .add("Edit configuration")
/// .add("Review settings")
/// .build();
/// ```
#[must_use]
pub fn builder(title: impl Into<String>) -> StepsMessageBuilder {
StepsMessageBuilder::new(title)
}
}
impl OutputMessage for StepsMessage {
fn format(&self, _theme: &Theme) -> String {
use std::fmt::Write;
let mut output = format!("{}\n", self.title);
for (idx, step) in self.items.iter().enumerate() {
writeln!(&mut output, "{}. {}", idx + 1, step).ok();
}
output
}
fn required_verbosity(&self) -> VerbosityLevel {
VerbosityLevel::Normal
}
fn channel(&self) -> Channel {
Channel::Stderr
}
fn type_name(&self) -> &'static str {
"StepsMessage"
}
}
/// Builder for constructing `StepsMessage` with a fluent API
///
/// Provides a consuming builder pattern for constructing step messages
/// with optional customization. Use this for complex cases where items
/// are added dynamically or for improved readability. Simple cases can
/// use `StepsMessage::new()` directly.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::StepsMessage;
///
/// let message = StepsMessage::builder("Next steps:")
/// .add("Edit configuration")
/// .add("Review settings")
/// .add("Deploy changes")
/// .build();
/// ```
///
/// Empty builders are valid:
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::StepsMessage;
///
/// let message = StepsMessage::builder("Title").build();
/// ```
pub struct StepsMessageBuilder {
title: String,
items: Vec<String>,
}
impl StepsMessageBuilder {
/// Create a new builder with the given title
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::StepsMessageBuilder;
///
/// let builder = StepsMessageBuilder::new("My steps:");
/// ```
#[must_use]
pub fn new(title: impl Into<String>) -> Self {
Self {
title: title.into(),
items: Vec::new(),
}
}
/// Add a step to the list (consuming self for method chaining)
///
/// This method consumes the builder and returns it, enabling
/// method chaining in a fluent API style.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::StepsMessage;
///
/// let message = StepsMessage::builder("Steps:")
/// .add("First step")
/// .add("Second step")
/// .build();
/// ```
#[must_use]
#[allow(clippy::should_implement_trait)]
pub fn add(mut self, step: impl Into<String>) -> Self {
self.items.push(step.into());
self
}
/// Build the final `StepsMessage`
///
/// Consumes the builder and produces the final message.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::StepsMessage;
///
/// let message = StepsMessage::builder("Steps:")
/// .add("Step 1")
/// .build();
/// ```
#[must_use]
pub fn build(self) -> StepsMessage {
StepsMessage {
title: self.title,
items: self.items,
}
}
}
/// Informational block message for grouped information
///
/// Info block messages display a title followed by multiple lines of text.
/// Useful for displaying grouped information, configuration details, or
/// multi-line informational content.
///
/// # Examples
///
/// Simple constructor for cases where you have all lines upfront:
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::InfoBlockMessage;
///
/// let message = InfoBlockMessage::new("Environment Details", vec![
/// "Name: production".to_string(),
/// "Status: running".to_string(),
/// ]);
/// ```
///
/// Builder pattern for dynamic construction or better readability:
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::InfoBlockMessage;
///
/// let message = InfoBlockMessage::builder("Environment Details")
/// .add_line("Name: production")
/// .add_line("Status: running")
/// .add_line("Uptime: 24 hours")
/// .build();
/// ```
pub struct InfoBlockMessage {
/// The title for the info block
pub title: String,
/// The lines of information
pub lines: Vec<String>,
}
impl InfoBlockMessage {
/// Create a new info block message with the given title and lines
///
/// This is a convenience constructor for simple cases where you have
/// all lines upfront. For dynamic construction or better readability,
/// consider using `InfoBlockMessage::builder()` instead.
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::InfoBlockMessage;
///
/// let msg = InfoBlockMessage::new("Configuration:", vec![
/// " - username: 'torrust'".to_string(),
/// " - port: 22".to_string(),
/// ]);
/// ```
#[must_use]
pub fn new(title: impl Into<String>, lines: Vec<String>) -> Self {
Self {
title: title.into(),
lines,
}
}
/// Create a builder for constructing info block messages with a fluent API
///
/// The builder pattern is useful when:
/// - Adding lines dynamically
/// - You want self-documenting, readable code
/// - Building the message in multiple steps
///
/// # Examples
///
/// ```rust
/// use torrust_tracker_deployer_lib::presentation::user_output::InfoBlockMessage;
///
/// let msg = InfoBlockMessage::builder("Environment Details")
/// .add_line("Name: production")
/// .add_line("Status: active")
/// .build();
/// ```
#[must_use]
pub fn builder(title: impl Into<String>) -> InfoBlockMessageBuilder {
InfoBlockMessageBuilder::new(title)
}
}
impl OutputMessage for InfoBlockMessage {
fn format(&self, _theme: &Theme) -> String {
use std::fmt::Write;
let mut output = format!("{}\n", self.title);
for line in &self.lines {
writeln!(&mut output, "{line}").ok();
}
output
}
fn required_verbosity(&self) -> VerbosityLevel {
VerbosityLevel::Normal
}
fn channel(&self) -> Channel {
Channel::Stderr
}
fn type_name(&self) -> &'static str {
"InfoBlockMessage"
}
}
/// Builder for constructing `InfoBlockMessage` with a fluent API
///
/// Provides a consuming builder pattern for constructing info block messages
/// with optional customization. Use this for complex cases where lines
/// are added dynamically or for improved readability. Simple cases can
/// use `InfoBlockMessage::new()` directly.
///
/// # Examples