Skip to content

Commit 2159c8b

Browse files
committed
config: Use write_mode from config
This commit tidies up handling of `write_mode` by setting it in the config at the start, and removing the `write_mode` parameter threaded throughout the formatting process.
1 parent 0fb71d0 commit 2159c8b

File tree

9 files changed

+72
-102
lines changed

9 files changed

+72
-102
lines changed

src/bin/rustfmt.rs

+22-21
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,14 @@ use std::env;
2424
use std::fs::{self, File};
2525
use std::io::{self, ErrorKind, Read, Write};
2626
use std::path::{Path, PathBuf};
27+
use std::str::FromStr;
2728

2829
use getopts::{Matches, Options};
2930

3031
/// Rustfmt operations.
3132
enum Operation {
3233
/// Format files and their child modules.
33-
Format(Vec<PathBuf>, WriteMode, Option<PathBuf>),
34+
Format(Vec<PathBuf>, Option<PathBuf>),
3435
/// Print the help message.
3536
Help,
3637
// Print version information
@@ -40,7 +41,7 @@ enum Operation {
4041
/// Invalid program input, including reason.
4142
InvalidInput(String),
4243
/// No file specified, read from stdin
43-
Stdin(String, WriteMode, Option<PathBuf>),
44+
Stdin(String, Option<PathBuf>),
4445
}
4546

4647
/// Try to find a project file in the given directory and its parents. Returns the path of a the
@@ -112,6 +113,14 @@ fn match_cli_path_or_file(config_path: Option<PathBuf>,
112113
fn update_config(config: &mut Config, matches: &Matches) {
113114
config.verbose = matches.opt_present("verbose");
114115
config.skip_children = matches.opt_present("skip-children");
116+
117+
let write_mode = matches.opt_str("write-mode").map(|ref s| {
118+
WriteMode::from_str(s).expect(&format!("Invalid write-mode: {}", s))
119+
});
120+
121+
if let Some(write_mode) = write_mode {
122+
config.write_mode = write_mode;
123+
}
115124
}
116125

117126
fn execute() -> i32 {
@@ -161,15 +170,18 @@ fn execute() -> i32 {
161170
Config::print_docs();
162171
0
163172
}
164-
Operation::Stdin(input, write_mode, config_path) => {
173+
Operation::Stdin(input, config_path) => {
165174
// try to read config from local directory
166-
let (config, _) = match_cli_path_or_file(config_path, &env::current_dir().unwrap())
167-
.expect("Error resolving config");
175+
let (mut config, _) = match_cli_path_or_file(config_path, &env::current_dir().unwrap())
176+
.expect("Error resolving config");
177+
178+
// write_mode is always Plain for Stdin.
179+
config.write_mode = WriteMode::Plain;
168180

169-
run_from_stdin(input, write_mode, &config);
181+
run_from_stdin(input, &config);
170182
0
171183
}
172-
Operation::Format(files, write_mode, config_path) => {
184+
Operation::Format(files, config_path) => {
173185
let mut config = Config::default();
174186
let mut path = None;
175187
// Load the config path file if provided
@@ -199,7 +211,7 @@ fn execute() -> i32 {
199211
}
200212

201213
update_config(&mut config, &matches);
202-
run(&file, write_mode, &config);
214+
run(&file, &config);
203215
}
204216
0
205217
}
@@ -267,21 +279,10 @@ fn determine_operation(matches: &Matches) -> Operation {
267279
Err(e) => return Operation::InvalidInput(e.to_string()),
268280
}
269281

270-
// WriteMode is always plain for Stdin
271-
return Operation::Stdin(buffer, WriteMode::Plain, config_path);
282+
return Operation::Stdin(buffer, config_path);
272283
}
273284

274-
let write_mode = match matches.opt_str("write-mode") {
275-
Some(mode) => {
276-
match mode.parse() {
277-
Ok(mode) => mode,
278-
Err(..) => return Operation::InvalidInput("Unrecognized write mode".into()),
279-
}
280-
}
281-
None => WriteMode::Default,
282-
};
283-
284285
let files: Vec<_> = matches.free.iter().map(PathBuf::from).collect();
285286

286-
Operation::Format(files, write_mode, config_path)
287+
Operation::Format(files, config_path)
287288
}

src/config.rs

+1-4
Original file line numberDiff line numberDiff line change
@@ -121,9 +121,6 @@ configuration_option_enum! { ReportTactic:
121121
}
122122

123123
configuration_option_enum! { WriteMode:
124-
// Used internally to represent when no option is given
125-
// Treated as Replace.
126-
Default,
127124
// Backsup the original file and overwrites the orignal.
128125
Replace,
129126
// Overwrites original file without backup.
@@ -349,6 +346,6 @@ create_config! {
349346
match_block_trailing_comma: bool, false,
350347
"Put a trailing comma after a block based match arm (non-block arms are not affected)";
351348
match_wildcard_trailing_comma: bool, true, "Put a trailing comma after a wildcard arm";
352-
write_mode: WriteMode, WriteMode::Default,
349+
write_mode: WriteMode, WriteMode::Replace,
353350
"What Write Mode to use when none is supplied: Replace, Overwrite, Display, Diff, Coverage";
354351
}

src/expr.rs

+2-4
Original file line numberDiff line numberDiff line change
@@ -427,7 +427,7 @@ impl Rewrite for ast::Block {
427427
return Some(user_str);
428428
}
429429

430-
let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config, None);
430+
let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
431431
visitor.block_indent = context.block_indent;
432432

433433
let prefix = match self.rules {
@@ -954,9 +954,7 @@ impl Rewrite for ast::Arm {
954954
let attr_str = if !attrs.is_empty() {
955955
// We only use this visitor for the attributes, should we use it for
956956
// more?
957-
let mut attr_visitor = FmtVisitor::from_codemap(context.parse_session,
958-
context.config,
959-
None);
957+
let mut attr_visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
960958
attr_visitor.block_indent = context.block_indent;
961959
attr_visitor.last_pos = attrs[0].span.lo;
962960
if attr_visitor.visit_attrs(attrs) {

src/filemap.rs

+5-13
Original file line numberDiff line numberDiff line change
@@ -31,18 +31,14 @@ pub fn append_newlines(file_map: &mut FileMap) {
3131
}
3232
}
3333

34-
pub fn write_all_files<T>(file_map: &FileMap,
35-
mut out: T,
36-
mode: WriteMode,
37-
config: &Config)
38-
-> Result<(), io::Error>
34+
pub fn write_all_files<T>(file_map: &FileMap, mut out: T, config: &Config) -> Result<(), io::Error>
3935
where T: Write
4036
{
41-
output_header(&mut out, mode).ok();
37+
output_header(&mut out, config.write_mode).ok();
4238
for filename in file_map.keys() {
43-
try!(write_file(&file_map[filename], filename, &mut out, mode, config));
39+
try!(write_file(&file_map[filename], filename, &mut out, config));
4440
}
45-
output_footer(&mut out, mode).ok();
41+
output_footer(&mut out, config.write_mode).ok();
4642

4743
Ok(())
4844
}
@@ -87,7 +83,6 @@ pub fn write_system_newlines<T>(writer: T,
8783
pub fn write_file<T>(text: &StringBuffer,
8884
filename: &str,
8985
out: &mut T,
90-
mode: WriteMode,
9186
config: &Config)
9287
-> Result<Option<String>, io::Error>
9388
where T: Write
@@ -114,7 +109,7 @@ pub fn write_file<T>(text: &StringBuffer,
114109
Ok(make_diff(&ori, &fmt, 3))
115110
}
116111

117-
match mode {
112+
match config.write_mode {
118113
WriteMode::Replace => {
119114
if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config) {
120115
if fmt != ori {
@@ -157,9 +152,6 @@ pub fn write_file<T>(text: &StringBuffer,
157152
|line_num| format!("\nDiff at line {}:", line_num));
158153
}
159154
}
160-
WriteMode::Default => {
161-
unreachable!("The WriteMode should NEVER Be default at this point!");
162-
}
163155
WriteMode::Checkstyle => {
164156
let diff = try!(create_diff(filename, text, config));
165157
try!(output_checkstyle_file(out, filename, diff));

src/items.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -530,7 +530,7 @@ pub fn format_impl(context: &RewriteContext, item: &ast::Item, offset: Indent) -
530530
let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
531531

532532
if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
533-
let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config, None);
533+
let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
534534
visitor.block_indent = context.block_indent.block_indent(context.config);
535535
visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
536536

src/lib.rs

+13-28
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ use std::fmt;
3939
use issues::{BadIssueSeeker, Issue};
4040
use filemap::FileMap;
4141
use visitor::FmtVisitor;
42-
use config::{Config, WriteMode};
42+
use config::Config;
4343

4444
#[macro_use]
4545
mod utils;
@@ -264,8 +264,7 @@ impl fmt::Display for FormatReport {
264264
fn fmt_ast(krate: &ast::Crate,
265265
parse_session: &ParseSess,
266266
main_file: &Path,
267-
config: &Config,
268-
mode: WriteMode)
267+
config: &Config)
269268
-> FileMap {
270269
let mut file_map = FileMap::new();
271270
for (path, module) in modules::list_files(krate, parse_session.codemap()) {
@@ -276,7 +275,7 @@ fn fmt_ast(krate: &ast::Crate,
276275
if config.verbose {
277276
println!("Formatting {}", path);
278277
}
279-
let mut visitor = FmtVisitor::from_codemap(parse_session, config, Some(mode));
278+
let mut visitor = FmtVisitor::from_codemap(parse_session, config);
280279
visitor.format_separate_mod(module);
281280
file_map.insert(path.to_owned(), visitor.buffer);
282281
}
@@ -366,7 +365,7 @@ pub fn fmt_lines(file_map: &mut FileMap, config: &Config) -> FormatReport {
366365
report
367366
}
368367

369-
pub fn format_string(input: String, config: &Config, mode: WriteMode) -> FileMap {
368+
pub fn format_string(input: String, config: &Config) -> FileMap {
370369
let path = "stdin";
371370
let mut parse_session = ParseSess::new();
372371
let krate = parse::parse_crate_from_source_str(path.to_owned(),
@@ -383,7 +382,7 @@ pub fn format_string(input: String, config: &Config, mode: WriteMode) -> FileMap
383382
let mut file_map = FileMap::new();
384383

385384
// do the actual formatting
386-
let mut visitor = FmtVisitor::from_codemap(&parse_session, config, Some(mode));
385+
let mut visitor = FmtVisitor::from_codemap(&parse_session, config);
387386
visitor.format_separate_mod(&krate.module);
388387

389388
// append final newline
@@ -393,15 +392,15 @@ pub fn format_string(input: String, config: &Config, mode: WriteMode) -> FileMap
393392
file_map
394393
}
395394

396-
pub fn format(file: &Path, config: &Config, mode: WriteMode) -> FileMap {
395+
pub fn format(file: &Path, config: &Config) -> FileMap {
397396
let mut parse_session = ParseSess::new();
398397
let krate = parse::parse_crate_from_file(file, Vec::new(), &parse_session);
399398

400399
// Suppress error output after parsing.
401400
let emitter = Box::new(EmitterWriter::new(Box::new(Vec::new()), None));
402401
parse_session.span_diagnostic.handler = Handler::with_emitter(false, emitter);
403402

404-
let mut file_map = fmt_ast(&krate, &parse_session, file, config, mode);
403+
let mut file_map = fmt_ast(&krate, &parse_session, file, config);
405404

406405
// For some reason, the codemap does not include terminating
407406
// newlines so we must add one on for each file. This is sad.
@@ -410,39 +409,25 @@ pub fn format(file: &Path, config: &Config, mode: WriteMode) -> FileMap {
410409
file_map
411410
}
412411

413-
// Make sure that we are using the correct WriteMode,
414-
// preferring what is passed as an argument
415-
fn check_write_mode(arg: WriteMode, config: WriteMode) -> WriteMode {
416-
match (arg, config) {
417-
(WriteMode::Default, WriteMode::Default) => WriteMode::Replace,
418-
(WriteMode::Default, mode) => mode,
419-
(mode, _) => mode,
420-
}
421-
}
422-
423-
// write_mode determines what happens to the result of running rustfmt, see
424-
// WriteMode.
425-
pub fn run(file: &Path, write_mode: WriteMode, config: &Config) {
426-
let mode = check_write_mode(write_mode, config.write_mode);
427-
let mut result = format(file, config, mode);
412+
pub fn run(file: &Path, config: &Config) {
413+
let mut result = format(file, config);
428414

429415
print!("{}", fmt_lines(&mut result, config));
430416
let out = stdout();
431-
let write_result = filemap::write_all_files(&result, out, mode, config);
417+
let write_result = filemap::write_all_files(&result, out, config);
432418

433419
if let Err(msg) = write_result {
434420
println!("Error writing files: {}", msg);
435421
}
436422
}
437423

438424
// Similar to run, but takes an input String instead of a file to format
439-
pub fn run_from_stdin(input: String, write_mode: WriteMode, config: &Config) {
440-
let mode = check_write_mode(write_mode, config.write_mode);
441-
let mut result = format_string(input, config, mode);
425+
pub fn run_from_stdin(input: String, config: &Config) {
426+
let mut result = format_string(input, config);
442427
fmt_lines(&mut result, config);
443428

444429
let mut out = stdout();
445-
let write_result = filemap::write_file(&result["stdin"], "stdin", &mut out, mode, config);
430+
let write_result = filemap::write_file(&result["stdin"], "stdin", &mut out, config);
446431

447432
if let Err(msg) = write_result {
448433
panic!("Error writing to stdout: {}", msg);

src/missed_spans.rs

+3-8
Original file line numberDiff line numberDiff line change
@@ -103,14 +103,9 @@ impl<'a> FmtVisitor<'a> {
103103
.collect()
104104
}
105105

106-
let replaced = match self.write_mode {
107-
Some(mode) => {
108-
match mode {
109-
WriteMode::Coverage => replace_chars(old_snippet),
110-
_ => old_snippet.to_owned(),
111-
}
112-
}
113-
None => old_snippet.to_owned(),
106+
let replaced = match self.config.write_mode {
107+
WriteMode::Coverage => replace_chars(old_snippet),
108+
_ => old_snippet.to_owned(),
114109
};
115110
let snippet = &*replaced;
116111

src/visitor.rs

+2-7
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use strings::string_buffer::StringBuffer;
1717

1818
use Indent;
1919
use utils;
20-
use config::{Config, WriteMode};
20+
use config::Config;
2121
use rewrite::{Rewrite, RewriteContext};
2222
use comment::rewrite_comment;
2323
use macros::rewrite_macro;
@@ -31,7 +31,6 @@ pub struct FmtVisitor<'a> {
3131
// FIXME: use an RAII util or closure for indenting
3232
pub block_indent: Indent,
3333
pub config: &'a Config,
34-
pub write_mode: Option<WriteMode>,
3534
}
3635

3736
impl<'a> FmtVisitor<'a> {
@@ -380,10 +379,7 @@ impl<'a> FmtVisitor<'a> {
380379
self.last_pos = span.hi;
381380
}
382381

383-
pub fn from_codemap(parse_session: &'a ParseSess,
384-
config: &'a Config,
385-
mode: Option<WriteMode>)
386-
-> FmtVisitor<'a> {
382+
pub fn from_codemap(parse_session: &'a ParseSess, config: &'a Config) -> FmtVisitor<'a> {
387383
FmtVisitor {
388384
parse_session: parse_session,
389385
codemap: parse_session.codemap(),
@@ -394,7 +390,6 @@ impl<'a> FmtVisitor<'a> {
394390
alignment: 0,
395391
},
396392
config: config,
397-
write_mode: mode,
398393
}
399394
}
400395

0 commit comments

Comments
 (0)