]> git.lizzy.rs Git - rust.git/blob - src/conf.rs
Start implementing a configuration file
[rust.git] / src / conf.rs
1 use std::{fmt, fs, io};
2 use std::io::Read;
3 use syntax::{ast, codemap, ptr};
4 use syntax::parse::token;
5 use toml;
6
7 /// Get the configuration file from arguments.
8 pub fn conf_file(args: &[ptr::P<ast::MetaItem>]) -> Result<Option<token::InternedString>, (&'static str, codemap::Span)> {
9     for arg in args {
10         match arg.node {
11             ast::MetaItemKind::Word(ref name) | ast::MetaItemKind::List(ref name, _) => {
12                 if name == &"conf_file" {
13                     return Err(("`conf_file` must be a named value", arg.span));
14                 }
15             }
16             ast::MetaItemKind::NameValue(ref name, ref value) => {
17                 if name == &"conf_file" {
18                     return if let ast::LitKind::Str(ref file, _) = value.node {
19                         Ok(Some(file.clone()))
20                     } else {
21                         Err(("`conf_file` value must be a string", value.span))
22                     }
23                 }
24             }
25         }
26     }
27
28     Ok(None)
29 }
30
31 /// Error from reading a configuration file.
32 #[derive(Debug)]
33 pub enum ConfError {
34     IoError(io::Error),
35     TomlError(Vec<toml::ParserError>),
36     TypeError(&'static str, &'static str, &'static str),
37     UnknownKey(String),
38 }
39
40 impl fmt::Display for ConfError {
41     fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
42         match *self {
43             ConfError::IoError(ref err) => {
44                 err.fmt(f)
45             }
46             ConfError::TomlError(ref errs) => {
47                 let mut first = true;
48                 for err in errs {
49                     if !first {
50                         try!(", ".fmt(f));
51                         first = false;
52                     }
53
54                     try!(err.fmt(f));
55                 }
56
57                 Ok(())
58             }
59             ConfError::TypeError(ref key, ref expected, ref got) => {
60                 write!(f, "`{}` is expected to be a `{}` but is a `{}`", key, expected, got)
61             }
62             ConfError::UnknownKey(ref key) => {
63                 write!(f, "unknown key `{}`", key)
64             }
65         }
66     }
67 }
68
69 impl From<io::Error> for ConfError {
70     fn from(e: io::Error) -> Self {
71         ConfError::IoError(e)
72     }
73 }
74
75 macro_rules! define_Conf {
76     ($(($toml_name: tt, $rust_name: ident, $default: expr, $ty: ident),)+) => {
77         /// Type used to store lint configuration.
78         pub struct Conf {
79             $(pub $rust_name: $ty,)+
80         }
81
82         impl Default for Conf {
83             fn default() -> Conf {
84                 Conf {
85                     $($rust_name: $default,)+
86                 }
87             }
88         }
89
90         impl Conf {
91             /// Set the property `name` (which must be the `toml` name) to the given value
92             #[allow(cast_sign_loss)]
93             fn set(&mut self, name: String, value: toml::Value) -> Result<(), ConfError> {
94                 match name.as_str() {
95                     $(
96                         define_Conf!(PAT $toml_name) => {
97                             if let Some(value) = define_Conf!(CONV $ty, value) {
98                                 self.$rust_name = value;
99                             }
100                             else {
101                                 return Err(ConfError::TypeError(define_Conf!(EXPR $toml_name),
102                                                                 stringify!($ty),
103                                                                 value.type_str()));
104                             }
105                         },
106                     )+
107                     _ => {
108                         return Err(ConfError::UnknownKey(name));
109                     }
110                 }
111
112                 Ok(())
113             }
114         }
115     };
116
117     // hack to convert tts
118     (PAT $pat: pat) => { $pat };
119     (EXPR $e: expr) => { $e };
120
121     // how to read the value?
122     (CONV i64, $value: expr) => { $value.as_integer() };
123     (CONV u64, $value: expr) => { $value.as_integer().iter().filter_map(|&i| if i >= 0 { Some(i as u64) } else { None }).next() };
124     (CONV String, $value: expr) => { $value.as_str().map(Into::into) };
125     (CONV StringVec, $value: expr) => {{
126         let slice = $value.as_slice();
127
128         if let Some(slice) = slice {
129             if slice.iter().any(|v| v.as_str().is_none()) {
130                 None
131             }
132             else {
133                 Some(slice.iter().map(|v| v.as_str().unwrap_or_else(|| unreachable!()).to_owned()).collect())
134             }
135         }
136         else {
137             None
138         }
139     }};
140 }
141
142 /// To keep the `define_Conf!` macro simple
143 pub type StringVec = Vec<String>;
144
145 define_Conf! {
146     ("blacklisted-names", blacklisted_names, vec!["foo".to_owned(), "bar".to_owned(), "baz".to_owned()], StringVec),
147     ("cyclomatic-complexity-threshold", cyclomatic_complexity_threshold, 25, u64),
148     ("too-many-arguments-threshold", too_many_arguments_threshold, 6, u64),
149     ("type-complexity-threshold", type_complexity_threshold, 250, u64),
150 }
151
152 /// Read the `toml` configuration file. The function will ignore “File not found” errors iif
153 /// `!must_exist`, in which case, it will return the default configuration.
154 pub fn read_conf(path: &str, must_exist: bool) -> Result<Conf, ConfError> {
155     let mut conf = Conf::default();
156
157     let file = match fs::File::open(path) {
158         Ok(mut file) => {
159             let mut buf = String::new();
160             try!(file.read_to_string(&mut buf));
161             buf
162         }
163         Err(ref err) if !must_exist && err.kind() == io::ErrorKind::NotFound => {
164             return Ok(conf);
165         }
166         Err(err) => {
167             return Err(err.into());
168         }
169     };
170
171     let mut parser = toml::Parser::new(&file);
172     let toml = if let Some(toml) = parser.parse() {
173         toml
174     }
175     else {
176         return Err(ConfError::TomlError(parser.errors));
177     };
178
179     for (key, value) in toml {
180         try!(conf.set(key, value));
181     }
182
183     Ok(conf)
184 }