Skip to content

Commit cc7a884

Browse files
committed
Implement custom error type for load_config
1 parent 5ab7dd0 commit cc7a884

File tree

4 files changed

+98
-43
lines changed

4 files changed

+98
-43
lines changed

src/bin/main.rs

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,6 @@ fn format_string(input: String, options: GetOptsOptions) -> Result<i32> {
276276
}
277277

278278
let out = &mut stdout();
279-
rustfmt::abort_or_warn_on_unstable_options!(config);
280279
let mut session = Session::new(config, Some(out));
281280
format_and_emit_report(&mut session, Input::Text(input));
282281

@@ -304,7 +303,6 @@ fn format(
304303

305304
let out = &mut stdout();
306305

307-
rustfmt::abort_or_warn_on_unstable_options!(config);
308306
let mut session = Session::new(config, Some(out));
309307

310308
for file in files {
@@ -329,7 +327,6 @@ fn format(
329327
}
330328
}
331329

332-
rustfmt::abort_or_warn_on_unstable_options!(local_config);
333330
session.override_config(local_config, |sess| {
334331
format_and_emit_report(sess, Input::File(file))
335332
});

src/config/config_type.rs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,37 @@ macro_rules! create_config {
158158
}
159159
}
160160

161+
#[allow(unreachable_pub)]
162+
pub fn collect_unstable_options(&mut self) {
163+
if crate::is_nightly_channel!() {
164+
return
165+
}
166+
167+
let mut unstable_options = vec![];
168+
let abort_option = "abort_on_unrecognised_options";
169+
170+
$(
171+
// self.$i.3 = 'is this a stable options'
172+
// self.$1.1 = 'was this set by the user'
173+
// the abort option is currently unstable so it needs to be special cased
174+
// otherwise we would abort when using it.
175+
if !self.$i.3 && self.$i.1 && stringify!($i) != abort_option {
176+
unstable_options.push(format!("{} = {:?}", stringify!($i), self.$i.2));
177+
}
178+
179+
)+
180+
181+
if unstable_options.len() > 0 {
182+
if let Some(mut options) = self.configured_unstable_options.take() {
183+
options.append(&mut unstable_options);
184+
options.sort();
185+
options.dedup();
186+
} else {
187+
self.configured_unstable_options.replace(unstable_options);
188+
}
189+
}
190+
}
191+
161192
/// Returns true if any unstable options were set while on the stable channel
162193
#[allow(unreachable_pub)]
163194
pub fn using_unstable_options_on_stable_channel(&self) -> bool {

src/config/mod.rs

Lines changed: 65 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -325,29 +325,62 @@ impl Config {
325325

326326
/// When using nightly options on stable channel decide whether to abort or
327327
/// log out warnings to the user.
328-
pub fn abort_or_warn_on_unstable_options(&self) -> Option<HandleUnstableOptions> {
328+
pub fn abort_or_warn_on_unstable_options(&self) -> HandleUnstableOptions {
329329
if !self.using_unstable_options_on_stable_channel() {
330-
return None;
330+
return HandleUnstableOptions::Continue;
331331
}
332332

333333
if self.abort_on_unrecognised_options() {
334-
Some(HandleUnstableOptions::Abort(
335-
self.unstable_options_abort_message().unwrap(),
336-
))
334+
HandleUnstableOptions::Abort(self.unstable_options_abort_message().unwrap())
337335
} else {
338-
Some(HandleUnstableOptions::Warn(
339-
self.unstable_options_warning_message().unwrap(),
340-
))
336+
HandleUnstableOptions::Warn(self.unstable_options_warning_message().unwrap())
341337
}
342338
}
343339
}
344340

341+
/// Errors that can occur when loading configuration
342+
#[derive(Debug)]
343+
pub enum LoadConfigurationError {
344+
/// An io error when reading configuration.
345+
IoError(std::io::Error),
346+
/// Used unstable options on the stable channel
347+
UsedUnstableOptions(String),
348+
}
349+
350+
impl From<std::io::Error> for LoadConfigurationError {
351+
fn from(e: std::io::Error) -> LoadConfigurationError {
352+
LoadConfigurationError::IoError(e)
353+
}
354+
}
355+
356+
impl std::error::Error for LoadConfigurationError {}
357+
358+
impl std::fmt::Display for LoadConfigurationError {
359+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
360+
match self {
361+
Self::IoError(e) => e.fmt(f),
362+
Self::UsedUnstableOptions(msg) => {
363+
write!(f, "{}", msg)
364+
}
365+
}
366+
}
367+
}
368+
369+
pub enum HandleUnstableOptions {
370+
// Exit early. Do not allow rustfmt to format any files
371+
Abort(String),
372+
// Warn the user that they are using unstable options and format files
373+
Warn(String),
374+
// Proceed as normal. No need to warn or abort.
375+
Continue,
376+
}
377+
345378
/// Loads a config by checking the client-supplied options and if appropriate, the
346379
/// file system (including searching the file system for overrides).
347380
pub fn load_config<O: CliOptions>(
348381
file_path: Option<&Path>,
349382
options: Option<O>,
350-
) -> Result<(Config, Option<PathBuf>), Error> {
383+
) -> Result<(Config, Option<PathBuf>), LoadConfigurationError> {
351384
let over_ride = match options {
352385
Some(ref opts) => config_path(opts)?,
353386
None => None,
@@ -361,12 +394,23 @@ pub fn load_config<O: CliOptions>(
361394
Ok((Config::default(), None))
362395
};
363396

364-
result.map(|(mut c, p)| {
397+
let (config, options) = result.map(|(mut c, p)| {
365398
if let Some(options) = options {
366399
options.apply_to(&mut c);
400+
c.collect_unstable_options();
367401
}
368402
(c, p)
369-
})
403+
})?;
404+
405+
use HandleUnstableOptions::{Abort, Continue, Warn};
406+
match config.abort_or_warn_on_unstable_options() {
407+
Abort(s) => Err(LoadConfigurationError::UsedUnstableOptions(s)),
408+
Warn(warning) => {
409+
eprint!("{}", warning);
410+
Ok((config, options))
411+
}
412+
Continue => Ok((config, options)),
413+
}
370414
}
371415

372416
// Check for the presence of known config file names (`rustfmt.toml, `.rustfmt.toml`) in `dir`
@@ -420,29 +464,6 @@ fn config_path(options: &dyn CliOptions) -> Result<Option<PathBuf>, Error> {
420464
}
421465
}
422466

423-
#[macro_export]
424-
macro_rules! abort_or_warn_on_unstable_options {
425-
($config:expr) => {
426-
match $config.abort_or_warn_on_unstable_options() {
427-
Some($crate::HandleUnstableOptions::Abort(message)) => {
428-
eprint!("{}", message);
429-
return Ok(1);
430-
}
431-
Some($crate::HandleUnstableOptions::Warn(message)) => {
432-
eprint!("{}", message);
433-
}
434-
None => {}
435-
}
436-
};
437-
}
438-
439-
#[allow(unreachable_pub)]
440-
pub use abort_or_warn_on_unstable_options;
441-
pub enum HandleUnstableOptions {
442-
Abort(String),
443-
Warn(String),
444-
}
445-
446467
#[cfg(test)]
447468
mod test {
448469
use super::*;
@@ -701,7 +722,7 @@ Set `abort_on_unrecognised_options = false` to convert this error into a warning
701722
let config = Config::from_toml(toml, Path::new("")).unwrap();
702723
assert!(matches!(
703724
config.abort_or_warn_on_unstable_options(),
704-
Some(HandleUnstableOptions::Warn(_))
725+
HandleUnstableOptions::Warn(_)
705726
))
706727
}
707728

@@ -718,7 +739,7 @@ Set `abort_on_unrecognised_options = false` to convert this error into a warning
718739
let config = Config::from_toml(toml, Path::new("")).unwrap();
719740
assert!(matches!(
720741
config.abort_or_warn_on_unstable_options(),
721-
Some(HandleUnstableOptions::Abort(_))
742+
HandleUnstableOptions::Abort(_)
722743
))
723744
}
724745

@@ -733,7 +754,10 @@ Set `abort_on_unrecognised_options = false` to convert this error into a warning
733754
array_width = 50
734755
"#;
735756
let config = Config::from_toml(toml, Path::new("")).unwrap();
736-
assert!(matches!(config.abort_or_warn_on_unstable_options(), None))
757+
assert!(matches!(
758+
config.abort_or_warn_on_unstable_options(),
759+
HandleUnstableOptions::Continue
760+
))
737761
}
738762

739763
#[test]
@@ -747,7 +771,10 @@ Set `abort_on_unrecognised_options = false` to convert this error into a warning
747771
array_width = 50
748772
"#;
749773
let config = Config::from_toml(toml, Path::new("")).unwrap();
750-
assert!(matches!(config.abort_or_warn_on_unstable_options(), None))
774+
assert!(matches!(
775+
config.abort_or_warn_on_unstable_options(),
776+
HandleUnstableOptions::Continue
777+
))
751778
}
752779

753780
#[test]

src/lib.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,8 @@ use crate::syntux::parser::DirectoryOwnership;
4545
use crate::utils::indent_next_line;
4646

4747
pub use crate::config::{
48-
load_config, CliOptions, Color, Config, Edition, EmitMode, FileLines, FileName,
49-
HandleUnstableOptions, NewlineStyle, Range, Verbosity,
48+
load_config, CliOptions, Color, Config, Edition, EmitMode, FileLines, FileName, NewlineStyle,
49+
Range, Verbosity,
5050
};
5151

5252
pub use crate::format_report_formatter::{FormatReportFormatter, FormatReportFormatterBuilder};

0 commit comments

Comments
 (0)