sqlmodel-console 0.2.2

Beautiful terminal output for SQLModel Rust - automatically adapts to agents vs humans
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
//! Output mode detection for agent-safe console output.
//!
//! This module provides automatic detection of whether output should be
//! plain text (for AI agents and CI) or richly formatted (for humans).
//!
//! # Detection Priority
//!
//! The detection follows this priority order (first match wins):
//!
//! 1. `SQLMODEL_PLAIN=1` - Force plain output
//! 2. `SQLMODEL_JSON=1` - Force JSON output
//! 3. `SQLMODEL_RICH=1` - Force rich output (overrides agent detection!)
//! 4. `NO_COLOR` - Standard env var for disabling colors
//! 5. `CI=true` - CI environment detection
//! 6. `TERM=dumb` - Dumb terminal
//! 7. Agent env vars - Claude Code, Codex CLI, Cursor, etc.
//! 8. `!is_terminal(stdout)` - Piped or redirected output
//! 9. Default: Rich output
//!
//! # Agent Detection
//!
//! The following AI coding agents are detected:
//!
//! - Claude Code (`CLAUDE_CODE`)
//! - OpenAI Codex CLI (`CODEX_CLI`)
//! - Cursor IDE (`CURSOR_SESSION`)
//! - Aider (`AIDER_MODEL`, `AIDER_REPO`)
//! - GitHub Copilot (`GITHUB_COPILOT`)
//! - Continue.dev (`CONTINUE_SESSION`)
//! - Generic agent marker (`AGENT_MODE`)

use std::env;
use std::io::IsTerminal;

/// Output mode for console rendering.
///
/// Determines how console output should be formatted. The mode is automatically
/// detected based on environment variables and terminal state, but can be
/// overridden via `SQLMODEL_PLAIN`, `SQLMODEL_RICH`, or `SQLMODEL_JSON`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
pub enum OutputMode {
    /// Plain text output, no ANSI codes. Machine-parseable.
    ///
    /// Used for: AI agents, CI systems, piped output, dumb terminals.
    Plain,

    /// Rich formatted output with colors, tables, panels.
    ///
    /// Used for: Interactive human terminal sessions.
    #[default]
    Rich,

    /// Structured JSON output for programmatic consumption.
    ///
    /// Used for: Tool integrations, scripting, IDEs.
    Json,
}

impl OutputMode {
    /// Detect the appropriate output mode from the environment.
    ///
    /// This function checks various environment variables and terminal state
    /// to determine the best output mode. The detection is deterministic and
    /// follows a well-defined priority order.
    ///
    /// # Priority Order
    ///
    /// 1. `SQLMODEL_PLAIN=1` - Force plain output
    /// 2. `SQLMODEL_JSON=1` - Force JSON output
    /// 3. `SQLMODEL_RICH=1` - Force rich output (overrides agent detection!)
    /// 4. `NO_COLOR` present - Plain (standard convention)
    /// 5. `CI=true` - Plain (CI environment)
    /// 6. `TERM=dumb` - Plain (dumb terminal)
    /// 7. Agent environment detected - Plain
    /// 8. stdout is not a TTY - Plain
    /// 9. Default - Rich
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sqlmodel_console::OutputMode;
    ///
    /// let mode = OutputMode::detect();
    /// match mode {
    ///     OutputMode::Plain => println!("Using plain text"),
    ///     OutputMode::Rich => println!("Using rich formatting"),
    ///     OutputMode::Json => println!("Using JSON output"),
    /// }
    /// ```
    #[must_use]
    pub fn detect() -> Self {
        // Explicit overrides (highest priority)
        if env_is_truthy("SQLMODEL_PLAIN") {
            return Self::Plain;
        }
        if env_is_truthy("SQLMODEL_JSON") {
            return Self::Json;
        }
        if env_is_truthy("SQLMODEL_RICH") {
            return Self::Rich; // Force rich even for agents
        }

        // Standard "no color" convention (https://no-color.org/)
        if env::var("NO_COLOR").is_ok() {
            return Self::Plain;
        }

        // CI environments
        if env_is_truthy("CI") {
            return Self::Plain;
        }

        // Dumb terminal
        if env::var("TERM").is_ok_and(|t| t == "dumb") {
            return Self::Plain;
        }

        // Agent detection
        if Self::is_agent_environment() {
            return Self::Plain;
        }

        // Not a TTY (piped, redirected)
        if !std::io::stdout().is_terminal() {
            return Self::Plain;
        }

        // Default: rich output for humans
        Self::Rich
    }

    /// Check if we're running in an AI coding agent environment.
    ///
    /// This function checks for environment variables set by known AI coding
    /// assistants. When detected, we default to plain output to ensure
    /// machine-parseability.
    ///
    /// # Known Agent Environment Variables
    ///
    /// - `CLAUDE_CODE` - Claude Code CLI
    /// - `CODEX_CLI` - OpenAI Codex CLI
    /// - `CURSOR_SESSION` - Cursor IDE
    /// - `AIDER_MODEL` / `AIDER_REPO` - Aider coding assistant
    /// - `AGENT_MODE` - Generic agent marker
    /// - `GITHUB_COPILOT` - GitHub Copilot
    /// - `CONTINUE_SESSION` - Continue.dev extension
    /// - `CODY_*` - Sourcegraph Cody
    /// - `WINDSURF_*` - Windsurf/Codeium
    /// - `GEMINI_CLI` - Google Gemini CLI
    ///
    /// # Returns
    ///
    /// `true` if any agent environment variable is detected.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sqlmodel_console::OutputMode;
    ///
    /// if OutputMode::is_agent_environment() {
    ///     println!("Running under an AI agent");
    /// }
    /// ```
    #[must_use]
    pub fn is_agent_environment() -> bool {
        const AGENT_MARKERS: &[&str] = &[
            // Claude/Anthropic
            "CLAUDE_CODE",
            // OpenAI
            "CODEX_CLI",
            "CODEX_SESSION",
            // Cursor
            "CURSOR_SESSION",
            "CURSOR_EDITOR",
            // Aider
            "AIDER_MODEL",
            "AIDER_REPO",
            // Generic
            "AGENT_MODE",
            "AI_AGENT",
            // GitHub Copilot
            "GITHUB_COPILOT",
            "COPILOT_SESSION",
            // Continue.dev
            "CONTINUE_SESSION",
            // Sourcegraph Cody
            "CODY_AGENT",
            "CODY_SESSION",
            // Windsurf/Codeium
            "WINDSURF_SESSION",
            "CODEIUM_AGENT",
            // Google Gemini
            "GEMINI_CLI",
            "GEMINI_SESSION",
            // Amazon CodeWhisperer / Q
            "CODEWHISPERER_SESSION",
            "AMAZON_Q_SESSION",
        ];

        AGENT_MARKERS.iter().any(|var| env::var(var).is_ok())
    }

    /// Check if this mode should use ANSI escape codes.
    ///
    /// Returns `true` only for `Rich` mode, which is the only mode that
    /// uses colors and formatting.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sqlmodel_console::OutputMode;
    ///
    /// assert!(!OutputMode::Plain.supports_ansi());
    /// assert!(OutputMode::Rich.supports_ansi());
    /// assert!(!OutputMode::Json.supports_ansi());
    /// ```
    #[must_use]
    pub const fn supports_ansi(&self) -> bool {
        matches!(self, Self::Rich)
    }

    /// Check if this mode uses structured format.
    ///
    /// Returns `true` only for `Json` mode, which outputs structured data
    /// for programmatic consumption.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sqlmodel_console::OutputMode;
    ///
    /// assert!(!OutputMode::Plain.is_structured());
    /// assert!(!OutputMode::Rich.is_structured());
    /// assert!(OutputMode::Json.is_structured());
    /// ```
    #[must_use]
    pub const fn is_structured(&self) -> bool {
        matches!(self, Self::Json)
    }

    /// Check if this mode is plain text.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sqlmodel_console::OutputMode;
    ///
    /// assert!(OutputMode::Plain.is_plain());
    /// assert!(!OutputMode::Rich.is_plain());
    /// assert!(!OutputMode::Json.is_plain());
    /// ```
    #[must_use]
    pub const fn is_plain(&self) -> bool {
        matches!(self, Self::Plain)
    }

    /// Check if this mode uses rich formatting.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sqlmodel_console::OutputMode;
    ///
    /// assert!(!OutputMode::Plain.is_rich());
    /// assert!(OutputMode::Rich.is_rich());
    /// assert!(!OutputMode::Json.is_rich());
    /// ```
    #[must_use]
    pub const fn is_rich(&self) -> bool {
        matches!(self, Self::Rich)
    }

    /// Get the mode name as a string slice.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sqlmodel_console::OutputMode;
    ///
    /// assert_eq!(OutputMode::Plain.as_str(), "plain");
    /// assert_eq!(OutputMode::Rich.as_str(), "rich");
    /// assert_eq!(OutputMode::Json.as_str(), "json");
    /// ```
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Plain => "plain",
            Self::Rich => "rich",
            Self::Json => "json",
        }
    }
}

impl std::fmt::Display for OutputMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Check if an environment variable is set to a truthy value.
///
/// Recognizes: `1`, `true`, `yes`, `on` (case-insensitive).
fn env_is_truthy(name: &str) -> bool {
    env::var(name).is_ok_and(|v| {
        let v = v.to_lowercase();
        v == "1" || v == "true" || v == "yes" || v == "on"
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::env;

    /// Environment variables to clean before each test.
    const VARS_TO_CLEAR: &[&str] = &[
        "SQLMODEL_PLAIN",
        "SQLMODEL_JSON",
        "SQLMODEL_RICH",
        "NO_COLOR",
        "CI",
        "TERM",
        "CLAUDE_CODE",
        "CODEX_CLI",
        "CURSOR_SESSION",
        "AIDER_MODEL",
        "AGENT_MODE",
        "GITHUB_COPILOT",
        "CONTINUE_SESSION",
    ];

    /// Wrapper for env::set_var (unsafe in Rust 2024 edition).
    ///
    /// # Safety
    /// This is only safe in single-threaded test contexts with #[test].
    /// Tests must be run with `--test-threads=1` for safety.
    #[allow(unsafe_code)]
    fn test_set_var(key: &str, value: &str) {
        // SAFETY: Tests are run single-threaded via `cargo test -- --test-threads=1`
        // or the env manipulation is isolated to a single test function.
        unsafe { env::set_var(key, value) };
    }

    /// Wrapper for env::remove_var (unsafe in Rust 2024 edition).
    #[allow(unsafe_code)]
    fn test_remove_var(key: &str) {
        // SAFETY: Same as test_set_var
        unsafe { env::remove_var(key) };
    }

    /// Helper to run test with clean environment.
    fn with_clean_env<F: FnOnce()>(f: F) {
        // Save current values
        let saved: Vec<_> = VARS_TO_CLEAR
            .iter()
            .map(|&v| (v, env::var(v).ok()))
            .collect();

        // Clear all relevant vars
        for &var in VARS_TO_CLEAR {
            test_remove_var(var);
        }

        // Run the test
        f();

        // Restore original values
        for (var, val) in saved {
            match val {
                Some(v) => test_set_var(var, &v),
                None => test_remove_var(var),
            }
        }
    }

    #[test]
    fn test_default_is_rich() {
        assert_eq!(OutputMode::default(), OutputMode::Rich);
    }

    #[test]
    fn test_explicit_plain_override() {
        with_clean_env(|| {
            test_set_var("SQLMODEL_PLAIN", "1");
            assert_eq!(OutputMode::detect(), OutputMode::Plain);
        });
    }

    #[test]
    fn test_explicit_plain_override_true() {
        with_clean_env(|| {
            test_set_var("SQLMODEL_PLAIN", "true");
            assert_eq!(OutputMode::detect(), OutputMode::Plain);
        });
    }

    #[test]
    #[ignore = "flaky: env var race conditions in parallel tests"]
    fn test_explicit_json_override() {
        with_clean_env(|| {
            test_set_var("SQLMODEL_JSON", "1");
            assert_eq!(OutputMode::detect(), OutputMode::Json);
        });
    }

    #[test]
    #[ignore = "flaky: env var race conditions in parallel tests (CI sets CI=true)"]
    fn test_explicit_rich_override() {
        with_clean_env(|| {
            test_set_var("SQLMODEL_RICH", "1");
            // Note: This test runs in a non-TTY context (cargo test),
            // but SQLMODEL_RICH should still force rich mode
            assert_eq!(OutputMode::detect(), OutputMode::Rich);
        });
    }

    #[test]
    #[ignore = "flaky: env var race conditions in parallel tests"]
    fn test_plain_takes_priority_over_json() {
        with_clean_env(|| {
            test_set_var("SQLMODEL_PLAIN", "1");
            test_set_var("SQLMODEL_JSON", "1");
            assert_eq!(OutputMode::detect(), OutputMode::Plain);
        });
    }

    #[test]
    #[ignore = "flaky: env var race conditions in parallel tests"]
    fn test_agent_detection_claude() {
        with_clean_env(|| {
            test_set_var("CLAUDE_CODE", "1");
            assert!(OutputMode::is_agent_environment());
        });
    }

    #[test]
    #[ignore = "flaky: env var race conditions in parallel tests"]
    fn test_agent_detection_codex() {
        with_clean_env(|| {
            test_set_var("CODEX_CLI", "1");
            assert!(OutputMode::is_agent_environment());
        });
    }

    #[test]
    #[ignore = "flaky: env var race conditions in parallel tests"]
    fn test_agent_detection_cursor() {
        with_clean_env(|| {
            test_set_var("CURSOR_SESSION", "active");
            assert!(OutputMode::is_agent_environment());
        });
    }

    #[test]
    #[ignore = "flaky: env var race conditions in parallel tests"]
    fn test_agent_detection_aider() {
        with_clean_env(|| {
            test_set_var("AIDER_MODEL", "gpt-4");
            assert!(OutputMode::is_agent_environment());
        });
    }

    #[test]
    #[ignore = "flaky: env var race conditions in parallel tests"]
    fn test_agent_causes_plain_mode() {
        with_clean_env(|| {
            test_set_var("CLAUDE_CODE", "1");
            assert_eq!(OutputMode::detect(), OutputMode::Plain);
        });
    }

    #[test]
    #[ignore = "flaky: env var race conditions in parallel tests (CI sets CI=true)"]
    fn test_rich_override_beats_agent() {
        with_clean_env(|| {
            test_set_var("CLAUDE_CODE", "1");
            test_set_var("SQLMODEL_RICH", "1");
            assert_eq!(OutputMode::detect(), OutputMode::Rich);
        });
    }

    #[test]
    #[ignore = "flaky: env var race conditions in parallel tests"]
    fn test_no_color_causes_plain() {
        with_clean_env(|| {
            test_set_var("NO_COLOR", "");
            assert_eq!(OutputMode::detect(), OutputMode::Plain);
        });
    }

    #[test]
    #[ignore = "flaky: env var race conditions in parallel tests"]
    fn test_ci_causes_plain() {
        with_clean_env(|| {
            test_set_var("CI", "true");
            assert_eq!(OutputMode::detect(), OutputMode::Plain);
        });
    }

    #[test]
    #[ignore = "flaky: env var race conditions in parallel tests"]
    fn test_dumb_terminal_causes_plain() {
        with_clean_env(|| {
            test_set_var("TERM", "dumb");
            assert_eq!(OutputMode::detect(), OutputMode::Plain);
        });
    }

    #[test]
    fn test_supports_ansi() {
        assert!(!OutputMode::Plain.supports_ansi());
        assert!(OutputMode::Rich.supports_ansi());
        assert!(!OutputMode::Json.supports_ansi());
    }

    #[test]
    fn test_is_structured() {
        assert!(!OutputMode::Plain.is_structured());
        assert!(!OutputMode::Rich.is_structured());
        assert!(OutputMode::Json.is_structured());
    }

    #[test]
    fn test_is_plain() {
        assert!(OutputMode::Plain.is_plain());
        assert!(!OutputMode::Rich.is_plain());
        assert!(!OutputMode::Json.is_plain());
    }

    #[test]
    fn test_is_rich() {
        assert!(!OutputMode::Plain.is_rich());
        assert!(OutputMode::Rich.is_rich());
        assert!(!OutputMode::Json.is_rich());
    }

    #[test]
    fn test_as_str() {
        assert_eq!(OutputMode::Plain.as_str(), "plain");
        assert_eq!(OutputMode::Rich.as_str(), "rich");
        assert_eq!(OutputMode::Json.as_str(), "json");
    }

    #[test]
    fn test_display() {
        assert_eq!(format!("{}", OutputMode::Plain), "plain");
        assert_eq!(format!("{}", OutputMode::Rich), "rich");
        assert_eq!(format!("{}", OutputMode::Json), "json");
    }

    #[test]
    fn test_env_is_truthy() {
        with_clean_env(|| {
            // Not set
            assert!(!env_is_truthy("SQLMODEL_TEST_VAR"));

            // Various truthy values
            test_set_var("SQLMODEL_TEST_VAR", "1");
            assert!(env_is_truthy("SQLMODEL_TEST_VAR"));

            test_set_var("SQLMODEL_TEST_VAR", "true");
            assert!(env_is_truthy("SQLMODEL_TEST_VAR"));

            test_set_var("SQLMODEL_TEST_VAR", "TRUE");
            assert!(env_is_truthy("SQLMODEL_TEST_VAR"));

            test_set_var("SQLMODEL_TEST_VAR", "yes");
            assert!(env_is_truthy("SQLMODEL_TEST_VAR"));

            test_set_var("SQLMODEL_TEST_VAR", "on");
            assert!(env_is_truthy("SQLMODEL_TEST_VAR"));

            // Falsy values
            test_set_var("SQLMODEL_TEST_VAR", "0");
            assert!(!env_is_truthy("SQLMODEL_TEST_VAR"));

            test_set_var("SQLMODEL_TEST_VAR", "false");
            assert!(!env_is_truthy("SQLMODEL_TEST_VAR"));

            test_set_var("SQLMODEL_TEST_VAR", "");
            assert!(!env_is_truthy("SQLMODEL_TEST_VAR"));

            test_remove_var("SQLMODEL_TEST_VAR");
        });
    }

    #[test]
    #[ignore = "flaky: env var race conditions in parallel tests"]
    fn test_no_agent_when_clean() {
        with_clean_env(|| {
            assert!(!OutputMode::is_agent_environment());
        });
    }
}