troll 0.3.1

The port manager that guards the bridge: permanent claims, expiring leases, and a live view of who listens where.
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
//! Human terminal styling shared by every command, keeping raw text for pipes,
//! scripts, CI, and AI agents.
//!
//! A command renders the aligned, ANSI-colored human layout only when the output
//! stream is a human terminal (or explicitly forced with `--color always` /
//! `TROLL_OUTPUT=human`). Pipes, captures, CI shells, recognized agent shells,
//! and `--json` always receive clean plain text without ANSI escape sequences.
//!
//! Untrusted text (stored names, process names, file paths) passes through
//! [`display`], which keeps printable Unicode while escaping control, C1, and
//! bidirectional-override characters so external data cannot inject terminal
//! escapes or spoof layout.

use std::{
    env,
    ffi::OsStr,
    io::{self, IsTerminal},
};

use crate::cli::Color;

/// Section headers and identity title: bold gold.
pub(crate) const HEADER: &str = "\x1b[1;38;5;220m";
/// Commands, ports, and primary identifiers: bold cyan.
pub(crate) const COMMAND: &str = "\x1b[1;38;5;81m";
/// Secondary descriptions, labels, and metadata: dim.
pub(crate) const DIM: &str = "\x1b[2m";
pub(crate) const RESET: &str = "\x1b[0m";

const GOOD: &str = "\x1b[32m";
const PENDING: &str = "\x1b[33m";
const BAD: &str = "\x1b[31m";
const MUTED: &str = "\x1b[2m";

const GOOD_GLYPH: &str = "✓";
const PENDING_GLYPH: &str = "•";
const BAD_GLYPH: &str = "✗";

const GAP: &str = "  ";
const DEFAULT_COLUMNS: u16 = 80;
const COLUMNS_VARIABLE: &str = "COLUMNS";

/// Environment variable overriding layout detection: `plain`, `human`, or `auto`.
pub(crate) const OUTPUT_MODE_VARIABLE: &str = "TROLL_OUTPUT";

/// Environment variables set by coding agents or CI runners. A terminal with
/// one of these set to a truthy value is treated as machine-consumed unless
/// `TROLL_OUTPUT=human` or `--color always` overrides it.
pub(crate) const AGENT_MARKERS: [&str; 4] = ["CLAUDECODE", "GEMINI_CLI", "CURSOR_AGENT", "CI"];

/// Global flags that disable ANSI color in addition to `--color never`.
pub(crate) const NO_COLOR_FLAGS: [&str; 3] = ["--no-color", "--no-colors", "--no-ansi-colors"];

/// Whether `token` is one of [`NO_COLOR_FLAGS`].
pub(crate) fn is_no_color_flag(token: &str) -> bool {
    NO_COLOR_FLAGS.contains(&token)
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum Stream {
    Stdout,
    #[allow(dead_code)]
    Stderr,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(crate) enum OutputMode {
    #[default]
    Auto,
    Plain,
    Human,
}

impl OutputMode {
    pub(crate) fn parse(value: Option<&OsStr>) -> Self {
        match value.and_then(OsStr::to_str).map(str::trim) {
            Some(value) if value.eq_ignore_ascii_case("plain") => Self::Plain,
            Some(value) if value.eq_ignore_ascii_case("human") => Self::Human,
            _ => Self::Auto,
        }
    }
}

pub(crate) fn agent_marker(
    lookup: impl Fn(&str) -> Option<std::ffi::OsString>,
) -> Option<&'static str> {
    AGENT_MARKERS.into_iter().find(|name| {
        lookup(name).is_some_and(|value| {
            let value = value.to_string_lossy();
            let value = value.trim();
            !(value.is_empty() || value == "0" || value.eq_ignore_ascii_case("false"))
        })
    })
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(crate) struct TerminalFacts {
    pub(crate) is_terminal: bool,
    /// True when `NO_COLOR` is set to a non-empty value (per no-color.org).
    pub(crate) no_color_env: bool,
    pub(crate) dumb_term: bool,
    pub(crate) mode: OutputMode,
    pub(crate) agent: bool,
    pub(crate) columns: Option<u16>,
}

impl TerminalFacts {
    pub(crate) fn of(stream: Stream) -> Self {
        let is_terminal = match stream {
            Stream::Stdout => io::stdout().is_terminal(),
            Stream::Stderr => io::stderr().is_terminal(),
        };
        Self {
            is_terminal,
            no_color_env: env::var_os("NO_COLOR").is_some_and(|value| !value.is_empty()),
            dumb_term: env::var_os("TERM").as_deref() == Some(OsStr::new("dumb")),
            mode: OutputMode::parse(env::var_os(OUTPUT_MODE_VARIABLE).as_deref()),
            agent: agent_marker(|name| env::var_os(name)).is_some(),
            columns: is_terminal.then(|| {
                columns_from(env::var_os(COLUMNS_VARIABLE).as_deref()).unwrap_or(DEFAULT_COLUMNS)
            }),
        }
    }
}

pub(crate) fn columns_from(value: Option<&OsStr>) -> Option<u16> {
    value?
        .to_str()?
        .trim()
        .parse::<u16>()
        .ok()
        .filter(|columns| *columns > 0)
}

/// Output style for one command invocation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct Style {
    human: bool,
    color: bool,
    columns: Option<u16>,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum Tone {
    Good,
    Pending,
    Bad,
    Muted,
    Neutral,
}

impl Style {
    #[cfg(test)]
    pub(crate) const PLAIN: Self = Self {
        human: false,
        color: false,
        columns: None,
    };

    #[cfg(test)]
    pub(crate) const COLOR: Self = Self {
        human: true,
        color: true,
        columns: None,
    };

    pub(crate) fn detect(stream: Stream, choice: Color, json: bool) -> Self {
        Self::decide(TerminalFacts::of(stream), choice, json)
    }

    pub(crate) fn decide(facts: TerminalFacts, choice: Color, json: bool) -> Self {
        if json {
            return Self {
                human: false,
                color: false,
                columns: None,
            };
        }
        let wanted_human = match facts.mode {
            OutputMode::Plain => false,
            OutputMode::Human => true,
            OutputMode::Auto => !facts.agent,
        };
        let human = match choice {
            Color::Always => true,
            Color::Never => facts.is_terminal && wanted_human,
            Color::Auto => facts.is_terminal && wanted_human,
        };
        let color = match choice {
            Color::Always => true,
            Color::Never => false,
            Color::Auto => human && !facts.no_color_env && !facts.dumb_term,
        };
        Self {
            human,
            color,
            columns: facts.columns.filter(|_| human),
        }
    }

    pub(crate) fn is_human(self) -> bool {
        self.human
    }

    pub(crate) fn has_color(self) -> bool {
        self.color
    }

    #[allow(dead_code)]
    pub(crate) fn columns(self) -> Option<usize> {
        self.columns.map(usize::from)
    }

    pub(crate) fn paint(self, code: &str, text: &str) -> String {
        if self.color {
            format!("{code}{text}{RESET}")
        } else {
            text.to_owned()
        }
    }

    pub(crate) fn heading(self, text: &str) -> String {
        self.paint(HEADER, text)
    }

    pub(crate) fn accent(self, text: &str) -> String {
        self.paint(COMMAND, text)
    }

    pub(crate) fn dim(self, text: &str) -> String {
        self.paint(DIM, text)
    }

    pub(crate) fn status_cell(self, word: &str) -> Cell {
        if !self.human {
            return Cell::plain(display(word));
        }
        let (glyph, code) = match tone(word) {
            Tone::Good => (GOOD_GLYPH, GOOD),
            Tone::Pending => (PENDING_GLYPH, PENDING),
            Tone::Bad => (BAD_GLYPH, BAD),
            Tone::Muted => (PENDING_GLYPH, MUTED),
            Tone::Neutral => return Cell::plain(display(word)),
        };
        let text = format!("{glyph} {}", display(word));
        Cell::styled(&text, self.paint(code, &text))
    }

    pub(crate) fn status_text(self, word: &str) -> String {
        self.status_cell(word).into()
    }
}

pub(crate) fn tone(word: &str) -> Tone {
    match word {
        "listening" | "ok" | "active" | "free" | "enabled" => Tone::Good,
        "warning" | "overdue" | "expiring" | "claimed" | "in use" | "unknown" => Tone::Pending,
        "failed" | "reclaimable" | "conflict" => Tone::Bad,
        "silent" | "disabled" => Tone::Muted,
        _ => Tone::Neutral,
    }
}

/// Escape control, C1, and bidirectional-override/isolate characters while
/// keeping ordinary printable Unicode text intact.
pub(crate) fn display(raw: &str) -> String {
    let mut out = String::with_capacity(raw.len());
    for character in raw.chars() {
        match character {
            '\n' => out.push_str("\\n"),
            '\t' => out.push_str("\\t"),
            '\r' => out.push_str("\\r"),
            ch if ch.is_control() || is_bidi_control(ch) => {
                out.push_str(&format!("\\u{{{:x}}}", u32::from(ch)));
            }
            other => out.push(other),
        }
    }
    out
}

fn is_bidi_control(ch: char) -> bool {
    matches!(
        ch,
        '\u{061C}'
            | '\u{200E}'..='\u{200F}'
            | '\u{202A}'..='\u{202E}'
            | '\u{2066}'..='\u{2069}'
    )
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct Cell {
    width: usize,
    shown: String,
}

impl Cell {
    pub(crate) fn plain(text: impl Into<String>) -> Self {
        let shown = text.into();
        Self {
            width: shown.chars().count(),
            shown,
        }
    }

    pub(crate) fn styled(text: &str, shown: String) -> Self {
        Self {
            width: text.chars().count(),
            shown,
        }
    }
}

impl From<Cell> for String {
    fn from(cell: Cell) -> Self {
        cell.shown
    }
}

#[derive(Debug)]
pub(crate) struct Table {
    headers: Vec<String>,
    rows: Vec<Vec<Cell>>,
}

impl Table {
    pub(crate) fn new(headers: &[&str]) -> Self {
        Self {
            headers: headers.iter().map(|header| (*header).to_owned()).collect(),
            rows: Vec::new(),
        }
    }

    pub(crate) fn row(&mut self, mut cells: Vec<Cell>) -> &mut Self {
        cells.resize_with(self.headers.len().max(cells.len()), || Cell::plain(""));
        self.rows.push(cells);
        self
    }

    pub(crate) fn render(&self, style: Style, indent: &str) -> String {
        let columns = self.headers.len();
        let mut widths: Vec<usize> = self
            .headers
            .iter()
            .map(|header| header.chars().count())
            .collect();
        for row in &self.rows {
            for (index, cell) in row.iter().enumerate().take(columns) {
                widths[index] = widths[index].max(cell.width);
            }
        }
        let mut out = String::new();
        let header: Vec<Cell> = self
            .headers
            .iter()
            .map(|text| Cell::styled(text, style.dim(text)))
            .collect();
        for row in std::iter::once(&header).chain(&self.rows) {
            out.push_str(indent);
            for (index, cell) in row.iter().enumerate() {
                out.push_str(&cell.shown);
                if index + 1 < row.len() {
                    let width = widths.get(index).copied().unwrap_or(cell.width);
                    out.push_str(&" ".repeat(width.saturating_sub(cell.width)));
                    out.push_str(GAP);
                }
            }
            let trimmed = out.trim_end_matches(' ').len();
            out.truncate(trimmed);
            out.push('\n');
        }
        out
    }
}

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

    #[test]
    fn style_gives_ansi_to_human_terminals_and_raw_text_to_pipes_and_agents() {
        let tty = TerminalFacts {
            is_terminal: true,
            ..TerminalFacts::default()
        };
        assert!(Style::decide(tty, Color::Auto, false).has_color());
        assert!(Style::decide(tty, Color::Auto, false).is_human());

        let piped = TerminalFacts::default();
        assert!(!Style::decide(piped, Color::Auto, false).has_color());
        assert!(!Style::decide(piped, Color::Auto, false).is_human());

        let agent = TerminalFacts {
            is_terminal: true,
            agent: true,
            ..TerminalFacts::default()
        };
        assert!(!Style::decide(agent, Color::Auto, false).has_color());
        assert!(!Style::decide(agent, Color::Auto, false).is_human());

        let forced_human = TerminalFacts {
            mode: OutputMode::Human,
            ..agent
        };
        assert!(Style::decide(forced_human, Color::Auto, false).has_color());

        let forced_plain = TerminalFacts {
            mode: OutputMode::Plain,
            ..tty
        };
        assert!(!Style::decide(forced_plain, Color::Auto, false).is_human());
        assert!(!Style::decide(forced_plain, Color::Auto, false).has_color());

        let dumb = TerminalFacts {
            dumb_term: true,
            ..tty
        };
        assert!(Style::decide(dumb, Color::Auto, false).is_human());
        assert!(!Style::decide(dumb, Color::Auto, false).has_color());

        let no_color = TerminalFacts {
            no_color_env: true,
            ..tty
        };
        assert!(Style::decide(no_color, Color::Auto, false).is_human());
        assert!(!Style::decide(no_color, Color::Auto, false).has_color());

        // --json never emits ANSI escapes even with --color always.
        assert!(!Style::decide(tty, Color::Always, true).has_color());
        // --color always works even when piped (tested by existing help tests).
        assert!(Style::decide(piped, Color::Always, false).has_color());
    }

    #[test]
    fn display_escapes_control_and_bidi_override_characters() {
        assert_eq!(display("safe-name"), "safe-name");
        assert_eq!(
            display("a\x1b[31mb\u{202e}c\nd"),
            "a\\u{1b}[31mb\\u{202e}c\\nd"
        );
    }

    #[test]
    fn table_aligns_visible_widths_ignoring_ansi_codes() {
        let mut table = Table::new(&["PORT", "STATUS"]);
        table.row(vec![
            Cell::styled("8123", Style::COLOR.accent("8123")),
            Style::COLOR.status_cell("listening"),
        ]);
        let rendered = table.render(Style::COLOR, "  ");
        assert!(rendered.contains("\x1b["));
        assert!(rendered.contains("✓ listening"));

        let plain = table.render(Style::PLAIN, "  ");
        assert!(plain.contains("8123"));
    }
}