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?
Your code already works:
Prints the output:
Note that there's a bunch of junk scattered inside the output (
[44;
,[0m
, etc.). Those are ANSI escape codes, and the terminal emulator interprets those to change the color of the following text.If you print the string with debugging, you will see:
Each escape code starts with an
ESC
(\u{1b}
) followed by the actual command. You will have to parse those in order to ignore them for whatever processing you are doing.Windows does not use escape codes (although maybe it can in Windows 10?), and instead a program directly modifies the console it is connected to. There is nothing in the output to indicate the color.