fastapi-output 0.3.0

Agent-aware rich console output for fastapi_rust
Documentation
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
//! Rich output facade.
//!
//! Provides a unified interface for console output that automatically
//! adapts to the current environment.

use crate::mode::OutputMode;
use crate::testing::{OutputEntry, OutputLevel, TestOutput};
use crate::themes::FastApiTheme;
use parking_lot::RwLock;
use std::cell::RefCell;
use std::sync::LazyLock;
use std::time::Instant;

const ANSI_RESET: &str = "\x1b[0m";

/// Global instance of `RichOutput` for convenient access.
static GLOBAL_OUTPUT: LazyLock<RwLock<RichOutput>> =
    LazyLock::new(|| RwLock::new(RichOutput::auto()));

thread_local! {
    static TEST_OUTPUT: RefCell<Option<TestOutput>> = const { RefCell::new(None) };
}

/// Get the global `RichOutput` instance.
///
/// # Panics
///
pub fn get_global() -> parking_lot::RwLockReadGuard<'static, RichOutput> {
    GLOBAL_OUTPUT.read()
}

/// Replace the global `RichOutput` instance.
///
/// # Panics
///
pub fn set_global(output: RichOutput) {
    *GLOBAL_OUTPUT.write() = output;
}

/// The main facade for rich console output.
///
/// Provides methods for printing styled text, tables, panels,
/// and other visual elements. Automatically adapts output based
/// on the detected environment.
#[derive(Debug, Clone)]
pub struct RichOutput {
    mode: OutputMode,
    theme: FastApiTheme,
}

impl RichOutput {
    /// Create a new `RichOutput` with the specified mode and default theme.
    #[must_use]
    pub fn new(mode: OutputMode) -> Self {
        Self {
            mode,
            theme: FastApiTheme::default(),
        }
    }

    /// Create a new `RichOutput` with the specified mode.
    #[must_use]
    pub fn with_mode(mode: OutputMode) -> Self {
        Self::new(mode)
    }

    /// Create a new `RichOutput` with auto-detected mode.
    #[must_use]
    pub fn auto() -> Self {
        Self::new(OutputMode::auto())
    }

    /// Create a new `RichOutput` with rich mode (for humans).
    #[must_use]
    pub fn rich() -> Self {
        Self::new(OutputMode::Rich)
    }

    /// Create a new `RichOutput` with plain mode (for agents).
    #[must_use]
    pub fn plain() -> Self {
        Self::new(OutputMode::Plain)
    }

    /// Create a builder for custom configuration.
    #[must_use]
    pub fn builder() -> RichOutputBuilder {
        RichOutputBuilder::new()
    }

    /// Get the current output mode.
    #[must_use]
    pub const fn mode(&self) -> OutputMode {
        self.mode
    }

    /// Set the output mode.
    pub fn set_mode(&mut self, mode: OutputMode) {
        self.mode = mode;
    }

    /// Check if running in agent-friendly mode (plain text output).
    ///
    /// Returns `true` if the output mode is `Plain`, which is the mode
    /// used when an AI agent environment is detected or explicitly requested.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastapi_output::prelude::*;
    ///
    /// let output = RichOutput::plain();
    /// assert!(output.is_agent_mode());
    ///
    /// let output = RichOutput::rich();
    /// assert!(!output.is_agent_mode());
    /// ```
    #[must_use]
    pub const fn is_agent_mode(&self) -> bool {
        matches!(self.mode, OutputMode::Plain)
    }

    /// Get the mode name as a string for logging/debugging.
    ///
    /// Returns one of: `"rich"`, `"plain"`, or `"minimal"`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fastapi_output::prelude::*;
    ///
    /// let output = RichOutput::plain();
    /// assert_eq!(output.mode_name(), "plain");
    /// ```
    #[must_use]
    pub const fn mode_name(&self) -> &'static str {
        self.mode.as_str()
    }

    /// Get the current theme.
    #[must_use]
    pub const fn theme(&self) -> &FastApiTheme {
        &self.theme
    }

    /// Set the theme.
    pub fn set_theme(&mut self, theme: FastApiTheme) {
        self.theme = theme;
    }

    /// Print a success message.
    ///
    /// In rich mode: Green checkmark with styled text.
    /// In plain mode: `[OK] message`
    pub fn success(&self, message: &str) {
        self.status(StatusKind::Success, message);
    }

    /// Print an error message.
    ///
    /// In rich mode: Red X with styled text.
    /// In plain mode: `[ERROR] message`
    pub fn error(&self, message: &str) {
        self.status(StatusKind::Error, message);
    }

    /// Print a warning message.
    ///
    /// In rich mode: Yellow warning symbol with styled text.
    /// In plain mode: `[WARN] message`
    pub fn warning(&self, message: &str) {
        self.status(StatusKind::Warning, message);
    }

    /// Print an info message.
    ///
    /// In rich mode: Blue info symbol with styled text.
    /// In plain mode: `[INFO] message`
    pub fn info(&self, message: &str) {
        self.status(StatusKind::Info, message);
    }

    /// Print a debug message (only in non-minimal modes).
    ///
    /// In rich mode: Gray text.
    /// In plain mode: `[DEBUG] message`
    /// In minimal mode: Nothing printed.
    pub fn debug(&self, message: &str) {
        self.status(StatusKind::Debug, message);
    }

    /// Print a status message with the given kind.
    pub fn status(&self, kind: StatusKind, message: &str) {
        if self.mode == OutputMode::Minimal && kind == StatusKind::Debug {
            return;
        }

        let (level, plain, raw, use_stderr) = self.format_status(kind, message);
        Self::write_line(level, &plain, &raw, use_stderr);
    }

    fn format_status(
        &self,
        kind: StatusKind,
        message: &str,
    ) -> (OutputLevel, String, String, bool) {
        let plain = format!("{} {}", kind.plain_prefix(), message);
        let level = kind.level();
        let use_stderr = kind.use_stderr();

        match self.mode {
            OutputMode::Plain => (level, plain.clone(), plain, use_stderr),
            OutputMode::Minimal => {
                let color = kind.color(&self.theme).to_ansi_fg();
                let raw = format!("{color}{}{} {message}", kind.plain_prefix(), ANSI_RESET);
                (level, plain, raw, use_stderr)
            }
            OutputMode::Rich => {
                let color = kind.color(&self.theme).to_ansi_fg();
                let icon = kind.rich_icon();
                let raw = format!("{color}{icon}{ANSI_RESET} {message}");
                (level, plain, raw, use_stderr)
            }
        }
    }

    /// Print a horizontal rule/divider.
    pub fn rule(&self, title: Option<&str>) {
        let plain = match title {
            Some(value) => format!("--- {value} ---"),
            None => "---".to_string(),
        };

        let raw = if self.mode.uses_ansi() {
            format!("{}{}{}", self.theme.border.to_ansi_fg(), plain, ANSI_RESET)
        } else {
            plain.clone()
        };

        Self::write_line(OutputLevel::Info, &plain, &raw, false);
    }

    /// Print content in a panel/box.
    pub fn panel(&self, content: &str, title: Option<&str>) {
        let plain = match title {
            Some(value) => format!("[{value}]\n{content}"),
            None => content.to_string(),
        };

        let raw = if self.mode.uses_ansi() {
            match title {
                Some(value) => format!(
                    "{}[{}]{}\n{content}",
                    self.theme.header.to_ansi_fg(),
                    value,
                    ANSI_RESET
                ),
                None => content.to_string(),
            }
        } else {
            plain.clone()
        };

        Self::write_line(OutputLevel::Info, &plain, &raw, false);
    }

    /// Print raw text.
    pub fn print(&self, text: &str) {
        Self::write_line(OutputLevel::Info, text, text, false);
    }

    /// Run a closure with test output capture enabled.
    pub fn with_test_output<F: FnOnce()>(test: &TestOutput, f: F) {
        TEST_OUTPUT.with(|cell| {
            *cell.borrow_mut() = Some(test.clone());
        });
        f();
        TEST_OUTPUT.with(|cell| {
            *cell.borrow_mut() = None;
        });
    }

    fn write_line(level: OutputLevel, content: &str, raw: &str, use_stderr: bool) {
        let captured = TEST_OUTPUT.with(|cell| {
            if let Some(test_output) = cell.borrow().as_ref() {
                let entry = OutputEntry {
                    content: content.to_string(),
                    timestamp: Instant::now(),
                    level,
                    component: None,
                    raw_ansi: raw.to_string(),
                };
                test_output.push(entry);
                true
            } else {
                false
            }
        });

        if captured {
            return;
        }

        if use_stderr {
            eprintln!("{raw}");
        } else {
            println!("{raw}");
        }
    }

    /// Get the global `RichOutput` instance.
    ///
    /// # Panics
    ///
    pub fn global() -> parking_lot::RwLockReadGuard<'static, RichOutput> {
        get_global()
    }

    /// Get mutable access to the global `RichOutput` instance.
    pub fn global_mut() -> parking_lot::RwLockWriteGuard<'static, RichOutput> {
        GLOBAL_OUTPUT.write()
    }
}

impl Default for RichOutput {
    fn default() -> Self {
        Self::auto()
    }
}

/// Builder for RichOutput with custom configuration.
pub struct RichOutputBuilder {
    mode: Option<OutputMode>,
    theme: Option<FastApiTheme>,
}

impl RichOutputBuilder {
    /// Create a new builder with defaults.
    #[must_use]
    pub fn new() -> Self {
        Self {
            mode: None,
            theme: None,
        }
    }

    /// Set the output mode.
    #[must_use]
    pub fn mode(mut self, mode: OutputMode) -> Self {
        self.mode = Some(mode);
        self
    }

    /// Set the output theme.
    #[must_use]
    pub fn theme(mut self, theme: FastApiTheme) -> Self {
        self.theme = Some(theme);
        self
    }

    /// Build the configured `RichOutput`.
    #[must_use]
    pub fn build(self) -> RichOutput {
        let mode = self.mode.unwrap_or_else(OutputMode::auto);
        let mut output = RichOutput::with_mode(mode);
        if let Some(theme) = self.theme {
            output.set_theme(theme);
        }
        output
    }
}

impl Default for RichOutputBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Status message kinds.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StatusKind {
    /// Success message.
    Success,
    /// Error message.
    Error,
    /// Warning message.
    Warning,
    /// Informational message.
    Info,
    /// Debug message.
    Debug,
    /// Pending status.
    Pending,
    /// In-progress status.
    InProgress,
}

impl StatusKind {
    /// Get the plain prefix used for this status kind.
    #[must_use]
    pub const fn plain_prefix(&self) -> &'static str {
        match self {
            Self::Success => "[OK]",
            Self::Error => "[ERROR]",
            Self::Warning => "[WARN]",
            Self::Info => "[INFO]",
            Self::Debug => "[DEBUG]",
            Self::Pending => "[PENDING]",
            Self::InProgress => "[...]",
        }
    }

    /// Get the icon used for rich mode output.
    #[must_use]
    pub const fn rich_icon(&self) -> &'static str {
        match self {
            Self::Success => "",
            Self::Error => "",
            Self::Warning => "",
            Self::Info => "",
            Self::Debug => "",
            Self::Pending => "",
            Self::InProgress => "",
        }
    }

    /// Map to the output level for capture.
    #[must_use]
    pub const fn level(&self) -> OutputLevel {
        match self {
            Self::Success => OutputLevel::Success,
            Self::Error => OutputLevel::Error,
            Self::Warning => OutputLevel::Warning,
            Self::Info | Self::Pending | Self::InProgress => OutputLevel::Info,
            Self::Debug => OutputLevel::Debug,
        }
    }

    /// Whether this status should be printed to stderr.
    #[must_use]
    pub const fn use_stderr(&self) -> bool {
        matches!(self, Self::Error | Self::Warning)
    }

    fn color(self, theme: &FastApiTheme) -> crate::themes::Color {
        match self {
            Self::Success => theme.success,
            Self::Error => theme.error,
            Self::Warning => theme.warning,
            Self::Info => theme.info,
            Self::Debug | Self::Pending => theme.muted,
            Self::InProgress => theme.accent,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::testing::{assert_contains, assert_has_ansi, assert_no_ansi};
    use serial_test::serial;

    #[test]
    fn test_rich_output_new() {
        let output = RichOutput::new(OutputMode::Plain);
        assert_eq!(output.mode(), OutputMode::Plain);
    }

    #[test]
    fn test_rich_output_mode_setters() {
        let rich = RichOutput::rich();
        assert_eq!(rich.mode(), OutputMode::Rich);

        let plain = RichOutput::plain();
        assert_eq!(plain.mode(), OutputMode::Plain);
    }

    #[test]
    fn test_rich_output_set_mode() {
        let mut output = RichOutput::rich();
        output.set_mode(OutputMode::Plain);
        assert_eq!(output.mode(), OutputMode::Plain);
    }

    #[test]
    fn test_builder_with_mode() {
        let output = RichOutput::builder().mode(OutputMode::Minimal).build();
        assert_eq!(output.mode(), OutputMode::Minimal);
    }

    #[test]
    fn test_builder_with_theme() {
        let theme = FastApiTheme::neon();
        let output = RichOutput::builder()
            .mode(OutputMode::Plain)
            .theme(theme.clone())
            .build();
        assert_eq!(output.theme(), &theme);
    }

    #[test]
    fn test_status_plain_success() {
        let output = RichOutput::plain();
        let test_output = TestOutput::new(OutputMode::Plain);
        RichOutput::with_test_output(&test_output, || {
            output.success("Operation completed");
        });
        let captured = test_output.captured();
        assert_contains(&captured, "[OK]");
        assert_contains(&captured, "Operation completed");
        assert_no_ansi(&captured);
    }

    #[test]
    fn test_status_rich_has_ansi() {
        let output = RichOutput::rich();
        let test_output = TestOutput::new(OutputMode::Rich);
        RichOutput::with_test_output(&test_output, || {
            output.info("Server starting");
        });
        let raw = test_output.captured_raw();
        assert_contains(&raw, "Server starting");
        assert_has_ansi(&raw);
    }

    #[test]
    fn test_rule_and_panel_capture() {
        let output = RichOutput::plain();
        let test_output = TestOutput::new(OutputMode::Plain);
        RichOutput::with_test_output(&test_output, || {
            output.rule(Some("Configuration"));
            output.panel("Content", Some("Title"));
        });
        let captured = test_output.captured();
        assert_contains(&captured, "Configuration");
        assert_contains(&captured, "[Title]");
    }

    #[test]
    fn test_print_capture() {
        let output = RichOutput::plain();
        let test_output = TestOutput::new(OutputMode::Plain);
        RichOutput::with_test_output(&test_output, || {
            output.print("Raw text");
        });
        let captured = test_output.captured();
        assert_contains(&captured, "Raw text");
    }

    #[test]
    #[serial]
    fn test_get_set_global() {
        let original = RichOutput::global().clone();
        set_global(RichOutput::plain());
        assert_eq!(get_global().mode(), OutputMode::Plain);
        set_global(original);
    }

    // ========== IS_AGENT_MODE TESTS ==========

    #[test]
    fn test_is_agent_mode_plain() {
        let output = RichOutput::plain();
        assert!(output.is_agent_mode());
    }

    #[test]
    fn test_is_agent_mode_rich() {
        let output = RichOutput::rich();
        assert!(!output.is_agent_mode());
    }

    #[test]
    fn test_is_agent_mode_minimal() {
        let output = RichOutput::new(OutputMode::Minimal);
        assert!(!output.is_agent_mode());
    }

    // ========== MODE_NAME TESTS ==========

    #[test]
    fn test_mode_name_plain() {
        let output = RichOutput::plain();
        assert_eq!(output.mode_name(), "plain");
    }

    #[test]
    fn test_mode_name_rich() {
        let output = RichOutput::rich();
        assert_eq!(output.mode_name(), "rich");
    }

    #[test]
    fn test_mode_name_minimal() {
        let output = RichOutput::new(OutputMode::Minimal);
        assert_eq!(output.mode_name(), "minimal");
    }
}