Skip to content

Commit 95d6b64

Browse files
committed
Replace WriteMode with EmitMode and backup bool
1 parent 843c126 commit 95d6b64

File tree

11 files changed

+87
-81
lines changed

11 files changed

+87
-81
lines changed

Configurations.md

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1885,13 +1885,6 @@ fn main() {
18851885

18861886
See also: [`match_block_trailing_comma`](#match_block_trailing_comma).
18871887

1888-
## `write_mode`
1889-
1890-
What Write Mode to use when none is supplied: Replace, Overwrite, Display, Diff, Coverage
1891-
1892-
- **Default value**: `"Overwrite"`
1893-
- **Possible values**: `"Checkstyle"`, `"Coverage"`, `"Diff"`, `"Display"`, `"Overwrite"`, `"Plain"`, `"Replace"`
1894-
- **Stable**: No
18951888

18961889
## `blank_lines_upper_bound`
18971890

@@ -2071,3 +2064,11 @@ ignore [
20712064
"examples",
20722065
]
20732066
```
2067+
2068+
## `emit_mode`
2069+
2070+
Internal option
2071+
2072+
## `make_backup`
2073+
2074+
Internal option, use `--backup`

src/bin/main.rs

Lines changed: 43 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -28,18 +28,18 @@ use getopts::{Matches, Options};
2828

2929
use rustfmt::{
3030
emit_post_matter, emit_pre_matter, format_and_emit_report, load_config, CliOptions, Color,
31-
Config, ErrorKind, FileLines, FileName, Input, Summary, Verbosity, WriteMode,
31+
Config, EmitMode, ErrorKind, FileLines, FileName, Input, Summary, Verbosity,
3232
};
3333

3434
fn main() {
3535
env_logger::init();
3636
let opts = make_opts();
3737

3838
let exit_code = match execute(&opts) {
39-
Ok((write_mode, summary)) => {
39+
Ok((exit_mode, summary)) => {
4040
if summary.has_operational_errors() || summary.has_parsing_errors()
4141
|| ((summary.has_diff || summary.has_check_errors())
42-
&& write_mode == WriteMode::Check)
42+
&& exit_mode == ExitCodeMode::Check)
4343
{
4444
1
4545
} else {
@@ -172,26 +172,26 @@ fn is_nightly() -> bool {
172172
.unwrap_or(false)
173173
}
174174

175-
fn execute(opts: &Options) -> Result<(WriteMode, Summary), failure::Error> {
175+
fn execute(opts: &Options) -> Result<(ExitCodeMode, Summary), failure::Error> {
176176
let matches = opts.parse(env::args().skip(1))?;
177177
let options = GetOptsOptions::from_matches(&matches)?;
178178

179179
match determine_operation(&matches)? {
180180
Operation::Help(HelpOp::None) => {
181181
print_usage_to_stdout(opts, "");
182-
Ok((WriteMode::None, Summary::default()))
182+
Ok((ExitCodeMode::Normal, Summary::default()))
183183
}
184184
Operation::Help(HelpOp::Config) => {
185185
Config::print_docs(&mut stdout(), options.unstable_features);
186-
Ok((WriteMode::None, Summary::default()))
186+
Ok((ExitCodeMode::Normal, Summary::default()))
187187
}
188188
Operation::Help(HelpOp::FileLines) => {
189189
print_help_file_lines();
190-
Ok((WriteMode::None, Summary::default()))
190+
Ok((ExitCodeMode::Normal, Summary::default()))
191191
}
192192
Operation::Version => {
193193
print_version();
194-
Ok((WriteMode::None, Summary::default()))
194+
Ok((ExitCodeMode::Normal, Summary::default()))
195195
}
196196
Operation::ConfigOutputDefault { path } => {
197197
let toml = Config::default().all_options().to_toml().map_err(err_msg)?;
@@ -201,14 +201,14 @@ fn execute(opts: &Options) -> Result<(WriteMode, Summary), failure::Error> {
201201
} else {
202202
io::stdout().write_all(toml.as_bytes())?;
203203
}
204-
Ok((WriteMode::None, Summary::default()))
204+
Ok((ExitCodeMode::Normal, Summary::default()))
205205
}
206206
Operation::Stdin { input } => {
207207
// try to read config from local directory
208208
let (mut config, _) = load_config(Some(Path::new(".")), Some(options.clone()))?;
209209

210-
// write_mode is always Display for Stdin.
211-
config.set().write_mode(WriteMode::Display);
210+
// emit mode is always Stdout for Stdin.
211+
config.set().emit_mode(EmitMode::Stdout);
212212
config.set().verbose(Verbosity::Quiet);
213213

214214
// parse file_lines
@@ -228,7 +228,7 @@ fn execute(opts: &Options) -> Result<(WriteMode, Summary), failure::Error> {
228228
}
229229
emit_post_matter(&config)?;
230230

231-
Ok((WriteMode::Display, error_summary))
231+
Ok((ExitCodeMode::Normal, error_summary))
232232
}
233233
Operation::Format {
234234
files,
@@ -241,7 +241,7 @@ fn format(
241241
files: Vec<PathBuf>,
242242
minimal_config_path: Option<String>,
243243
options: GetOptsOptions,
244-
) -> Result<(WriteMode, Summary), failure::Error> {
244+
) -> Result<(ExitCodeMode, Summary), failure::Error> {
245245
options.verify_file_lines(&files);
246246
let (config, config_path) = load_config(None, Some(options.clone()))?;
247247

@@ -299,7 +299,12 @@ fn format(
299299
file.write_all(toml.as_bytes())?;
300300
}
301301

302-
Ok((config.write_mode(), error_summary))
302+
let exit_mode = if options.check {
303+
ExitCodeMode::Check
304+
} else {
305+
ExitCodeMode::Normal
306+
};
307+
Ok((exit_mode, error_summary))
303308
}
304309

305310
fn print_usage_to_stdout(opts: &Options, reason: &str) {
@@ -406,12 +411,13 @@ fn determine_operation(matches: &Matches) -> Result<Operation, ErrorKind> {
406411
})
407412
}
408413

409-
const STABLE_WRITE_MODES: [WriteMode; 4] = [
410-
WriteMode::Replace,
411-
WriteMode::Overwrite,
412-
WriteMode::Display,
413-
WriteMode::Check,
414-
];
414+
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
415+
enum ExitCodeMode {
416+
Normal,
417+
Check,
418+
}
419+
420+
const STABLE_EMIT_MODES: [EmitMode; 3] = [EmitMode::Files, EmitMode::Stdout, EmitMode::Diff];
415421

416422
/// Parsed command line options.
417423
#[derive(Clone, Debug, Default)]
@@ -420,7 +426,8 @@ struct GetOptsOptions {
420426
quiet: bool,
421427
verbose: bool,
422428
config_path: Option<PathBuf>,
423-
write_mode: WriteMode,
429+
emit_mode: EmitMode,
430+
backup: bool,
424431
check: bool,
425432
color: Option<Color>,
426433
file_lines: FileLines, // Default is all lines in all files.
@@ -463,19 +470,19 @@ impl GetOptsOptions {
463470
if options.check {
464471
return Err(format_err!("Invalid to use `--emit` and `--check`"));
465472
}
466-
if let Ok(write_mode) = write_mode_from_emit_str(emit_str) {
467-
options.write_mode = write_mode;
473+
if let Ok(emit_mode) = emit_mode_from_emit_str(emit_str) {
474+
options.emit_mode = emit_mode;
468475
} else {
469476
return Err(format_err!("Invalid value for `--emit`"));
470477
}
471478
}
472479

473-
if options.write_mode == WriteMode::Overwrite && matches.opt_present("backup") {
474-
options.write_mode = WriteMode::Replace;
480+
if matches.opt_present("backup") {
481+
options.backup = true;
475482
}
476483

477484
if !rust_nightly {
478-
if !STABLE_WRITE_MODES.contains(&options.write_mode) {
485+
if !STABLE_EMIT_MODES.contains(&options.emit_mode) {
479486
return Err(format_err!(
480487
"Invalid value for `--emit` - using an unstable \
481488
value without `--unstable-features`",
@@ -524,9 +531,12 @@ impl CliOptions for GetOptsOptions {
524531
config.set().error_on_unformatted(error_on_unformatted);
525532
}
526533
if self.check {
527-
config.set().write_mode(WriteMode::Check);
534+
config.set().emit_mode(EmitMode::Diff);
528535
} else {
529-
config.set().write_mode(self.write_mode);
536+
config.set().emit_mode(self.emit_mode);
537+
}
538+
if self.backup {
539+
config.set().make_backup(true);
530540
}
531541
if let Some(color) = self.color {
532542
config.set().color(color);
@@ -538,12 +548,12 @@ impl CliOptions for GetOptsOptions {
538548
}
539549
}
540550

541-
fn write_mode_from_emit_str(emit_str: &str) -> Result<WriteMode, failure::Error> {
551+
fn emit_mode_from_emit_str(emit_str: &str) -> Result<EmitMode, failure::Error> {
542552
match emit_str {
543-
"files" => Ok(WriteMode::Overwrite),
544-
"stdout" => Ok(WriteMode::Display),
545-
"coverage" => Ok(WriteMode::Coverage),
546-
"checkstyle" => Ok(WriteMode::Checkstyle),
553+
"files" => Ok(EmitMode::Files),
554+
"stdout" => Ok(EmitMode::Stdout),
555+
"coverage" => Ok(EmitMode::Coverage),
556+
"checkstyle" => Ok(EmitMode::Checkstyle),
547557
_ => Err(format_err!("Invalid value for `--emit`")),
548558
}
549559
}

src/config/mod.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -114,9 +114,6 @@ create_config! {
114114
in tuple patterns";
115115

116116
// Control options (changes the operation of rustfmt, rather than the formatting)
117-
write_mode: WriteMode, WriteMode::Overwrite, false,
118-
"What Write Mode to use when none is supplied: \
119-
Replace, Overwrite, Display, Plain, Diff, Coverage, Check";
120117
color: Color, Color::Auto, false,
121118
"What Color option to use when none is supplied: Always, Never, Auto";
122119
required_version: String, env!("CARGO_PKG_VERSION").to_owned(), false,
@@ -144,6 +141,9 @@ create_config! {
144141
via the --file-lines option";
145142
width_heuristics: WidthHeuristics, WidthHeuristics::scaled(100), false,
146143
"'small' heuristic values";
144+
emit_mode: EmitMode, EmitMode::Files, false,
145+
"What emit Mode to use when none is supplied";
146+
make_backup: bool, false, false, "Backup changed files";
147147
}
148148

149149
pub fn load_config<O: CliOptions>(

src/config/options.rs

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -165,25 +165,21 @@ configuration_option_enum! { ReportTactic:
165165
Never,
166166
}
167167

168-
configuration_option_enum! { WriteMode:
169-
// Overwrites original file without backup.
170-
Overwrite,
171-
// Backs the original file up and overwrites the original.
172-
Replace,
168+
configuration_option_enum! { EmitMode:
169+
// Emits to files.
170+
Files,
173171
// Writes the output to stdout.
174-
Display,
172+
Stdout,
175173
// Displays how much of the input file was processed
176174
Coverage,
177175
// Unfancy stdout
178176
Checkstyle,
179177
// Output the changed lines (for internal value only)
180-
Modified,
178+
ModifiedLines,
181179
// Checks if a diff can be generated. If so, rustfmt outputs a diff and quits with exit code 1.
182180
// This option is designed to be run in CI where a non-zero exit signifies non-standard code
183181
// formatting.
184-
Check,
185-
// Rustfmt shouldn't output anything formatting-like (e.g., emit a help message).
186-
None,
182+
Diff,
187183
}
188184

189185
configuration_option_enum! { Color:
@@ -266,9 +262,9 @@ impl ::std::str::FromStr for WidthHeuristics {
266262
}
267263
}
268264

269-
impl Default for WriteMode {
270-
fn default() -> WriteMode {
271-
WriteMode::Overwrite
265+
impl Default for EmitMode {
266+
fn default() -> EmitMode {
267+
EmitMode::Files
272268
}
273269
}
274270

src/filemap.rs

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ use std::io::{self, BufWriter, Read, Write};
1515
use std::path::Path;
1616

1717
use checkstyle::output_checkstyle_file;
18-
use config::{Config, FileName, NewlineStyle, Verbosity, WriteMode};
18+
use config::{Config, EmitMode, FileName, NewlineStyle, Verbosity};
1919
use rustfmt_diff::{make_diff, output_modified, print_diff, Mismatch};
2020

2121
#[cfg(test)]
@@ -35,13 +35,13 @@ pub(crate) fn write_all_files<T>(
3535
where
3636
T: Write,
3737
{
38-
if config.write_mode() == WriteMode::Checkstyle {
38+
if config.emit_mode() == EmitMode::Checkstyle {
3939
::checkstyle::output_header(out)?;
4040
}
4141
for &(ref filename, ref text) in file_map {
4242
write_file(text, filename, out, config)?;
4343
}
44-
if config.write_mode() == WriteMode::Checkstyle {
44+
if config.emit_mode() == EmitMode::Checkstyle {
4545
::checkstyle::output_footer(out)?;
4646
}
4747

@@ -116,11 +116,11 @@ where
116116

117117
let filename_to_path = || match *filename {
118118
FileName::Real(ref path) => path,
119-
_ => panic!("cannot format `{}` with WriteMode::Replace", filename),
119+
_ => panic!("cannot format `{}` and emit to files", filename),
120120
};
121121

122-
match config.write_mode() {
123-
WriteMode::Replace => {
122+
match config.emit_mode() {
123+
EmitMode::Files if config.make_backup() => {
124124
let filename = filename_to_path();
125125
if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config) {
126126
if fmt != ori {
@@ -140,7 +140,7 @@ where
140140
}
141141
}
142142
}
143-
WriteMode::Overwrite => {
143+
EmitMode::Files => {
144144
// Write text directly over original file if there is a diff.
145145
let filename = filename_to_path();
146146
let (source, formatted) = source_and_formatted_text(text, filename, config)?;
@@ -149,13 +149,13 @@ where
149149
write_system_newlines(file, text, config)?;
150150
}
151151
}
152-
WriteMode::Display | WriteMode::Coverage => {
152+
EmitMode::Stdout | EmitMode::Coverage => {
153153
if config.verbose() != Verbosity::Quiet {
154154
println!("{}:\n", filename);
155155
}
156156
write_system_newlines(out, text, config)?;
157157
}
158-
WriteMode::Modified => {
158+
EmitMode::ModifiedLines => {
159159
let filename = filename_to_path();
160160
if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config) {
161161
let mismatch = make_diff(&ori, &fmt, 0);
@@ -164,12 +164,12 @@ where
164164
return Ok(has_diff);
165165
}
166166
}
167-
WriteMode::Checkstyle => {
167+
EmitMode::Checkstyle => {
168168
let filename = filename_to_path();
169169
let diff = create_diff(filename, text, config)?;
170170
output_checkstyle_file(out, filename, diff)?;
171171
}
172-
WriteMode::Check => {
172+
EmitMode::Diff => {
173173
let filename = filename_to_path();
174174
if let Ok((ori, fmt)) = source_and_formatted_text(text, filename, config) {
175175
let mismatch = make_diff(&ori, &fmt, 3);
@@ -182,7 +182,6 @@ where
182182
return Ok(has_diff);
183183
}
184184
}
185-
WriteMode::None => {}
186185
}
187186

188187
// when we are not in diff mode, don't indicate differing files

0 commit comments

Comments
 (0)