about summary refs log tree commit diff stats
path: root/yt/src/comments/output.rs
blob: cb3a9c48ca8a72c845f2dcc49639d0587366d1f7 (plain) (blame)
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
// yt - A fully featured command line YouTube client
//
// Copyright (C) 2024 Benedikt Peetz <benedikt.peetz@b-peetz.de>
// Copyright (C) 2025 Benedikt Peetz <benedikt.peetz@b-peetz.de>
// SPDX-License-Identifier: GPL-3.0-or-later
//
// This file is part of Yt.
//
// You should have received a copy of the License along with this program.
// If not, see <https://www.gnu.org/licenses/gpl-3.0.txt>.

use std::{
    io::Write,
    process::{Command, Stdio},
};

use anyhow::{Context, Result};
use uu_fmt::{FmtOptions, process_text};

use crate::unreachable::Unreachable;

pub async fn display_fmt_and_less(input: String) -> Result<()> {
    let mut less = Command::new("less")
        .args(["--raw-control-chars"])
        .stdin(Stdio::piped())
        .stderr(Stdio::inherit())
        .spawn()
        .context("Failed to run less")?;

    let input = format_text(&input);
    let mut stdin = less.stdin.take().context("Failed to open stdin")?;
    std::thread::spawn(move || {
        stdin
            .write_all(input.as_bytes())
            .unreachable("Should be able to write to the stdin of less");
    });

    let _ = less.wait().context("Failed to await less")?;

    Ok(())
}

#[must_use]
pub fn format_text(input: &str) -> String {
    let width = termsize::get().map_or(90, |size| size.cols);
    let fmt_opts = FmtOptions {
        uniform: true,
        split_only: true,
        ..FmtOptions::new(Some(width as usize), None, Some(4))
    };

    process_text(input, &fmt_opts)
}