cli: use color only when stdout is a TTY

This adds a `ui.color` config that can be set to "always", "never", or
"auto". If set to "auto", we use color iff stdout is a TTY.
This commit is contained in:
Martin von Zweigbergk 2021-06-02 22:02:06 -07:00
parent 0fadac38d6
commit 9ce56f6cb7
3 changed files with 14 additions and 3 deletions

1
Cargo.lock generated
View file

@ -528,6 +528,7 @@ dependencies = [
name = "jujutsu" name = "jujutsu"
version = "0.2.0" version = "0.2.0"
dependencies = [ dependencies = [
"atty",
"blake2", "blake2",
"bytes", "bytes",
"chrono", "chrono",

View file

@ -20,6 +20,7 @@ path = "src/main.rs"
members = ["lib"] members = ["lib"]
[dependencies] [dependencies]
atty = "0.2.14"
blake2 = "0.9.2" blake2 = "0.9.2"
bytes = "1.1.0" bytes = "1.1.0"
chrono = "0.4.19" chrono = "0.4.19"

View file

@ -17,6 +17,7 @@ use std::path::{Component, Path, PathBuf};
use std::sync::{Mutex, MutexGuard}; use std::sync::{Mutex, MutexGuard};
use std::{fmt, io}; use std::{fmt, io};
use atty::Stream;
use jujutsu_lib::commit::Commit; use jujutsu_lib::commit::Commit;
use jujutsu_lib::repo::RepoRef; use jujutsu_lib::repo::RepoRef;
use jujutsu_lib::repo_path::{RepoPath, RepoPathComponent, RepoPathJoin}; use jujutsu_lib::repo_path::{RepoPath, RepoPathComponent, RepoPathJoin};
@ -48,10 +49,9 @@ impl<'stdout> Ui<'stdout> {
pub fn new( pub fn new(
cwd: PathBuf, cwd: PathBuf,
stdout: Box<dyn Write + 'stdout>, stdout: Box<dyn Write + 'stdout>,
is_atty: bool, color: bool,
settings: UserSettings, settings: UserSettings,
) -> Ui<'stdout> { ) -> Ui<'stdout> {
let color = is_atty;
let formatter = Mutex::new(new_formatter(&settings, color, stdout)); let formatter = Mutex::new(new_formatter(&settings, color, stdout));
Ui { Ui {
cwd, cwd,
@ -64,7 +64,16 @@ impl<'stdout> Ui<'stdout> {
pub fn for_terminal(settings: UserSettings) -> Ui<'static> { pub fn for_terminal(settings: UserSettings) -> Ui<'static> {
let cwd = std::env::current_dir().unwrap(); let cwd = std::env::current_dir().unwrap();
let stdout: Box<dyn Write + 'static> = Box::new(io::stdout()); let stdout: Box<dyn Write + 'static> = Box::new(io::stdout());
Ui::new(cwd, stdout, true, settings) let color_setting = settings
.config()
.get_str("ui.color")
.unwrap_or_else(|_| "auto".to_string());
let color = match color_setting.as_str() {
"always" => true,
"never" => false,
_ => atty::is(Stream::Stdout),
};
Ui::new(cwd, stdout, color, settings)
} }
pub fn cwd(&self) -> &Path { pub fn cwd(&self) -> &Path {