about summary refs log tree commit diff stats
path: root/yt/src/comments/output.rs
blob: 626db2a704348acea337aa64ebc6b34836dfe8f1 (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
// yt - A fully featured command line YouTube client
//
// Copyright (C) 2024 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 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 mut child = Command::new("fmt")
        .args(["--uniform-spacing", "--split-only", "--width=90"])
        .stdin(Stdio::piped())
        .stderr(Stdio::inherit())
        .stdout(less.stdin.take().unreachable("Should be open"))
        .spawn()
        .context("Failed to run fmt")?;

    let mut stdin = child.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(())
}