Skip to content

config: Introduce RunConfig for config related to a single run #795

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 12 additions & 7 deletions src/bin/rustfmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -78,9 +79,12 @@ fn lookup_and_read_project_file(input_file: &Path) -> io::Result<(PathBuf, Strin
Ok((path, toml))
}

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 {
Expand Down Expand Up @@ -131,13 +135,14 @@ 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) => {
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(),
Expand All @@ -146,9 +151,9 @@ 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
}
Expand Down
30 changes: 5 additions & 25 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -270,17 +261,6 @@ macro_rules! create_config {
)+
}
}

// Template for the default configuration
impl Default for Config {
fn default() -> Config {
Config {
$(
$i: $def,
)+
}
}
}
)
}

Expand Down
6 changes: 5 additions & 1 deletion src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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;
Expand Down
41 changes: 26 additions & 15 deletions src/filemap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand All @@ -34,13 +35,19 @@ pub fn append_newlines(file_map: &mut FileMap) {
pub fn write_all_files<T>(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();

Expand All @@ -51,7 +58,8 @@ pub fn write_all_files<T>(file_map: &FileMap,
// Prints all newlines either as `\n` or as `\r\n`.
pub fn write_system_newlines<T>(writer: T,
text: &StringBuffer,
config: &Config)
config: &Config,
_run_config: &RunConfig)
-> Result<(), io::Error>
where T: Write
{
Expand Down Expand Up @@ -88,35 +96,38 @@ pub fn write_file<T>(text: &StringBuffer,
filename: &str,
out: &mut T,
mode: WriteMode,
config: &Config)
config: &Config,
run_config: &RunConfig)
-> Result<Option<String>, 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<Vec<Mismatch>, 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
Expand All @@ -126,7 +137,7 @@ pub fn write_file<T>(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));
Expand All @@ -137,22 +148,22 @@ pub fn write_file<T>(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));
}
Expand All @@ -161,7 +172,7 @@ pub fn write_file<T>(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));
}
}
Expand Down
5 changes: 4 additions & 1 deletion src/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
47 changes: 31 additions & 16 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -55,6 +56,7 @@ mod expr;
mod imports;
mod issues;
mod rewrite;
pub mod run_config;
mod string;
mod comment;
mod modules;
Expand Down Expand Up @@ -265,18 +267,19 @@ 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();
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, 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);
}
Expand All @@ -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() };

Expand Down Expand Up @@ -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(),
Expand All @@ -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
Expand All @@ -393,15 +400,15 @@ 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);

// Suppress error output after parsing.
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.
Expand All @@ -424,27 +431,35 @@ 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);
}
}

// 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);
Expand Down
Loading