ctl-core 0.6.9

Shared clap chassis for the *ctl CLIs
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
//! Pretty, colorless, and JSON emission from one typed model.

use std::io::{self, IsTerminal, Write};
use std::process::ExitCode;

use anstream::AutoStream;
use serde::Serialize;

use crate::color::ColorMode;
use crate::document::{Document, Text};
use crate::format::OutputFormat;
use crate::model::{Envelope, ErrorBody};
use crate::render::{
    DEFAULT_COLUMN_BUFFER_ENVS, DEFAULT_FALLBACK_WIDTH, DEFAULT_MINIMUM_AUTOMATIC_WIDTH, EnvChoice,
    RenderOptions, env_choice, process_env,
};

/// Default environment variable for the operator's JSON layout.
pub const DEFAULT_JSON_LAYOUT_ENV: &str = "CTL_CORE_JSON_LAYOUT";
/// Default ordered environment lookup for the JSON layout.
pub const DEFAULT_JSON_LAYOUT_ENVS: &[&str] = &[DEFAULT_JSON_LAYOUT_ENV];

/// A serializable domain model with one semantic human presentation.
pub trait Present: Serialize {
    /// Build the human document. JSON serializes `self` directly.
    fn present(&self) -> Document;

    /// Whether this value represents success or failure.
    fn message_kind(&self) -> MessageKind {
        MessageKind::Success
    }

    /// Process exit code. Typed protocols can distinguish usage errors from
    /// operational failures without changing their presentation stream.
    fn exit_code(&self) -> u8 {
        self.message_kind().default_exit_code()
    }
}

/// Human stream and exit semantics for a presented model.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum MessageKind {
    /// Successful command result.
    #[default]
    Success,
    /// Failed command result.
    Error,
}

impl MessageKind {
    /// Default process exit code.
    #[must_use]
    pub const fn default_exit_code(self) -> u8 {
        match self {
            Self::Success => 0,
            Self::Error => 1,
        }
    }
}

/// Destination selected by a view.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Stream {
    /// No output, used for quiet successful pretty output.
    None,
    /// Standard output.
    Stdout,
    /// Standard error.
    Stderr,
}

/// Rendered bytes plus their destination and exit semantics.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Captured {
    stream: Stream,
    content: String,
    exit_code: u8,
}

impl Captured {
    /// Destination stream.
    #[must_use]
    pub const fn stream(&self) -> Stream {
        self.stream
    }

    /// Rendered bytes.
    #[must_use]
    pub fn bytes(&self) -> &[u8] {
        self.content.as_bytes()
    }

    /// UTF-8 rendered content.
    #[must_use]
    pub fn text(&self) -> &str {
        &self.content
    }

    /// Process exit code.
    #[must_use = "return it from main, or the command exits 0"]
    pub fn exit_code(&self) -> ExitCode {
        ExitCode::from(self.exit_code)
    }
}

/// Line layout of JSON output. No layout adds ANSI.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum JsonLayout {
    /// One line per document.
    Compact,
    /// Two-space indentation.
    #[default]
    Pretty,
    /// Two-space indentation when stdout is a terminal, one line otherwise.
    PrettyOnTerminal,
}

impl EnvChoice for JsonLayout {
    const VALUES: &'static [(&'static str, Self)] = &[
        ("pretty", Self::Pretty),
        ("compact", Self::Compact),
        ("pretty-on-terminal", Self::PrettyOnTerminal),
    ];
}

impl JsonLayout {
    fn pretty(self) -> bool {
        match self {
            Self::Compact => false,
            Self::Pretty => true,
            Self::PrettyOnTerminal => io::stdout().is_terminal(),
        }
    }
}

/// How to present a model. JSON never contains ANSI.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct View {
    /// Pretty or JSON.
    pub format: OutputFormat,
    /// ANSI policy for pretty output.
    pub color: ColorMode,
    /// Suppress successful pretty output.
    pub quiet: bool,
    width: Option<u16>,
    automatic_width_buffer: Option<u16>,
    automatic_width_buffer_envs: &'static [&'static str],
    minimum_automatic_width: u16,
    fallback_width: Option<u16>,
    json_layout: Option<JsonLayout>,
    json_layout_envs: &'static [&'static str],
    styles: RenderOptions,
}

impl View {
    /// Build a view that prints successes.
    #[must_use]
    pub const fn new(format: OutputFormat, color: ColorMode) -> Self {
        Self {
            format,
            color,
            quiet: false,
            width: None,
            automatic_width_buffer: None,
            automatic_width_buffer_envs: DEFAULT_COLUMN_BUFFER_ENVS,
            minimum_automatic_width: DEFAULT_MINIMUM_AUTOMATIC_WIDTH,
            fallback_width: Some(DEFAULT_FALLBACK_WIDTH),
            json_layout: None,
            json_layout_envs: DEFAULT_JSON_LAYOUT_ENVS,
            styles: RenderOptions::new(color),
        }
    }

    /// Lay out JSON output as `layout`. This beats the environment.
    #[must_use]
    pub const fn json_layout(mut self, layout: JsonLayout) -> Self {
        self.json_layout = Some(layout);
        self
    }

    /// Replace the ordered environment names read for the JSON layout.
    /// An empty slice disables lookup.
    #[must_use]
    pub const fn json_layout_envs(mut self, names: &'static [&'static str]) -> Self {
        self.json_layout_envs = names;
        self
    }

    /// JSON layout: the owner's choice, then the environment, then the
    /// default.
    #[must_use]
    pub fn layout(self) -> JsonLayout {
        self.layout_with(process_env)
    }

    pub(crate) fn layout_with(self, value: impl Fn(&str) -> Option<String>) -> JsonLayout {
        self.json_layout
            .or_else(|| env_choice(self.json_layout_envs, value))
            .unwrap_or_default()
    }

    /// One line per style or JSON layout variable whose value is not
    /// accepted. `App` prints them before it runs.
    #[cfg(feature = "app")]
    pub(crate) fn env_warnings(self, value: impl Fn(&str) -> Option<String>) -> Vec<String> {
        let mut warnings = self.styles.style_env_warnings(&value);
        if self.json_layout.is_none() {
            warnings.extend(crate::render::env_choice_warnings::<JsonLayout>(
                self.json_layout_envs,
                &value,
            ));
        }
        warnings
    }

    /// Take record style, list style, and row separation from `styles`.
    /// Its color and width settings are ignored; the view owns those.
    #[must_use]
    pub const fn styles(mut self, styles: RenderOptions) -> Self {
        self.styles = styles;
        self
    }

    /// Suppress successful pretty output when `quiet` is set.
    #[must_use]
    pub const fn quiet(mut self, quiet: bool) -> Self {
        self.quiet = quiet;
        self
    }

    /// Force an explicit presentation width.
    #[must_use]
    pub const fn width(mut self, width: u16) -> Self {
        self.width = Some(width);
        self
    }

    /// Override the buffer subtracted from automatically detected widths.
    /// Zero disables buffering. Explicit [`Self::width`] remains exact.
    #[must_use]
    pub const fn automatic_width_buffer(mut self, columns: u16) -> Self {
        self.automatic_width_buffer = Some(columns);
        self
    }

    /// Replace the ordered environment names used for the automatic buffer.
    #[must_use]
    pub const fn automatic_width_buffer_envs(mut self, names: &'static [&'static str]) -> Self {
        self.automatic_width_buffer_envs = names;
        self
    }

    /// Set the floor for automatically detected effective widths.
    #[must_use]
    pub const fn minimum_automatic_width(mut self, columns: u16) -> Self {
        self.minimum_automatic_width = columns;
        self
    }

    /// Lay out to `width` when no width is detected; `None` disables it.
    #[must_use]
    pub const fn fallback_width(mut self, width: Option<u16>) -> Self {
        self.fallback_width = width;
        self
    }

    /// Explicit automatic-width buffer, when set.
    #[must_use]
    pub const fn explicit_automatic_width_buffer(self) -> Option<u16> {
        self.automatic_width_buffer
    }

    /// Ordered environment names used for the automatic-width buffer.
    #[must_use]
    pub const fn automatic_width_buffer_env_names(self) -> &'static [&'static str] {
        self.automatic_width_buffer_envs
    }

    /// Floor applied only to automatically detected widths.
    #[must_use]
    pub const fn automatic_width_minimum(self) -> u16 {
        self.minimum_automatic_width
    }

    pub(crate) fn render_options(self) -> RenderOptions {
        let mut options = RenderOptions::new(self.color)
            .automatic_width_buffer_envs(self.automatic_width_buffer_envs)
            .minimum_automatic_width(self.minimum_automatic_width)
            .fallback_width(self.fallback_width)
            .record_style(self.styles.record())
            .list_style(self.styles.list())
            .row_separation(self.styles.separation());
        if let Some(width) = self.width {
            options = options.width(width);
        }
        if let Some(buffer) = self.automatic_width_buffer {
            options = options.automatic_width_buffer(buffer);
        }
        options
    }

    /// One JSON document in this view's layout, newline-terminated. Successes
    /// and error envelopes share it, so both follow the same layout.
    fn json(self, value: &impl Serialize) -> io::Result<String> {
        let mut content = if self.layout().pretty() {
            serde_json::to_string_pretty(value)?
        } else {
            serde_json::to_string(value)?
        };
        content.push('\n');
        Ok(content)
    }

    /// Render without writing. Tests and alternate transports use this path.
    pub fn capture(self, value: &impl Present) -> io::Result<Captured> {
        let kind = value.message_kind();
        let exit_code = value.exit_code();
        if self.format.is_json() {
            return Ok(Captured {
                stream: Stream::Stdout,
                content: self.json(value)?,
                exit_code,
            });
        }
        if self.quiet && kind == MessageKind::Success {
            return Ok(Captured {
                stream: Stream::None,
                content: String::new(),
                exit_code,
            });
        }
        let content = value.present().render(self.render_options());
        Ok(Captured {
            stream: match kind {
                MessageKind::Success => Stream::Stdout,
                MessageKind::Error => Stream::Stderr,
            },
            content,
            exit_code,
        })
    }

    /// Render and write one typed model. Returns its process exit semantics.
    pub fn show(self, value: &impl Present) -> io::Result<ExitCode> {
        let captured = self.capture(value)?;
        match captured.stream() {
            Stream::None => {}
            Stream::Stdout => write_stdout(captured.bytes(), self.color)?,
            Stream::Stderr => write_stderr(captured.bytes(), self.color)?,
        }
        Ok(captured.exit_code())
    }

    /// Emit `{bin}: {message}` or a JSON error envelope.
    pub fn emit_err(self, bin: &str, message: &str) -> io::Result<ExitCode> {
        if self.format.is_json() {
            let envelope = Envelope::<()>::err(ErrorBody::new(bin, message));
            write_stdout(self.json(&envelope)?.as_bytes(), ColorMode::Never)?;
            return Ok(ExitCode::FAILURE);
        }
        let document =
            Document::new().paragraph(Text::new().error(bin).then(": ").then(message.to_owned()));
        write_stderr(
            document.render(self.render_options()).as_bytes(),
            self.color,
        )?;
        Ok(ExitCode::FAILURE)
    }
}

/// Write raw bytes to stdout with `color`.
pub(crate) fn write_stdout(bytes: &[u8], color: ColorMode) -> io::Result<()> {
    let mut stream = AutoStream::new(io::stdout().lock(), color.choice());
    stream.write_all(bytes)?;
    stream.flush()
}

/// Write raw bytes to stderr with `color`.
pub(crate) fn write_stderr(bytes: &[u8], color: ColorMode) -> io::Result<()> {
    let mut stream = AutoStream::new(io::stderr().lock(), color.choice());
    stream.write_all(bytes)?;
    stream.flush()
}

#[cfg(test)]
mod tests {
    use super::View;
    use crate::color::ColorMode;
    use crate::format::OutputFormat;
    use crate::model::{Envelope, ErrorBody};
    use crate::view::JsonLayout;

    #[test]
    fn error_envelopes_follow_the_json_layout() {
        let envelope = Envelope::<()>::err(ErrorBody::new("toy", "failed"));
        let view = View::new(OutputFormat::Json, ColorMode::Never);
        assert!(view.json(&envelope).unwrap().contains("\n  "));
        let compact = view
            .json_layout(JsonLayout::Compact)
            .json(&envelope)
            .unwrap();
        assert_eq!(compact.lines().count(), 1, "{compact}");
    }

    #[test]
    fn the_environment_picks_the_json_layout_the_owner_left_open() {
        let compact = |name: &str| (name == "CTL_CORE_JSON_LAYOUT").then(|| "compact".to_owned());
        let view = View::new(OutputFormat::Json, ColorMode::Never);
        assert_eq!(view.layout_with(compact), JsonLayout::Compact);
        assert_eq!(
            view.json_layout(JsonLayout::Pretty).layout_with(compact),
            JsonLayout::Pretty
        );
        assert_eq!(
            view.json_layout_envs(&[]).layout_with(compact),
            JsonLayout::Pretty
        );
    }

    #[cfg(feature = "app")]
    #[test]
    fn view_warnings_cover_styles_and_the_json_layout() {
        let typos = |name: &str| match name {
            "CTL_CORE_LIST_STYLE" => Some("boxes".to_owned()),
            "CTL_CORE_JSON_LAYOUT" => Some("tight".to_owned()),
            _ => None,
        };
        let view = View::new(OutputFormat::Pretty, ColorMode::Never);
        assert_eq!(
            view.env_warnings(typos),
            [
                "CTL_CORE_LIST_STYLE=boxes is ignored; use one of grid, header-rule, plain",
                "CTL_CORE_JSON_LAYOUT=tight is ignored; use one of pretty, compact, pretty-on-terminal",
            ]
        );
    }
}