ctl-core 0.7.0

A framework for clap programs: typed results, help, and terminal or JSON output
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
//! Pretty, colourless, and JSON output from one typed model.
//!
//! A command result implements [`Present`]: it serializes for JSON and builds
//! a [`Document`] for people. A [`View`] holds the output format, the colour
//! mode, and the layout policy, and writes the result with [`View::show`] or
//! returns it unwritten with [`View::capture`].
//!
//! Success goes to stdout and failure to stderr, except JSON, which always
//! goes to stdout. JSON never contains ANSI whatever the colour mode says.
//!
//! ```
//! use ctl_core::color::ColorMode;
//! use ctl_core::document::{Document, Fields};
//! use ctl_core::format::OutputFormat;
//! use ctl_core::view::{Destination, JsonLayout, Present, View};
//! use serde::Serialize;
//!
//! #[derive(Serialize)]
//! struct Status {
//!     pending: usize,
//! }
//!
//! impl Present for Status {
//!     fn present(&self) -> Document {
//!         Document::new().fields(Fields::new().row("pending", self.pending.to_string()))
//!     }
//! }
//!
//! let status = Status { pending: 2 };
//! let json = View::new(OutputFormat::Json, ColorMode::Never)
//!     .json_layout(JsonLayout::Pretty)
//!     .capture(&status)?;
//! assert_eq!(json.stream(), Destination::Stdout);
//! assert!(json.text().contains("\"pending\": 2"));
//!
//! let pretty = View::new(OutputFormat::Pretty, ColorMode::Never)
//!     .width(40)
//!     .capture(&status)?;
//! assert!(pretty.text().contains("pending"));
//! # Ok::<(), std::io::Error>(())
//! ```

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

use serde::Serialize;

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

/// The environment variable that sets the JSON layout when the CLI has not:
/// `CTL_CORE_JSON_LAYOUT`. Its values are the [`JsonLayout`] names
/// `pretty`, `compact`, and `pretty-on-terminal`.
pub const DEFAULT_JSON_LAYOUT_ENV: &str = "CTL_CORE_JSON_LAYOUT";
/// The ordered list of variables [`View::resolved_json_layout`] reads,
/// holding only [`DEFAULT_JSON_LAYOUT_ENV`]. [`View::json_layout_envs`]
/// replaces it.
pub const DEFAULT_JSON_LAYOUT_ENVS: &[&str] = &[DEFAULT_JSON_LAYOUT_ENV];

/// A command result that serializes for machines and presents itself to people.
///
/// JSON output is `self` serialized as is. Pretty and colourless output is the
/// [`Document`] that [`Self::present`] builds. The two share one value, so they
/// cannot drift apart.
pub trait Present: Serialize {
    /// Build the human document. JSON output serializes `self` and ignores
    /// this.
    fn present(&self) -> Document;

    /// Whether the result is a success or a failure. It picks the stream of
    /// pretty output (stdout or stderr) and the default exit code. The default
    /// is [`Outcome::Success`].
    fn outcome(&self) -> Outcome {
        Outcome::Success
    }

    /// The process exit code. The default is `0` for a success and `1` for an
    /// error ([`Outcome::default_exit_code`]).
    ///
    /// Override it to give a failure its own code, such as a usage error
    /// distinct from an operational failure. The stream still follows
    /// [`Self::outcome`].
    fn exit_code(&self) -> u8 {
        self.outcome().default_exit_code()
    }
}

/// Whether a [`Present`] result succeeded. It picks the stream pretty output
/// goes to and the default exit code.
///
/// The set is closed, and the enum is not `#[non_exhaustive]`: a command
/// either succeeded or failed.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum Outcome {
    /// The command succeeded. Pretty output goes to stdout, and the exit code
    /// is `0`.
    #[default]
    Success,
    /// The command failed. Pretty output goes to stderr, and the exit code is
    /// `1`.
    Error,
}

impl Outcome {
    /// The exit code for a result of this variant, unless the result
    /// overrides [`Present::exit_code`]: `0` for a success, `1` for an error.
    #[must_use]
    pub const fn default_exit_code(self) -> u8 {
        match self {
            Self::Success => 0,
            Self::Error => 1,
        }
    }
}

/// Where a view sends rendered output.
///
/// [`ctl_term::Stream`](crate::term::Stream) names the stream that colour
/// and width are decided for. A destination can also be no output at all.
///
/// The set is closed, and the enum is not `#[non_exhaustive]`: a process has
/// one standard output and one standard error, and quiet output goes to
/// neither.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Destination {
    /// No output, used for quiet successful pretty output.
    None,
    /// Standard output.
    Stdout,
    /// Standard error.
    Stderr,
}

/// A rendered result that has not been written: its text, the stream it
/// belongs on, and its exit code.
///
/// [`View::capture`] returns one. [`View::show`] writes it. Tests and
/// alternate transports read it directly.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Captured {
    stream: Destination,
    content: String,
    exit_code: u8,
}

impl Captured {
    /// The stream the text belongs on.
    #[must_use]
    pub const fn stream(&self) -> Destination {
        self.stream
    }

    /// The rendered text as UTF-8 bytes. It is empty when the stream is
    /// [`Destination::None`].
    #[must_use]
    pub fn bytes(&self) -> &[u8] {
        self.content.as_bytes()
    }

    /// The rendered text. It ends with a newline unless it is empty.
    #[must_use]
    pub fn text(&self) -> &str {
        &self.content
    }

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

/// How JSON output is broken into lines. No layout adds ANSI.
///
/// The layout changes only whitespace, so every layout parses to the same
/// value.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum JsonLayout {
    /// The whole document on one line.
    Compact,
    /// One value per line, indented by two spaces.
    #[default]
    Pretty,
    /// [`Self::Pretty`] when stdout is a terminal, and [`Self::Compact`]
    /// 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 [`Present`] result: the format, the colour mode, and the
/// layout policy. JSON never contains ANSI.
///
/// Pretty output decides colour and width for the stream it goes to: a
/// success for stdout, a failure for stderr. So a failure printed to a
/// terminal is coloured while a success piped to a file is not.
/// [`Self::capture`] under [`ColorMode::Auto`] holds no escape sequence when
/// that stream is not a terminal.
///
/// The colour, width, and style settings are one [`RenderOptions`], which
/// [`Self::render_options`] returns. A setter takes the name of its setting
/// and returns the view changed, as on `RenderOptions`. [`Self::format`] and
/// [`Self::is_quiet`] read the format and the quiet setting.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct View {
    format: OutputFormat,
    quiet: bool,
    options: RenderOptions,
    json_layout: Option<JsonLayout>,
    json_layout_envs: &'static [&'static str],
}

impl View {
    /// Build a view in `format` and `color` that prints successes. Width,
    /// buffer, minimum, fallback, styles, and JSON layout take their defaults.
    #[must_use]
    pub const fn new(format: OutputFormat, color: ColorMode) -> Self {
        Self {
            format,
            quiet: false,
            options: RenderOptions::new(color),
            json_layout: None,
            json_layout_envs: DEFAULT_JSON_LAYOUT_ENVS,
        }
    }

    /// 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 CLI's choice, then the environment, then the
    /// default. It reads the process environment.
    #[must_use]
    pub fn resolved_json_layout(self) -> JsonLayout {
        self.json_layout_with(process_env)
    }

    pub(crate) fn json_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.options.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 the theme, record style, table frame, row separation, and the
    /// variables they read from `styles`. Its colour and width settings are
    /// ignored; the view owns those.
    #[must_use]
    pub const fn styles(mut self, styles: RenderOptions) -> Self {
        self.options = self.options.styles(styles);
        self
    }

    /// Draw each role in the style `theme` gives it, in place of
    /// [`Theme::default`]. Colour is still the colour mode's choice:
    /// [`ColorMode::Never`] writes no style. A later [`Self::styles`]
    /// replaces this theme with its own.
    #[must_use]
    pub const fn theme(mut self, theme: Theme) -> Self {
        self.options = self.options.theme(theme);
        self
    }

    /// Write colour as `color` says, in place of the mode given to
    /// [`Self::new`].
    #[must_use]
    pub const fn color(mut self, color: ColorMode) -> Self {
        self.options = self.options.color(color);
        self
    }

    /// Suppress a successful pretty result when `quiet` is true. Errors and
    /// JSON are still written.
    #[must_use]
    pub const fn quiet(mut self, quiet: bool) -> Self {
        self.quiet = quiet;
        self
    }

    /// Pretty or JSON output, as [`Self::new`] set it.
    #[must_use]
    pub const fn format(self) -> OutputFormat {
        self.format
    }

    /// Whether a successful pretty result is suppressed, as [`Self::quiet`]
    /// set it.
    #[must_use]
    pub const fn is_quiet(self) -> bool {
        self.quiet
    }

    /// The view in `format`, every other setting kept. The parse-error path
    /// uses it when `--format` is read before the parser runs.
    #[cfg(feature = "app")]
    pub(crate) const fn in_format(mut self, format: OutputFormat) -> Self {
        self.format = format;
        self
    }

    /// Lay out pretty output to exactly `width` terminal cells, skipping
    /// detection, the buffer, and the minimum.
    #[must_use]
    pub const fn width(mut self, width: u16) -> Self {
        self.options = self.options.width(width);
        self
    }

    /// Override the number of cells subtracted from an automatically
    /// detected width. Zero disables the subtraction. An explicit
    /// [`Self::width`] stays exact.
    #[must_use]
    pub const fn automatic_width_buffer(mut self, cells: u16) -> Self {
        self.options = self.options.automatic_width_buffer(cells);
        self
    }

    /// Replace the ordered environment names that set the buffer. An empty
    /// slice disables lookup.
    #[must_use]
    pub const fn automatic_width_buffer_envs(mut self, names: &'static [&'static str]) -> Self {
        self.options = self.options.automatic_width_buffer_envs(names);
        self
    }

    /// Set the floor, in cells, for an automatically detected width.
    #[must_use]
    pub const fn minimum_automatic_width(mut self, cells: u16) -> Self {
        self.options = self.options.minimum_automatic_width(cells);
        self
    }

    /// Lay out to `width` cells when no width is detected. `None` turns the
    /// fallback off, so tables render at their natural width.
    #[must_use]
    pub const fn fallback_width(mut self, width: Option<u16>) -> Self {
        self.options = self.options.fallback_width(width);
        self
    }

    /// The colour, width, and style settings pretty output renders with:
    /// the buffer, its environment names, the minimum, the fallback, and the
    /// styles.
    #[must_use]
    pub const fn render_options(self) -> RenderOptions {
        self.options
    }

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

    /// `document` in the colour and at the width decided for `stream`.
    fn pretty(self, stream: ctl_term::Stream, document: &Document) -> String {
        self.options.render_for(stream, document)
    }

    /// Render `value` without writing it. Tests and alternate transports use
    /// this path.
    ///
    /// JSON output is `value` serialized in the layout
    /// [`Self::resolved_json_layout`] returns, for stdout. Pretty output is
    /// rendered as [`Self::show`] would write it. Colour and width are decided
    /// for the stream [`Captured::stream`] names, from the colour mode, the
    /// process environment, and whether that stream is a terminal.
    ///
    /// # Errors
    ///
    /// Returns an error when `value` does not serialize to JSON.
    pub fn capture(self, value: &impl Present) -> io::Result<Captured> {
        let outcome = value.outcome();
        let exit_code = value.exit_code();
        if self.format.is_json() {
            return Ok(Captured {
                stream: Destination::Stdout,
                content: self.json(value)?,
                exit_code,
            });
        }
        if self.quiet && outcome == Outcome::Success {
            return Ok(Captured {
                stream: Destination::None,
                content: String::new(),
                exit_code,
            });
        }
        let (stream, target) = match outcome {
            Outcome::Success => (Destination::Stdout, ctl_term::Stream::Stdout),
            Outcome::Error => (Destination::Stderr, ctl_term::Stream::Stderr),
        };
        Ok(Captured {
            stream,
            content: self.pretty(target, &value.present()),
            exit_code,
        })
    }

    /// Render `value` and write it to the stream [`Self::capture`] picks.
    /// Returns the exit code for `main` to return.
    ///
    /// # Errors
    ///
    /// Returns an error when `value` does not serialize to JSON, or when
    /// writing to stdout or stderr fails.
    pub fn show(self, value: &impl Present) -> io::Result<ExitCode> {
        let captured = self.capture(value)?;
        match captured.stream() {
            Destination::None => {}
            Destination::Stdout => write_stdout(captured.bytes())?,
            Destination::Stderr => write_stderr(captured.bytes())?,
        }
        Ok(captured.exit_code())
    }

    /// Write a failure that has no [`Present`] model, such as a parse error.
    ///
    /// Pretty output is `{bin}: {message}` on stderr. JSON output is an
    /// [`Envelope`] with an [`ErrorBody`] on stdout, in this view's layout.
    /// The exit code is [`ExitCode::FAILURE`] in both.
    ///
    /// # Errors
    ///
    /// Returns an error when writing to stdout or stderr fails.
    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())?;
            return Ok(ExitCode::FAILURE);
        }
        let document =
            Document::new().paragraph(Text::new().error(bin).then(": ").then(message.to_owned()));
        write_stderr(self.pretty(ctl_term::Stream::Stderr, &document).as_bytes())?;
        Ok(ExitCode::FAILURE)
    }
}

/// Write bytes to stdout as they are. Pretty output already holds exactly
/// the escapes decided for its stream, and JSON and protocol text hold none.
pub(crate) fn write_stdout(bytes: &[u8]) -> io::Result<()> {
    let mut stream = io::stdout().lock();
    stream.write_all(bytes)?;
    stream.flush()
}

/// Write bytes to stderr as they are; see [`write_stdout`].
pub(crate) fn write_stderr(bytes: &[u8]) -> io::Result<()> {
    let mut stream = io::stderr().lock();
    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.json_layout_with(compact), JsonLayout::Compact);
        assert_eq!(
            view.json_layout(JsonLayout::Pretty)
                .json_layout_with(compact),
            JsonLayout::Pretty
        );
        assert_eq!(
            view.json_layout_envs(&[]).json_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",
            ]
        );
    }
}