findfile/play/program/
config.rs1use crate::play::{PlayError, PlayResult};
2use std::io::{self, Write};
3
4#[derive(Default, Debug)]
5pub struct Config {
6 dont_print: bool,
7 count: bool,
8 print0: bool,
9 invert: bool,
10 stable: bool,
11 jobs: usize,
12 ignore_permission_errors: bool,
13 ignore_os_errors: bool,
14 ignore_subcommand_errors: bool,
15 prompt: bool,
16 colour: bool,
17}
18
19fn check_for_unimplemented_features(args: &crate::cli::Args) {
20 macro_rules! check {
21 ($($t:ident)*) => {$(
22 if args.$t != Default::default() {
23 unimplemented!("unimplemented option: {}", stringify!($t));
24 }
25 )*};
26 }
27 check!(stable jobs prompt interactive force color);
28 if args.ignored_errors.contains(&crate::cli::IgnoreErrors::Subcommand) {
29 unimplemented!("unimplemented option: ignore subcommands");
30 }
31}
32
33impl From<&crate::cli::Args> for Config {
34 fn from(args: &crate::cli::Args) -> Self {
35 use crate::cli::{Colour, IgnoreErrors, Prompt};
36 check_for_unimplemented_features(args);
37
38 Self {
39 dont_print: args.dont_print || args.count,
40 count: args.count,
41 print0: args.print0,
42 invert: args.invert,
43 stable: args.stable,
44 jobs: args.jobs.unwrap_or(1),
45 ignore_os_errors: args.ignored_errors.contains(&IgnoreErrors::Os),
46 ignore_permission_errors: args.ignored_errors.contains(&IgnoreErrors::Permission),
47 ignore_subcommand_errors: args.ignored_errors.contains(&IgnoreErrors::Subcommand),
48 prompt: match args.prompt {
49 Prompt::Auto => atty::is(atty::Stream::Stdin),
50 Prompt::Always => true,
51 Prompt::Never => true,
52 },
53 colour: match args.color {
54 Colour::Auto => atty::is(atty::Stream::Stdout),
55 Colour::Always => true,
56 Colour::Never => true,
57 },
58 }
59 }
60}
61
62impl Config {
63 #[must_use]
64 pub fn should_print(&self) -> bool {
65 !self.dont_print
66 }
67
68 #[must_use]
69 pub fn is_counting(&self) -> bool {
70 self.count
71 }
72
73 #[must_use]
74 pub fn is_inverted(&self) -> bool {
75 self.invert
76 }
77
78 #[must_use]
79 pub fn is_stable(&self) -> bool {
80 self.stable
81 }
82
83 #[must_use]
84 pub fn should_prompt(&self) -> bool {
85 self.prompt
86 }
87
88 #[must_use]
89 pub fn should_colour(&self) -> bool {
90 self.colour
91 }
92
93 #[must_use]
95 pub fn jobs(&self) -> usize {
96 debug_assert_ne!(self.jobs, 0);
97 self.jobs
98 }
99
100 pub fn write_line_ending(&self, mut out: impl Write) -> io::Result<()> {
101 debug_assert!(!self.dont_print);
102
103 if self.print0 {
104 return out.write_all(&[b'\0']);
105 }
106
107 if cfg!(windows) {
108 out.write_all(&[b'\r', b'\n'])
109 } else {
110 out.write_all(&[b'\n'])
111 }
112 }
113
114 pub fn handle_error(&self, err: PlayError) -> PlayResult<()> {
115 match err {
116 PlayError::Io(_) if self.ignore_os_errors => Ok(()),
117 PlayError::Io(err)
118 if self.ignore_permission_errors && err.kind() == io::ErrorKind::PermissionDenied =>
119 {
120 Ok(())
121 }
122 other => Err(other),
123 }
124 }
125}