]> git.lizzy.rs Git - rust.git/blob - src/config/options.rs
Remove `--verbose-diff`
[rust.git] / src / config / options.rs
1 // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use syntax::codemap::FileName;
12
13 use config::config_type::ConfigType;
14 use config::file_lines::FileLines;
15 use config::lists::*;
16 use config::Config;
17 use {FmtResult, WRITE_MODE_LIST};
18
19 use failure::err_msg;
20
21 use getopts::Matches;
22 use std::collections::HashSet;
23 use std::path::{Path, PathBuf};
24 use std::str::FromStr;
25
26 /// Macro for deriving implementations of Serialize/Deserialize for enums
27 #[macro_export]
28 macro_rules! impl_enum_serialize_and_deserialize {
29     ( $e:ident, $( $x:ident ),* ) => {
30         impl ::serde::ser::Serialize for $e {
31             fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
32                 where S: ::serde::ser::Serializer
33             {
34                 use serde::ser::Error;
35
36                 // We don't know whether the user of the macro has given us all options.
37                 #[allow(unreachable_patterns)]
38                 match *self {
39                     $(
40                         $e::$x => serializer.serialize_str(stringify!($x)),
41                     )*
42                     _ => {
43                         Err(S::Error::custom(format!("Cannot serialize {:?}", self)))
44                     }
45                 }
46             }
47         }
48
49         impl<'de> ::serde::de::Deserialize<'de> for $e {
50             fn deserialize<D>(d: D) -> Result<Self, D::Error>
51                     where D: ::serde::Deserializer<'de> {
52                 use serde::de::{Error, Visitor};
53                 use std::marker::PhantomData;
54                 use std::fmt;
55                 struct StringOnly<T>(PhantomData<T>);
56                 impl<'de, T> Visitor<'de> for StringOnly<T>
57                         where T: ::serde::Deserializer<'de> {
58                     type Value = String;
59                     fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
60                         formatter.write_str("string")
61                     }
62                     fn visit_str<E>(self, value: &str) -> Result<String, E> {
63                         Ok(String::from(value))
64                     }
65                 }
66                 let s = d.deserialize_string(StringOnly::<D>(PhantomData))?;
67                 $(
68                     if stringify!($x).eq_ignore_ascii_case(&s) {
69                       return Ok($e::$x);
70                     }
71                 )*
72                 static ALLOWED: &'static[&str] = &[$(stringify!($x),)*];
73                 Err(D::Error::unknown_variant(&s, ALLOWED))
74             }
75         }
76
77         impl ::std::str::FromStr for $e {
78             type Err = &'static str;
79
80             fn from_str(s: &str) -> Result<Self, Self::Err> {
81                 $(
82                     if stringify!($x).eq_ignore_ascii_case(s) {
83                         return Ok($e::$x);
84                     }
85                 )*
86                 Err("Bad variant")
87             }
88         }
89
90         impl ConfigType for $e {
91             fn doc_hint() -> String {
92                 let mut variants = Vec::new();
93                 $(
94                     variants.push(stringify!($x));
95                 )*
96                 format!("[{}]", variants.join("|"))
97             }
98         }
99     };
100 }
101
102 macro_rules! configuration_option_enum{
103     ($e:ident: $( $x:ident ),+ $(,)*) => {
104         #[derive(Copy, Clone, Eq, PartialEq, Debug)]
105         pub enum $e {
106             $( $x ),+
107         }
108
109         impl_enum_serialize_and_deserialize!($e, $( $x ),+);
110     }
111 }
112
113 configuration_option_enum! { NewlineStyle:
114     Windows, // \r\n
115     Unix, // \n
116     Native, // \r\n in Windows, \n on other platforms
117 }
118
119 configuration_option_enum! { BraceStyle:
120     AlwaysNextLine,
121     PreferSameLine,
122     // Prefer same line except where there is a where clause, in which case force
123     // the brace to the next line.
124     SameLineWhere,
125 }
126
127 configuration_option_enum! { ControlBraceStyle:
128     // K&R style, Rust community default
129     AlwaysSameLine,
130     // Stroustrup style
131     ClosingNextLine,
132     // Allman style
133     AlwaysNextLine,
134 }
135
136 configuration_option_enum! { IndentStyle:
137     // First line on the same line as the opening brace, all lines aligned with
138     // the first line.
139     Visual,
140     // First line is on a new line and all lines align with block indent.
141     Block,
142 }
143
144 configuration_option_enum! { Density:
145     // Fit as much on one line as possible.
146     Compressed,
147     // Use more lines.
148     Tall,
149     // Place every item on a separate line.
150     Vertical,
151 }
152
153 configuration_option_enum! { TypeDensity:
154     // No spaces around "=" and "+"
155     Compressed,
156     // Spaces around " = " and " + "
157     Wide,
158 }
159
160 impl Density {
161     pub fn to_list_tactic(self) -> ListTactic {
162         match self {
163             Density::Compressed => ListTactic::Mixed,
164             Density::Tall => ListTactic::HorizontalVertical,
165             Density::Vertical => ListTactic::Vertical,
166         }
167     }
168 }
169
170 configuration_option_enum! { ReportTactic:
171     Always,
172     Unnumbered,
173     Never,
174 }
175
176 configuration_option_enum! { WriteMode:
177     // Backs the original file up and overwrites the original.
178     Replace,
179     // Overwrites original file without backup.
180     Overwrite,
181     // Writes the output to stdout.
182     Display,
183     // Writes the diff to stdout.
184     Diff,
185     // Displays how much of the input file was processed
186     Coverage,
187     // Unfancy stdout
188     Checkstyle,
189     // Output the changed lines (for internal value only)
190     Modified,
191     // Checks if a diff can be generated. If so, rustfmt outputs a diff and quits with exit code 1.
192     // This option is designed to be run in CI where a non-zero exit signifies non-standard code
193     // formatting.
194     Check,
195     // Rustfmt shouldn't output anything formatting-like (e.g., emit a help message).
196     None,
197 }
198
199 configuration_option_enum! { Color:
200     // Always use color, whether it is a piped or terminal output
201     Always,
202     // Never use color
203     Never,
204     // Automatically use color, if supported by terminal
205     Auto,
206 }
207
208 configuration_option_enum! { Verbosity:
209     // Emit more.
210     Verbose,
211     Normal,
212     // Emit as little as possible.
213     Quiet,
214 }
215
216 #[derive(Deserialize, Serialize, Clone, Debug)]
217 pub struct WidthHeuristics {
218     // Maximum width of the args of a function call before falling back
219     // to vertical formatting.
220     pub fn_call_width: usize,
221     // Maximum width in the body of a struct lit before falling back to
222     // vertical formatting.
223     pub struct_lit_width: usize,
224     // Maximum width in the body of a struct variant before falling back
225     // to vertical formatting.
226     pub struct_variant_width: usize,
227     // Maximum width of an array literal before falling back to vertical
228     // formatting.
229     pub array_width: usize,
230     // Maximum length of a chain to fit on a single line.
231     pub chain_width: usize,
232     // Maximum line length for single line if-else expressions. A value
233     // of zero means always break if-else expressions.
234     pub single_line_if_else_max_width: usize,
235 }
236
237 impl WidthHeuristics {
238     // Using this WidthHeuristics means we ignore heuristics.
239     pub fn null() -> WidthHeuristics {
240         WidthHeuristics {
241             fn_call_width: usize::max_value(),
242             struct_lit_width: 0,
243             struct_variant_width: 0,
244             array_width: usize::max_value(),
245             chain_width: usize::max_value(),
246             single_line_if_else_max_width: 0,
247         }
248     }
249
250     // scale the default WidthHeuristics according to max_width
251     pub fn scaled(max_width: usize) -> WidthHeuristics {
252         const DEFAULT_MAX_WIDTH: usize = 100;
253         let max_width_ratio = if max_width > DEFAULT_MAX_WIDTH {
254             let ratio = max_width as f32 / DEFAULT_MAX_WIDTH as f32;
255             // round to the closest 0.1
256             (ratio * 10.0).round() / 10.0
257         } else {
258             1.0
259         };
260         WidthHeuristics {
261             fn_call_width: (60.0 * max_width_ratio).round() as usize,
262             struct_lit_width: (18.0 * max_width_ratio).round() as usize,
263             struct_variant_width: (35.0 * max_width_ratio).round() as usize,
264             array_width: (60.0 * max_width_ratio).round() as usize,
265             chain_width: (60.0 * max_width_ratio).round() as usize,
266             single_line_if_else_max_width: (50.0 * max_width_ratio).round() as usize,
267         }
268     }
269 }
270
271 impl ::std::str::FromStr for WidthHeuristics {
272     type Err = &'static str;
273
274     fn from_str(_: &str) -> Result<Self, Self::Err> {
275         Err("WidthHeuristics is not parsable")
276     }
277 }
278
279 impl Default for WriteMode {
280     fn default() -> WriteMode {
281         WriteMode::Overwrite
282     }
283 }
284
285 /// A set of directories, files and modules that rustfmt should ignore.
286 #[derive(Default, Deserialize, Serialize, Clone, Debug)]
287 pub struct IgnoreList(HashSet<PathBuf>);
288
289 impl IgnoreList {
290     pub fn add_prefix(&mut self, dir: &Path) {
291         self.0 = self
292             .0
293             .iter()
294             .map(|s| {
295                 if s.has_root() {
296                     s.clone()
297                 } else {
298                     let mut path = PathBuf::from(dir);
299                     path.push(s);
300                     path
301                 }
302             })
303             .collect();
304     }
305
306     fn skip_file_inner(&self, file: &Path) -> bool {
307         self.0.iter().any(|path| file.starts_with(path))
308     }
309
310     pub fn skip_file(&self, file: &FileName) -> bool {
311         if let FileName::Real(ref path) = file {
312             self.skip_file_inner(path)
313         } else {
314             false
315         }
316     }
317 }
318
319 impl ::std::str::FromStr for IgnoreList {
320     type Err = &'static str;
321
322     fn from_str(_: &str) -> Result<Self, Self::Err> {
323         Err("IgnoreList is not parsable")
324     }
325 }
326
327 /// Parsed command line options.
328 #[derive(Clone, Debug, Default)]
329 pub struct CliOptions {
330     skip_children: Option<bool>,
331     quiet: bool,
332     verbose: bool,
333     pub(super) config_path: Option<PathBuf>,
334     write_mode: Option<WriteMode>,
335     color: Option<Color>,
336     file_lines: FileLines, // Default is all lines in all files.
337     unstable_features: bool,
338     error_on_unformatted: Option<bool>,
339 }
340
341 impl CliOptions {
342     pub fn from_matches(matches: &Matches) -> FmtResult<CliOptions> {
343         let mut options = CliOptions::default();
344         options.verbose = matches.opt_present("verbose");
345         options.quiet = matches.opt_present("quiet");
346         if options.verbose && options.quiet {
347             return Err(format_err!("Can't use both `--verbose` and `--quiet`"));
348         }
349
350         let unstable_features = matches.opt_present("unstable-features");
351         let rust_nightly = option_env!("CFG_RELEASE_CHANNEL")
352             .map(|c| c == "nightly")
353             .unwrap_or(false);
354         if unstable_features && !rust_nightly {
355             return Err(format_err!(
356                 "Unstable features are only available on Nightly channel"
357             ));
358         } else {
359             options.unstable_features = unstable_features;
360         }
361
362         options.config_path = matches.opt_str("config-path").map(PathBuf::from);
363
364         if let Some(ref write_mode) = matches.opt_str("write-mode") {
365             if let Ok(write_mode) = WriteMode::from_str(write_mode) {
366                 options.write_mode = Some(write_mode);
367             } else {
368                 return Err(format_err!(
369                     "Invalid write-mode: {}, expected one of {}",
370                     write_mode,
371                     WRITE_MODE_LIST
372                 ));
373             }
374         }
375
376         if let Some(ref color) = matches.opt_str("color") {
377             match Color::from_str(color) {
378                 Ok(color) => options.color = Some(color),
379                 _ => return Err(format_err!("Invalid color: {}", color)),
380             }
381         }
382
383         if let Some(ref file_lines) = matches.opt_str("file-lines") {
384             options.file_lines = file_lines.parse().map_err(err_msg)?;
385         }
386
387         if matches.opt_present("skip-children") {
388             options.skip_children = Some(true);
389         }
390         if matches.opt_present("error-on-unformatted") {
391             options.error_on_unformatted = Some(true);
392         }
393
394         Ok(options)
395     }
396
397     pub fn apply_to(self, config: &mut Config) {
398         if self.verbose {
399             config.set().verbose(Verbosity::Verbose);
400         } else if self.quiet {
401             config.set().verbose(Verbosity::Quiet);
402         } else {
403             config.set().verbose(Verbosity::Normal);
404         }
405         config.set().file_lines(self.file_lines);
406         config.set().unstable_features(self.unstable_features);
407         if let Some(skip_children) = self.skip_children {
408             config.set().skip_children(skip_children);
409         }
410         if let Some(error_on_unformatted) = self.error_on_unformatted {
411             config.set().error_on_unformatted(error_on_unformatted);
412         }
413         if let Some(write_mode) = self.write_mode {
414             config.set().write_mode(write_mode);
415         }
416         if let Some(color) = self.color {
417             config.set().color(color);
418         }
419     }
420
421     pub fn verify_file_lines(&self, files: &[PathBuf]) {
422         for f in self.file_lines.files() {
423             match *f {
424                 FileName::Real(ref f) if files.contains(f) => {}
425                 FileName::Real(_) => {
426                     eprintln!("Warning: Extra file listed in file_lines option '{}'", f)
427                 }
428                 _ => eprintln!("Warning: Not a file '{}'", f),
429             }
430         }
431     }
432 }