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