Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rust, how can I capture process output with colors?

I would like to capture output from another process (for example git status), process it, and print with all styles (bold, italics, underscore) and colors. It's very important for me to further process that String, I don't want only to print it.

In the Unix world, I think this would involve escape codes, I'm not sure about Windows world but it's important for me too.

I know how to do it without colors:

fn exec_git() -> String {
    let output = Command::new("git")
        .arg("status")
        .output()
        .expect("failed to execute process");

    String::from_utf8_lossy(&output.stdout).into_owned()
}

Maybe I should use spawn instead?

like image 851
Wojciech Polak Avatar asked Dec 30 '16 10:12

Wojciech Polak


1 Answers

You can force git to output colors by using git -c color.status=always status

use std::process::Command;

fn main() {
    let output = Command::new("git")
        .arg("-c")
        .arg("color.status=always")
        .arg("status")
        .output()
        .expect("failed to execute process");

    let output = String::from_utf8_lossy(&output.stdout).into_owned();

    println!("{}", output);
}

This works for git status only. For a more general solution, you either have to check the programs documentation and hope there is a way to force colored output or check how the program determines if it should output colors or not (such as checking for the COLORTERM environment variable).

like image 66
belst Avatar answered Sep 28 '22 00:09

belst