cargo_plugin_utils/
tty.rs1use std::io::IsTerminal;
4
5#[allow(clippy::disallowed_methods)] pub fn should_show_progress() -> bool {
27 match std::env::var("CARGO_TERM_PROGRESS_WHEN")
30 .as_deref()
31 .unwrap_or("auto")
32 {
33 "never" => false,
34 "always" => true,
35 "auto" => {
36 std::io::stdout().is_terminal()
38 }
39 _ => {
40 std::io::stdout().is_terminal()
42 }
43 }
44}
45
46#[cfg(test)]
47mod tests {
48 use std::env;
49
50 use super::*;
51
52 fn with_env_var<F, R>(key: &str, value: Option<&str>, test_fn: F) -> R
55 where
56 F: FnOnce() -> R,
57 {
58 let original = env::var(key).ok();
59 match value {
60 Some(val) => unsafe { env::set_var(key, val) },
61 None => unsafe { env::remove_var(key) },
62 }
63 let result = test_fn();
64 match original {
65 Some(val) => unsafe { env::set_var(key, &val) },
66 None => unsafe { env::remove_var(key) },
67 }
68 result
69 }
70
71 #[test]
72 fn test_should_show_progress_default() {
73 with_env_var("CARGO_TERM_PROGRESS_WHEN", None, || {
75 let _ = should_show_progress();
77 });
78 }
79
80 #[test]
81 fn test_should_show_progress_never() {
82 with_env_var("CARGO_TERM_PROGRESS_WHEN", Some("never"), || {
83 assert!(
84 !should_show_progress(),
85 "should return false when set to 'never'"
86 );
87 });
88 }
89
90 #[test]
91 fn test_should_show_progress_always() {
92 with_env_var("CARGO_TERM_PROGRESS_WHEN", Some("always"), || {
93 assert!(
94 should_show_progress(),
95 "should return true when set to 'always'"
96 );
97 });
98 }
99
100 #[test]
101 fn test_should_show_progress_auto() {
102 with_env_var("CARGO_TERM_PROGRESS_WHEN", Some("auto"), || {
103 let _ = should_show_progress();
105 });
106 }
107
108 #[test]
109 fn test_should_show_progress_unknown_value() {
110 with_env_var("CARGO_TERM_PROGRESS_WHEN", Some("unknown_value"), || {
112 let _ = should_show_progress();
114 });
115 }
116
117 #[test]
118 fn test_should_show_progress_empty_string() {
119 with_env_var("CARGO_TERM_PROGRESS_WHEN", Some(""), || {
121 let _ = should_show_progress();
122 });
123 }
124}