Debian Codegraph @

src/control.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 //! A couple of functions to enable and disable coloring.
2
3 use std::default::Default;
4 use std::env;
5 use std::io::{self, IsTerminal};
6 use std::sync::atomic::{AtomicBool, Ordering};
7 use std::sync::LazyLock;
8
9 /// Sets a flag to the console to use a virtual terminal environment.
10 ///
11 /// This is primarily used for Windows 10 environments which will not correctly colorize
12 /// the outputs based on ANSI escape codes.
13 ///
14 /// The returned `Result` is _always_ `Ok(())`, the return type was kept to ensure backwards
15 /// compatibility.
16 ///
17 /// # Notes
18 /// > Only available to `Windows` build targets.
19 ///
20 /// # Example
21 /// ```rust
22 /// use colored::*;
23 /// control::set_virtual_terminal(false).unwrap();
24 /// println!("{}", "bright cyan".bright_cyan()); // will print 'bright cyan' on windows 10
25 ///
26 /// control::set_virtual_terminal(true).unwrap();
27 /// println!("{}", "bright cyan".bright_cyan()); // will print correctly
28 /// ```
29 /// # Errors
30 /// This function will return `Ok(())` if the operation was successful.
31 #[allow(clippy::result_unit_err)]
32 #[cfg(windows)]
33 pub fn set_virtual_terminal(use_virtual: bool) -> Result<(), ()> {
34 use windows_sys::Win32::System::Console::{
35 GetConsoleMode, GetStdHandle, SetConsoleMode, ENABLE_VIRTUAL_TERMINAL_PROCESSING,
36 STD_OUTPUT_HANDLE,
37 };
38
39 #[allow(unsafe_code)] // needed here
40 unsafe {
41 let handle = GetStdHandle(STD_OUTPUT_HANDLE);
42 let mut original_mode = 0;
43 GetConsoleMode(handle, &mut original_mode);
44
45 let enabled = original_mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING
46 == ENABLE_VIRTUAL_TERMINAL_PROCESSING;
47
48 match (use_virtual, enabled) {
49 // not enabled, should be enabled
50 (true, false) => {
51 SetConsoleMode(handle, ENABLE_VIRTUAL_TERMINAL_PROCESSING | original_mode)
52 }
53 // already enabled, should be disabled
54 (false, true) => {
55 SetConsoleMode(handle, ENABLE_VIRTUAL_TERMINAL_PROCESSING ^ original_mode)
56 }
57 _ => 0,
58 };
59 }
60
61 Ok(())
62 }
63
64 /// A flag for whether coloring should occur.
65 pub struct ShouldColorize {
66 clicolor: bool,
67 clicolor_force: Option<bool>,
68 // XXX we can't use Option<Atomic> because we can't use &mut references to ShouldColorize
69 has_manual_override: AtomicBool,
70 manual_override: AtomicBool,
71 }
72
73 /// Use this to force colored to ignore the environment and always/never colorize
74 /// See example/control.rs
75 pub fn set_override(override_colorize: bool) {
76 SHOULD_COLORIZE.set_override(override_colorize);
77 }
78
79 /// Remove the manual override and let the environment decide if it's ok to colorize
80 /// See example/control.rs
81 pub fn unset_override() {
82 SHOULD_COLORIZE.unset_override();
83 }
84
85 /// The persistent [`ShouldColorize`].
86 pub static SHOULD_COLORIZE: LazyLock<ShouldColorize> = LazyLock::new(ShouldColorize::from_env);
87
88 impl Default for ShouldColorize {
89 fn default() -> Self {
90 Self {
91 clicolor: true,
92 clicolor_force: None,
93 has_manual_override: AtomicBool::new(false),
94 manual_override: AtomicBool::new(false),
95 }
96 }
97 }
98
99 impl ShouldColorize {
100 /// Reads environment variables and checks if output is a tty to determine
101 /// whether colorization should be used or not.
102 /// `CLICOLOR_FORCE` takes highest priority, followed by `NO_COLOR`,
103 /// followed by `CLICOLOR` combined with tty check.
104 #[must_use]
105 pub fn from_env() -> Self {
106 Self {
107 clicolor: Self::normalize_env(env::var("CLICOLOR")).unwrap_or(true)
108 && io::stdout().is_terminal(),
109 clicolor_force: Self::resolve_clicolor_force(
110 env::var("NO_COLOR"),
111 env::var("CLICOLOR_FORCE"),
112 ),
113 ..Self::default()
114 }
115 }
116
117 /// Returns if the current coloring is expected.
118 pub fn should_colorize(&self) -> bool {
119 if self.has_manual_override.load(Ordering::Relaxed) {
120 return self.manual_override.load(Ordering::Relaxed);
121 }
122
123 if let Some(forced_value) = self.clicolor_force {
124 return forced_value;
125 }
126
127 self.clicolor
128 }
129
130 /// Use this to force colored to ignore the environment and always/never colorize
131 pub fn set_override(&self, override_colorize: bool) {
132 self.has_manual_override.store(true, Ordering::Relaxed);
133 self.manual_override
134 .store(override_colorize, Ordering::Relaxed);
135 }
136
137 /// Remove the manual override and let the environment decide if it's ok to colorize
138 pub fn unset_override(&self) {
139 self.has_manual_override.store(false, Ordering::Relaxed);
140 }
141
142 /* private */
143
144 fn normalize_env(env_res: Result<String, env::VarError>) -> Option<bool> {
145 env_res.map_or(None, |string| Some(string != "0"))
146 }
147
148 fn resolve_clicolor_force(
149 no_color: Result<String, env::VarError>,
150 clicolor_force: Result<String, env::VarError>,
151 ) -> Option<bool> {
152 if Self::normalize_env(clicolor_force) == Some(true) {
153 Some(true)
154 } else if Self::normalize_env(no_color).is_some() {
155 Some(false)
156 } else {
157 None
158 }
159 }
160 }
161
•162 /*#[cfg(test)]
163
164 mod specs {
165 use super::*;
166 use rspec;
167 use std::env;
168
169 #[test]
170 fn clicolor_behavior() {
171 rspec::run(&rspec::describe("ShouldColorize", (), |ctx| {
172 ctx.specify("::normalize_env", |ctx| {
173 ctx.it("should return None if error", |()| {
174 assert_eq!(
175 None,
176 ShouldColorize::normalize_env(Err(env::VarError::NotPresent))
177 );
178 assert_eq!(
179 None,
180 ShouldColorize::normalize_env(Err(env::VarError::NotUnicode("".into())))
181 );
182 });
183
184 ctx.it("should return Some(true) if != 0", |()| {
185 Some(true) == ShouldColorize::normalize_env(Ok(String::from("1")))
186 });
187
188 ctx.it("should return Some(false) if == 0", |()| {
189 Some(false) == ShouldColorize::normalize_env(Ok(String::from("0")))
190 });
191 });
192
193 ctx.specify("::resolve_clicolor_force", |ctx| {
194 ctx.it(
195 "should return None if NO_COLOR is not set and CLICOLOR_FORCE is not set or set to 0",
196 |()| {
197 assert_eq!(
198 None,
199 ShouldColorize::resolve_clicolor_force(
200 Err(env::VarError::NotPresent),
201 Err(env::VarError::NotPresent)
202 )
203 );
204 assert_eq!(
205 None,
206 ShouldColorize::resolve_clicolor_force(
207 Err(env::VarError::NotPresent),
208 Ok(String::from("0")),
209 )
210 );
211 },
212 );
213
214 ctx.it(
215 "should return Some(false) if NO_COLOR is set and CLICOLOR_FORCE is not enabled",
216 |()| {
217 assert_eq!(
218 Some(false),
219 ShouldColorize::resolve_clicolor_force(
220 Ok(String::from("0")),
221 Err(env::VarError::NotPresent)
222 )
223 );
224 assert_eq!(
225 Some(false),
226 ShouldColorize::resolve_clicolor_force(
227 Ok(String::from("1")),
228 Err(env::VarError::NotPresent)
229 )
230 );
231 assert_eq!(
232 Some(false),
233 ShouldColorize::resolve_clicolor_force(
234 Ok(String::from("1")),
235 Ok(String::from("0")),
236 )
237 );
238 },
239 );
240
241 ctx.it(
242 "should prioritize CLICOLOR_FORCE over NO_COLOR if CLICOLOR_FORCE is set to non-zero value",
243 |()| {
244 assert_eq!(
245 Some(true),
246 ShouldColorize::resolve_clicolor_force(
247 Ok(String::from("1")),
248 Ok(String::from("1")),
249 )
250 );
251 assert_eq!(
252 Some(false),
253 ShouldColorize::resolve_clicolor_force(
254 Ok(String::from("1")),
255 Ok(String::from("0")),
256 )
257 );
258 assert_eq!(
259 Some(true),
260 ShouldColorize::resolve_clicolor_force(
261 Err(env::VarError::NotPresent),
262 Ok(String::from("1")),
263 )
264 );
265 },
266 );
267 });
268
269 ctx.specify("constructors", |ctx| {
270 ctx.it("should have a default constructor", |()| {
271 ShouldColorize::default();
272 });
273
274 ctx.it("should have an environment constructor", |()| {
275 #[allow(unused_must_use)]
276 ShouldColorize::from_env();
277 });
278 });
279
280 ctx.specify("when only changing clicolors", |ctx| {
281 ctx.it("clicolor == false means no colors", |()| {
282 let colorize_control = ShouldColorize {
283 clicolor: false,
284 ..ShouldColorize::default()
285 };
286 !colorize_control.should_colorize()
287 });
288
289 ctx.it("clicolor == true means colors !", |()| {
290 let colorize_control = ShouldColorize {
291 clicolor: true,
292 ..ShouldColorize::default()
293 };
294 colorize_control.should_colorize()
295 });
296
297 ctx.it("unset clicolors implies true", |()| {
298 ShouldColorize::default().should_colorize()
299 });
300 });
301
302 ctx.specify("when using clicolor_force", |ctx| {
303 ctx.it(
304 "clicolor_force should force to true no matter clicolor",
305 |()| {
306 let colorize_control = ShouldColorize {
307 clicolor: false,
308 clicolor_force: Some(true),
309 ..ShouldColorize::default()
310 };
311
312 colorize_control.should_colorize()
313 },
314 );
315
316 ctx.it(
317 "clicolor_force should force to false no matter clicolor",
318 |()| {
319 let colorize_control = ShouldColorize {
320 clicolor: true,
321 clicolor_force: Some(false),
322 ..ShouldColorize::default()
323 };
324
325 !colorize_control.should_colorize()
326 },
327 );
328 });
329
330 ctx.specify("using a manual override", |ctx| {
331 ctx.it("should colorize if manual_override is true, but clicolor is false and clicolor_force also false", |()| {
332 let colorize_control = ShouldColorize {
333 clicolor: false,
334 clicolor_force: None,
335 has_manual_override: AtomicBool::new(true),
336 manual_override: AtomicBool::new(true),
337 };
338
339 colorize_control.should_colorize();
340 });
341
342 ctx.it("should not colorize if manual_override is false, but clicolor is true or clicolor_force is true", |()| {
343 let colorize_control = ShouldColorize {
344 clicolor: true,
345 clicolor_force: Some(true),
346 has_manual_override: AtomicBool::new(true),
347 manual_override: AtomicBool::new(false),
348 };
349
350 !colorize_control.should_colorize()
351 });
352 });
353
354 ctx.specify("::set_override", |ctx| {
355 ctx.it("should exists", |()| {
356 let colorize_control = ShouldColorize::default();
357 colorize_control.set_override(true);
358 });
359
360 ctx.it("set the manual_override property", |()| {
361 let colorize_control = ShouldColorize::default();
362 colorize_control.set_override(true);
363 {
364 assert!(colorize_control.has_manual_override.load(Ordering::Relaxed));
365 let val = colorize_control.manual_override.load(Ordering::Relaxed);
366 assert!(val);
367 }
368 colorize_control.set_override(false);
369 {
370 assert!(colorize_control.has_manual_override.load(Ordering::Relaxed));
371 let val = colorize_control.manual_override.load(Ordering::Relaxed);
372 assert!(!val);
373 }
374 });
375 });
376
377 ctx.specify("::unset_override", |ctx| {
378 ctx.it("should exists", |()| {
379 let colorize_control = ShouldColorize::default();
380 colorize_control.unset_override();
381 });
382
383 ctx.it("unset the manual_override property", |()| {
384 let colorize_control = ShouldColorize::default();
385 colorize_control.set_override(true);
386 colorize_control.unset_override();
387 assert!(!colorize_control.has_manual_override.load(Ordering::Relaxed));
388 });
389 });
390 }));
391 }
•392 }*/