From e10b18daa12e05199898f6ea749ea4b97ef2706f Mon Sep 17 00:00:00 2001 From: Kamal Marhubi Date: Sat, 30 Jan 2016 21:27:53 -0500 Subject: [PATCH 1/3] config: Extract macro to implement Default and override_value Add an exported macro `impl_default_and_override` to `util`, allowing that functionality to be reused without also implementing parsing and documentation printing. --- src/config.rs | 30 ++---------- src/utils.rs | 130 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 135 insertions(+), 25 deletions(-) diff --git a/src/config.rs b/src/config.rs index 48b7a06e538..95c555f59f6 100644 --- a/src/config.rs +++ b/src/config.rs @@ -191,9 +191,11 @@ impl ConfigHelpItem { macro_rules! create_config { ($($i:ident: $ty:ty, $def:expr, $( $dstring:expr ),+ );+ $(;)*) => ( - #[derive(RustcDecodable, Clone)] - pub struct Config { - $(pub $i: $ty),+ + impl_default_and_override! { + #[derive(RustcDecodable, Clone)] + pub struct Config { + $(pub $i: $ty = $def),+ + } } // Just like the Config struct but with each property wrapped @@ -231,17 +233,6 @@ macro_rules! create_config { Config::default().fill_from_parsed_config(parsed_config) } - pub fn override_value(&mut self, key: &str, val: &str) { - match key { - $( - stringify!($i) => { - self.$i = val.parse::<$ty>().unwrap(); - } - )+ - _ => panic!("Bad config key!") - } - } - pub fn print_docs() { use std::cmp; let max = 0; @@ -270,17 +261,6 @@ macro_rules! create_config { )+ } } - - // Template for the default configuration - impl Default for Config { - fn default() -> Config { - Config { - $( - $i: $def, - )+ - } - } - } ) } diff --git a/src/utils.rs b/src/utils.rs index 3b03ede2be3..27a23d79bf6 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -199,6 +199,136 @@ pub fn round_up_to_power_of_two(mut x: usize) -> usize { x.wrapping_add(1) } +/// Helper macro to allow defining an empty struct with braces. +macro_rules! def_struct { + ($(#[$attr:meta])* pub struct $sname:ident {}) => ( + $(#[$attr])* + pub struct $sname; + ); + ($(#[$attr:meta])* pub struct $sname:ident { $(pub $field:ident: $ty:ty),+ $(,)* }) => ( + $(#[$attr])* + pub struct $sname { + $(pub $field: $ty),+ + } + ); +} + +/// Helper macro to allow defining `Default::default()` on an empty struct with braces. +macro_rules! def_default { + ($sname:ident {}) => ( + fn default() -> $sname { + $sname + } + ); + ($sname:ident { $($field:ident: $def:expr),+ }) => ( + fn default() -> $sname { + $sname { + $($field: $def),+ + } + } + ); +} + +/// Macro for creating structs that implement `Default`. +/// +/// # Limitations +/// +/// All structs and all fields must be `pub`. +macro_rules! impl_default { + ($($(#[$attr:meta])* + pub struct $sname:ident { + $(pub $field:ident: $ty:ty = $def:expr),* $(,)* + })*) => ($( + + def_struct! { + $(#[$attr])* + pub struct $sname { + $(pub $field: $ty),* + } + } + + impl ::std::default::Default for $sname { + def_default! { + $sname { + $($field: $def),* + } + } + } + )*) +} + +/// Macro for implementing an `override_value(&mut self, key: &str, val: &str)` method. +/// +/// # Limitations +/// +/// All field types must implement `FromStr`. +macro_rules! impl_override_value { + ($sname:ident { $($field:ident: $ty:ty),* $(,)* }) => ( + impl $sname { + #[allow(unused_variables)] + pub fn override_value(&mut self, key: &str, val: &str) { + match key { + $( + stringify!($field) => { + self.$field = val.parse::<$ty>().unwrap(); + } + )* + _ => panic!("Not a field of {}: {:?}", stringify!($sname), key) + } + } + } + ) +} + +/// Macro for creating structs that implement `Default` and an +/// `override_value(&mut self, key: &str, val: &str)` method. +/// +/// # Limitations +/// +/// - All structs and all fields must be `pub`; +/// - all field types must implement `FromStr`; and +/// - empty structs must be defined with braces. +/// +/// # Example +/// +/// ```ignore +/// impl_default_and_override! { +/// #[derive(Eq, PartialEq)] +/// pub struct Foo { +/// pub b: u32 = 42, +/// pub z: i8 = -1 +/// } +/// +/// #[derive(Debug)] +/// pub struct Bar {} +/// +/// #[derive(Debug)] +/// pub struct Baz { +/// pub a: bool = true, +/// } +/// } +/// ``` +#[macro_export] +macro_rules! impl_default_and_override { + ($($(#[$attr:meta])* + pub struct $sname:ident { + $(pub $field:ident: $ty:ty = $def:expr),* $(,)* + })*) => ($( + impl_default!{ + $(#[$attr])* + pub struct $sname { + $(pub $field:$ty = $def),* + } + } + + impl_override_value! { + $sname { + $($field: $ty),* + } + } + )*) +} + // Macro for deriving implementations of Decodable for enums #[macro_export] macro_rules! impl_enum_decodable { From 2ddbef73a7ac1f3e42f44245e03b701c70e97f59 Mon Sep 17 00:00:00 2001 From: Kamal Marhubi Date: Sat, 30 Jan 2016 15:30:03 -0500 Subject: [PATCH 2/3] config: Introduce RunConfig for config related to a single run This commit introduces a `RunConfig` struct, and threads it through all libraries, binaries, and tests. While initially empty, this will be a place to store configuration related to a single run of `rustfmt`, as distinct from configuration read in from the `rustfmt.toml` file. Examples of such per-run settings include: - the `write_mode` override - the `--verbose` flag - the `--skip-children` flag - line ranges to restrict formatting to; see #434 These will be added to `RunConfig` in later commits. refs https://github.com/rust-lang-nursery/rustfmt/issues/434 --- src/bin/rustfmt.rs | 11 +++++++++-- src/expr.rs | 6 +++++- src/filemap.rs | 41 ++++++++++++++++++++++++++--------------- src/items.rs | 5 ++++- src/lib.rs | 43 +++++++++++++++++++++++++++++-------------- src/rewrite.rs | 3 +++ src/run_config.rs | 14 ++++++++++++++ src/visitor.rs | 5 +++++ tests/system.rs | 26 ++++++++++++++++---------- 9 files changed, 111 insertions(+), 43 deletions(-) create mode 100644 src/run_config.rs diff --git a/src/bin/rustfmt.rs b/src/bin/rustfmt.rs index 1bea4430c30..417651418c7 100644 --- a/src/bin/rustfmt.rs +++ b/src/bin/rustfmt.rs @@ -19,6 +19,7 @@ extern crate getopts; use rustfmt::{run, run_from_stdin}; use rustfmt::config::{Config, WriteMode}; +use rustfmt::run_config::RunConfig; use std::env; use std::fs::{self, File}; @@ -78,6 +79,10 @@ fn lookup_and_read_project_file(input_file: &Path) -> io::Result<(PathBuf, Strin Ok((path, toml)) } +fn run_config_from_options(_matches: &Matches) -> RunConfig { + RunConfig::default() +} + fn update_config(config: &mut Config, matches: &Matches) { config.verbose = matches.opt_present("verbose"); config.skip_children = matches.opt_present("skip-children"); @@ -131,8 +136,9 @@ fn execute() -> i32 { Ok((_, toml)) => Config::from_toml(&toml), Err(_) => Default::default(), }; + let run_config = run_config_from_options(&matches); - run_from_stdin(input, write_mode, &config); + run_from_stdin(input, write_mode, &config, &run_config); 0 } Operation::Format(files, write_mode) => { @@ -146,9 +152,10 @@ fn execute() -> i32 { } Err(_) => Default::default(), }; + let run_config = run_config_from_options(&matches); update_config(&mut config, &matches); - run(&file, write_mode, &config); + run(&file, write_mode, &config, &run_config); } 0 } diff --git a/src/expr.rs b/src/expr.rs index 8e76001e731..8bdd9e70438 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -427,7 +427,10 @@ impl Rewrite for ast::Block { return Some(user_str); } - let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config, None); + let mut visitor = FmtVisitor::from_codemap(context.parse_session, + context.config, + context.run_config, + None); visitor.block_indent = context.block_indent; let prefix = match self.rules { @@ -956,6 +959,7 @@ impl Rewrite for ast::Arm { // more? let mut attr_visitor = FmtVisitor::from_codemap(context.parse_session, context.config, + context.run_config, None); attr_visitor.block_indent = context.block_indent; attr_visitor.last_pos = attrs[0].span.lo; diff --git a/src/filemap.rs b/src/filemap.rs index 61ad573f702..d28ccdbdd59 100644 --- a/src/filemap.rs +++ b/src/filemap.rs @@ -18,6 +18,7 @@ use std::fs::{self, File}; use std::io::{self, Write, Read, stdout, BufWriter}; use config::{NewlineStyle, Config, WriteMode}; +use run_config::RunConfig; use rustfmt_diff::{make_diff, print_diff, Mismatch}; use checkstyle::{output_header, output_footer, output_checkstyle_file}; @@ -34,13 +35,19 @@ pub fn append_newlines(file_map: &mut FileMap) { pub fn write_all_files(file_map: &FileMap, mut out: T, mode: WriteMode, - config: &Config) + config: &Config, + run_config: &RunConfig) -> Result<(), io::Error> where T: Write { output_header(&mut out, mode).ok(); for filename in file_map.keys() { - try!(write_file(&file_map[filename], filename, &mut out, mode, config)); + try!(write_file(&file_map[filename], + filename, + &mut out, + mode, + config, + run_config)); } output_footer(&mut out, mode).ok(); @@ -51,7 +58,8 @@ pub fn write_all_files(file_map: &FileMap, // Prints all newlines either as `\n` or as `\r\n`. pub fn write_system_newlines(writer: T, text: &StringBuffer, - config: &Config) + config: &Config, + _run_config: &RunConfig) -> Result<(), io::Error> where T: Write { @@ -88,35 +96,38 @@ pub fn write_file(text: &StringBuffer, filename: &str, out: &mut T, mode: WriteMode, - config: &Config) + config: &Config, + run_config: &RunConfig) -> Result, io::Error> where T: Write { fn source_and_formatted_text(text: &StringBuffer, filename: &str, - config: &Config) + config: &Config, + run_config: &RunConfig) -> Result<(String, String), io::Error> { let mut f = try!(File::open(filename)); let mut ori_text = String::new(); try!(f.read_to_string(&mut ori_text)); let mut v = Vec::new(); - try!(write_system_newlines(&mut v, text, config)); + try!(write_system_newlines(&mut v, text, config, run_config)); let fmt_text = String::from_utf8(v).unwrap(); Ok((ori_text, fmt_text)) } fn create_diff(filename: &str, text: &StringBuffer, - config: &Config) + config: &Config, + run_config: &RunConfig) -> Result, io::Error> { - let (ori, fmt) = try!(source_and_formatted_text(text, filename, config)); + let (ori, fmt) = try!(source_and_formatted_text(text, filename, config, run_config)); Ok(make_diff(&ori, &fmt, 3)) } match mode { WriteMode::Replace => { - if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config) { + if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config, run_config) { if fmt != ori { // Do a little dance to make writing safer - write to a temp file // rename the original to a .bk, then rename the temp file to the @@ -126,7 +137,7 @@ pub fn write_file(text: &StringBuffer, { // Write text to temp file let tmp_file = try!(File::create(&tmp_name)); - try!(write_system_newlines(tmp_file, text, config)); + try!(write_system_newlines(tmp_file, text, config, run_config)); } try!(fs::rename(filename, bk_name)); @@ -137,22 +148,22 @@ pub fn write_file(text: &StringBuffer, WriteMode::Overwrite => { // Write text directly over original file. let file = try!(File::create(filename)); - try!(write_system_newlines(file, text, config)); + try!(write_system_newlines(file, text, config, run_config)); } WriteMode::Plain => { let stdout = stdout(); let stdout = stdout.lock(); - try!(write_system_newlines(stdout, text, config)); + try!(write_system_newlines(stdout, text, config, run_config)); } WriteMode::Display | WriteMode::Coverage => { println!("{}:\n", filename); let stdout = stdout(); let stdout = stdout.lock(); - try!(write_system_newlines(stdout, text, config)); + try!(write_system_newlines(stdout, text, config, run_config)); } WriteMode::Diff => { println!("Diff of {}:\n", filename); - if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config) { + if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config, run_config) { print_diff(make_diff(&ori, &fmt, 3), |line_num| format!("\nDiff at line {}:", line_num)); } @@ -161,7 +172,7 @@ pub fn write_file(text: &StringBuffer, unreachable!("The WriteMode should NEVER Be default at this point!"); } WriteMode::Checkstyle => { - let diff = try!(create_diff(filename, text, config)); + let diff = try!(create_diff(filename, text, config, run_config)); try!(output_checkstyle_file(out, filename, diff)); } } diff --git a/src/items.rs b/src/items.rs index 2ff52148f6a..d0bfcc3067f 100644 --- a/src/items.rs +++ b/src/items.rs @@ -530,7 +530,10 @@ pub fn format_impl(context: &RewriteContext, item: &ast::Item, offset: Indent) - let open_pos = try_opt!(snippet.find_uncommented("{")) + 1; if !items.is_empty() || contains_comment(&snippet[open_pos..]) { - let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config, None); + let mut visitor = FmtVisitor::from_codemap(context.parse_session, + context.config, + context.run_config, + None); visitor.block_indent = context.block_indent.block_indent(context.config); visitor.last_pos = item.span.lo + BytePos(open_pos as u32); diff --git a/src/lib.rs b/src/lib.rs index ad9322ab649..3280dec5e86 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -40,6 +40,7 @@ use issues::{BadIssueSeeker, Issue}; use filemap::FileMap; use visitor::FmtVisitor; use config::{Config, WriteMode}; +use run_config::RunConfig; #[macro_use] mod utils; @@ -55,6 +56,7 @@ mod expr; mod imports; mod issues; mod rewrite; +pub mod run_config; mod string; mod comment; mod modules; @@ -265,6 +267,7 @@ fn fmt_ast(krate: &ast::Crate, parse_session: &ParseSess, main_file: &Path, config: &Config, + run_config: &RunConfig, mode: WriteMode) -> FileMap { let mut file_map = FileMap::new(); @@ -276,7 +279,7 @@ fn fmt_ast(krate: &ast::Crate, if config.verbose { println!("Formatting {}", path); } - let mut visitor = FmtVisitor::from_codemap(parse_session, config, Some(mode)); + let mut visitor = FmtVisitor::from_codemap(parse_session, config, run_config, Some(mode)); visitor.format_separate_mod(module); file_map.insert(path.to_owned(), visitor.buffer); } @@ -286,7 +289,7 @@ fn fmt_ast(krate: &ast::Crate, // Formatting done on a char by char or line by line basis. // TODO(#209) warn on bad license // TODO(#20) other stuff for parity with make tidy -pub fn fmt_lines(file_map: &mut FileMap, config: &Config) -> FormatReport { +pub fn fmt_lines(file_map: &mut FileMap, config: &Config, _run_config: &RunConfig) -> FormatReport { let mut truncate_todo = Vec::new(); let mut report = FormatReport { file_error_map: HashMap::new() }; @@ -366,7 +369,11 @@ pub fn fmt_lines(file_map: &mut FileMap, config: &Config) -> FormatReport { report } -pub fn format_string(input: String, config: &Config, mode: WriteMode) -> FileMap { +pub fn format_string(input: String, + config: &Config, + run_config: &RunConfig, + mode: WriteMode) + -> FileMap { let path = "stdin"; let mut parse_session = ParseSess::new(); let krate = parse::parse_crate_from_source_str(path.to_owned(), @@ -383,7 +390,7 @@ pub fn format_string(input: String, config: &Config, mode: WriteMode) -> FileMap let mut file_map = FileMap::new(); // do the actual formatting - let mut visitor = FmtVisitor::from_codemap(&parse_session, config, Some(mode)); + let mut visitor = FmtVisitor::from_codemap(&parse_session, config, run_config, Some(mode)); visitor.format_separate_mod(&krate.module); // append final newline @@ -393,7 +400,7 @@ pub fn format_string(input: String, config: &Config, mode: WriteMode) -> FileMap file_map } -pub fn format(file: &Path, config: &Config, mode: WriteMode) -> FileMap { +pub fn format(file: &Path, config: &Config, run_config: &RunConfig, mode: WriteMode) -> FileMap { let mut parse_session = ParseSess::new(); let krate = parse::parse_crate_from_file(file, Vec::new(), &parse_session); @@ -401,7 +408,7 @@ pub fn format(file: &Path, config: &Config, mode: WriteMode) -> FileMap { let emitter = Box::new(EmitterWriter::new(Box::new(Vec::new()), None)); parse_session.span_diagnostic.handler = Handler::with_emitter(false, emitter); - let mut file_map = fmt_ast(&krate, &parse_session, file, config, mode); + let mut file_map = fmt_ast(&krate, &parse_session, file, config, run_config, mode); // For some reason, the codemap does not include terminating // newlines so we must add one on for each file. This is sad. @@ -424,13 +431,13 @@ fn check_write_mode(arg: WriteMode, config: WriteMode) -> WriteMode { // to the compiler. // write_mode determines what happens to the result of running rustfmt, see // WriteMode. -pub fn run(file: &Path, write_mode: WriteMode, config: &Config) { +pub fn run(file: &Path, write_mode: WriteMode, config: &Config, run_config: &RunConfig) { let mode = check_write_mode(write_mode, config.write_mode); - let mut result = format(file, config, mode); + let mut result = format(file, config, run_config, mode); - print!("{}", fmt_lines(&mut result, config)); + print!("{}", fmt_lines(&mut result, config, run_config)); let out = stdout(); - let write_result = filemap::write_all_files(&result, out, mode, config); + let write_result = filemap::write_all_files(&result, out, mode, config, run_config); if let Err(msg) = write_result { println!("Error writing files: {}", msg); @@ -438,13 +445,21 @@ pub fn run(file: &Path, write_mode: WriteMode, config: &Config) { } // Similar to run, but takes an input String instead of a file to format -pub fn run_from_stdin(input: String, write_mode: WriteMode, config: &Config) { +pub fn run_from_stdin(input: String, + write_mode: WriteMode, + config: &Config, + run_config: &RunConfig) { let mode = check_write_mode(write_mode, config.write_mode); - let mut result = format_string(input, config, mode); - fmt_lines(&mut result, config); + let mut result = format_string(input, config, run_config, mode); + fmt_lines(&mut result, config, run_config); let mut out = stdout(); - let write_result = filemap::write_file(&result["stdin"], "stdin", &mut out, mode, config); + let write_result = filemap::write_file(&result["stdin"], + "stdin", + &mut out, + mode, + config, + run_config); if let Err(msg) = write_result { panic!("Error writing to stdout: {}", msg); diff --git a/src/rewrite.rs b/src/rewrite.rs index 5ca8d2e8241..3ff78d9a896 100644 --- a/src/rewrite.rs +++ b/src/rewrite.rs @@ -15,6 +15,7 @@ use syntax::parse::ParseSess; use Indent; use config::Config; +use run_config::RunConfig; pub trait Rewrite { /// Rewrite self into offset and width. @@ -31,6 +32,7 @@ pub struct RewriteContext<'a> { pub parse_session: &'a ParseSess, pub codemap: &'a CodeMap, pub config: &'a Config, + pub run_config: &'a RunConfig, // Indentation due to nesting of blocks. pub block_indent: Indent, } @@ -41,6 +43,7 @@ impl<'a> RewriteContext<'a> { parse_session: self.parse_session, codemap: self.codemap, config: self.config, + run_config: self.run_config, block_indent: self.block_indent.block_indent(self.config), } } diff --git a/src/run_config.rs b/src/run_config.rs new file mode 100644 index 00000000000..3e8801043ba --- /dev/null +++ b/src/run_config.rs @@ -0,0 +1,14 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/// Contains configuration specific to a single run of `rustfmt`. +impl_default_and_override! { + pub struct RunConfig {} +} diff --git a/src/visitor.rs b/src/visitor.rs index 073a05ef2bc..9dc69370af7 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -19,6 +19,7 @@ use Indent; use utils; use config::{Config, WriteMode}; use rewrite::{Rewrite, RewriteContext}; +use run_config::RunConfig; use comment::rewrite_comment; use macros::rewrite_macro; use items::{rewrite_static, rewrite_type_alias, format_impl}; @@ -31,6 +32,7 @@ pub struct FmtVisitor<'a> { // FIXME: use an RAII util or closure for indenting pub block_indent: Indent, pub config: &'a Config, + pub run_config: &'a RunConfig, pub write_mode: Option, } @@ -382,6 +384,7 @@ impl<'a> FmtVisitor<'a> { pub fn from_codemap(parse_session: &'a ParseSess, config: &'a Config, + run_config: &'a RunConfig, mode: Option) -> FmtVisitor<'a> { FmtVisitor { @@ -395,6 +398,7 @@ impl<'a> FmtVisitor<'a> { }, config: config, write_mode: mode, + run_config: run_config, } } @@ -518,6 +522,7 @@ impl<'a> FmtVisitor<'a> { parse_session: self.parse_session, codemap: self.codemap, config: self.config, + run_config: self.run_config, block_indent: self.block_indent, } } diff --git a/tests/system.rs b/tests/system.rs index 84dbf2e1abc..c13d5e05045 100644 --- a/tests/system.rs +++ b/tests/system.rs @@ -21,6 +21,7 @@ use std::path::Path; use rustfmt::*; use rustfmt::filemap::{write_system_newlines, FileMap}; use rustfmt::config::{Config, ReportTactic, WriteMode}; +use rustfmt::run_config::RunConfig; use rustfmt::rustfmt_diff::*; static DIFF_CONTEXT_SIZE: usize = 3; @@ -74,12 +75,12 @@ fn checkstyle_test() { // Helper function for comparing the results of rustfmt // to a known output file generated by one of the write modes. fn assert_output(source: &str, expected_filename: &str, write_mode: WriteMode) { - let config = read_config(&source); + let (config, run_config) = read_config(&source); let file_map = run_rustfmt(source.to_string(), write_mode); // Populate output by writing to a vec. let mut out = vec![]; - let _ = filemap::write_all_files(&file_map, &mut out, write_mode, &config); + let _ = filemap::write_all_files(&file_map, &mut out, write_mode, &config, &run_config); let output = String::from_utf8(out).unwrap(); let mut expected_file = fs::File::open(&expected_filename) @@ -181,40 +182,45 @@ fn print_mismatches(result: HashMap>) { assert!(t.reset().unwrap()); } -fn read_config(filename: &str) -> Config { +fn read_config(filename: &str) -> (Config, RunConfig) { let sig_comments = read_significant_comments(&filename); let mut config = get_config(sig_comments.get("config").map(|x| &(*x)[..])); + let mut run_config = RunConfig::default(); for (key, val) in &sig_comments { if key != "target" && key != "config" { - config.override_value(key, val); + if key.starts_with("run_config-") { + run_config.override_value(&key["run_config-".len()..], val); + } else { + config.override_value(key, val); + } } } // Don't generate warnings for to-do items. config.report_todo = ReportTactic::Never; - config + (config, run_config) } // Simulate run() fn run_rustfmt(filename: String, write_mode: WriteMode) -> FileMap { - let config = read_config(&filename); - format(Path::new(&filename), &config, write_mode) + let (config, run_config) = read_config(&filename); + format(Path::new(&filename), &config, &run_config, write_mode) } pub fn idempotent_check(filename: String, write_mode: WriteMode) -> Result>> { let sig_comments = read_significant_comments(&filename); - let config = read_config(&filename); + let (config, run_config) = read_config(&filename); let mut file_map = run_rustfmt(filename, write_mode); - let format_report = fmt_lines(&mut file_map, &config); + let format_report = fmt_lines(&mut file_map, &config, &run_config); let mut write_result = HashMap::new(); for (filename, text) in file_map.iter() { let mut v = Vec::new(); // Won't panic, as we're not doing any IO. - write_system_newlines(&mut v, text, &config).unwrap(); + write_system_newlines(&mut v, text, &config, &run_config).unwrap(); // Won't panic, we are writing correct utf8. let one_result = String::from_utf8(v).unwrap(); write_result.insert(filename.clone(), one_result); From b459c373d7d0c903a731de3399a4234486c6f216 Mon Sep 17 00:00:00 2001 From: Kamal Marhubi Date: Sat, 30 Jan 2016 23:28:14 -0500 Subject: [PATCH 3/3] config: Make verbose and skip_children run config settings --- src/bin/rustfmt.rs | 16 +++++++--------- src/lib.rs | 4 ++-- src/run_config.rs | 5 ++++- tests/source/mod_skip_child.rs | 2 +- tests/target/mod_skip_child.rs | 2 +- 5 files changed, 15 insertions(+), 14 deletions(-) diff --git a/src/bin/rustfmt.rs b/src/bin/rustfmt.rs index 417651418c7..c235545b757 100644 --- a/src/bin/rustfmt.rs +++ b/src/bin/rustfmt.rs @@ -79,13 +79,12 @@ fn lookup_and_read_project_file(input_file: &Path) -> io::Result<(PathBuf, Strin Ok((path, toml)) } -fn run_config_from_options(_matches: &Matches) -> RunConfig { - RunConfig::default() -} - -fn update_config(config: &mut Config, matches: &Matches) { - config.verbose = matches.opt_present("verbose"); - config.skip_children = matches.opt_present("skip-children"); +fn run_config_from_options(matches: &Matches) -> RunConfig { + RunConfig { + skip_children: matches.opt_present("skip-children"), + verbose: matches.opt_present("verbose"), + ..RunConfig::default() + } } fn execute() -> i32 { @@ -143,7 +142,7 @@ fn execute() -> i32 { } Operation::Format(files, write_mode) => { for file in files { - let mut config = match lookup_and_read_project_file(&file) { + let config = match lookup_and_read_project_file(&file) { Ok((path, toml)) => { println!("Using rustfmt config file {} for {}", path.display(), @@ -154,7 +153,6 @@ fn execute() -> i32 { }; let run_config = run_config_from_options(&matches); - update_config(&mut config, &matches); run(&file, write_mode, &config, &run_config); } 0 diff --git a/src/lib.rs b/src/lib.rs index 3280dec5e86..00deee23834 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -272,11 +272,11 @@ fn fmt_ast(krate: &ast::Crate, -> FileMap { let mut file_map = FileMap::new(); for (path, module) in modules::list_files(krate, parse_session.codemap()) { - if config.skip_children && path.as_path() != main_file { + if run_config.skip_children && path.as_path() != main_file { continue; } let path = path.to_str().unwrap(); - if config.verbose { + if run_config.verbose { println!("Formatting {}", path); } let mut visitor = FmtVisitor::from_codemap(parse_session, config, run_config, Some(mode)); diff --git a/src/run_config.rs b/src/run_config.rs index 3e8801043ba..f32db356258 100644 --- a/src/run_config.rs +++ b/src/run_config.rs @@ -10,5 +10,8 @@ /// Contains configuration specific to a single run of `rustfmt`. impl_default_and_override! { - pub struct RunConfig {} + pub struct RunConfig { + pub skip_children: bool = false, + pub verbose: bool = false, + } } diff --git a/tests/source/mod_skip_child.rs b/tests/source/mod_skip_child.rs index d48c4a37e81..0d59e4edf0a 100644 --- a/tests/source/mod_skip_child.rs +++ b/tests/source/mod_skip_child.rs @@ -1,2 +1,2 @@ -// rustfmt-skip_children: true +// rustfmt-run_config-skip_children: true mod nested_skipped; diff --git a/tests/target/mod_skip_child.rs b/tests/target/mod_skip_child.rs index d48c4a37e81..0d59e4edf0a 100644 --- a/tests/target/mod_skip_child.rs +++ b/tests/target/mod_skip_child.rs @@ -1,2 +1,2 @@ -// rustfmt-skip_children: true +// rustfmt-run_config-skip_children: true mod nested_skipped;