Skip to content

Commit e44a71c

Browse files
authored
Refactor for 2.0 (#4168)
2 parents d885995 + d7e660f commit e44a71c

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

63 files changed

+1719
-1824
lines changed

Configurations.md

Lines changed: 1 addition & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -311,14 +311,6 @@ By default this option is set as a percentage of [`max_width`](#max_width) provi
311311

312312
See also [`max_width`](#max_width) and [`width_heuristics`](#width_heuristics)
313313

314-
## `color`
315-
316-
Whether to use colored output or not.
317-
318-
- **Default value**: `"Auto"`
319-
- **Possible values**: "Auto", "Always", "Never"
320-
- **Stable**: No (tracking issue: [#3385](https://github.com/rust-lang/rustfmt/issues/3385))
321-
322314
## `combine_control_expr`
323315

324316
Combine control expressions with function calls.
@@ -2629,17 +2621,4 @@ Break comments to fit on the line
26292621
// magna aliqua. Ut enim ad minim veniam, quis nostrud
26302622
// exercitation ullamco laboris nisi ut aliquip ex ea
26312623
// commodo consequat.
2632-
```
2633-
2634-
# Internal Options
2635-
2636-
## `emit_mode`
2637-
2638-
Internal option
2639-
2640-
## `print_misformatted_file_names`
2641-
2642-
Internal option, use `-l` or `--files-with-diff`
2643-
2644-
## `recursive`
2645-
Internal option, use `-r` or `--recursive`
2624+
```

rustfmt-core/rustfmt-bin/src/bin/main.rs

Lines changed: 74 additions & 128 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,14 @@ use structopt::StructOpt;
1414
use thiserror::Error;
1515

1616
use rustfmt_lib::{
17-
load_config, CliOptions, Config, Edition, EmitMode, FileLines, FileName,
18-
FormatReportFormatterBuilder, Input, Session, Verbosity,
17+
emitter::{emit_format_report, EmitMode, EmitterConfig, Verbosity},
18+
format_inputs, load_config, CliOptions, Config, Edition, FileLines, FileName,
19+
FormatReportFormatterBuilder, Input, OperationSetting,
1920
};
2021

2122
fn main() {
2223
env_logger::init();
24+
2325
let opt: Opt = Opt::from_args();
2426

2527
let exit_code = match execute(opt) {
@@ -127,6 +129,32 @@ struct Opt {
127129
files: Vec<PathBuf>,
128130
}
129131

132+
impl Opt {
133+
fn verbosity(&self) -> Verbosity {
134+
if self.verbose {
135+
Verbosity::Verbose
136+
} else if self.quiet {
137+
Verbosity::Quiet
138+
} else {
139+
Verbosity::Normal
140+
}
141+
}
142+
143+
fn emitter_config(&self, default_emit_mode: EmitMode) -> EmitterConfig {
144+
let emit_mode = if self.check {
145+
EmitMode::Diff
146+
} else {
147+
self.emit.map_or(default_emit_mode, Emit::to_emit_mode)
148+
};
149+
EmitterConfig {
150+
emit_mode,
151+
verbosity: self.verbosity(),
152+
print_filename: self.files_with_diff,
153+
..EmitterConfig::default()
154+
}
155+
}
156+
}
157+
130158
#[derive(Debug, Clone)]
131159
struct InlineConfig(HashMap<String, String>, bool /* is help */);
132160

@@ -307,29 +335,13 @@ impl From<IoError> for OperationError {
307335

308336
impl CliOptions for Opt {
309337
fn apply_to(&self, config: &mut Config) {
310-
if self.verbose {
311-
config.set().verbose(Verbosity::Verbose);
312-
} else if self.quiet {
313-
config.set().verbose(Verbosity::Quiet);
314-
}
315338
config.set().file_lines(self.file_lines.clone());
316-
if self.recursive {
317-
config.set().recursive(true);
318-
}
319339
if self.error_on_unformatted {
320340
config.set().error_on_unformatted(true);
321341
}
322342
if let Some(ref edition) = self.edition {
323343
config.set().edition((*edition).clone());
324344
}
325-
if self.check {
326-
config.set().emit_mode(EmitMode::Diff);
327-
} else if let Some(emit) = self.emit {
328-
config.set().emit_mode(emit.to_emit_mode());
329-
}
330-
if self.files_with_diff {
331-
config.set().print_misformatted_file_names(true);
332-
}
333345
if let Some(ref inline_configs) = self.inline_config {
334346
for inline_config in inline_configs {
335347
for (k, v) in &inline_config.0 {
@@ -392,17 +404,8 @@ fn format_string(input: String, opt: Opt) -> Result<i32> {
392404
// try to read config from local directory
393405
let (mut config, _) = load_config(Some(Path::new(".")), Some(&opt))?;
394406

395-
if opt.check {
396-
config.set().emit_mode(EmitMode::Diff);
397-
} else {
398-
config
399-
.set()
400-
.emit_mode(opt.emit.map_or(EmitMode::Stdout, Emit::to_emit_mode));
401-
}
402-
config.set().verbose(Verbosity::Quiet);
403-
404407
// parse file_lines
405-
config.set().file_lines(opt.file_lines);
408+
config.set().file_lines(opt.file_lines.clone());
406409
for f in config.file_lines().files() {
407410
match *f {
408411
FileName::Stdin => {}
@@ -411,15 +414,13 @@ fn format_string(input: String, opt: Opt) -> Result<i32> {
411414
}
412415

413416
let out = &mut stdout();
414-
let mut session = Session::new(config, Some(out));
415-
format_and_emit_report(&mut session, Input::Text(input));
416-
417-
let exit_code = if session.has_operational_errors() || session.has_parsing_errors() {
418-
1
419-
} else {
420-
0
417+
let setting = OperationSetting {
418+
recursive: opt.recursive,
419+
verbosity: Verbosity::Quiet,
421420
};
422-
Ok(exit_code)
421+
let report = rustfmt_lib::format(Input::Text(input), &config, setting)?;
422+
let has_diff = emit_format_report(report, out, opt.emitter_config(EmitMode::Stdout))?;
423+
Ok(if opt.check && has_diff { 1 } else { 0 })
423424
}
424425

425426
enum FileConfig {
@@ -482,80 +483,50 @@ fn format(opt: Opt) -> Result<i32> {
482483
return Err(format_err!("Error: `{}` is a directory", dir.display()));
483484
}
484485

485-
let (config, config_path) = load_config(None, Some(&opt))?;
486+
let (default_config, config_path) = load_config(None, Some(&opt))?;
486487

487-
if config.verbose() == Verbosity::Verbose {
488+
if opt.verbose {
488489
if let Some(path) = config_path.as_ref() {
489490
println!("Using rustfmt config file {}", path.display());
490491
}
491492
}
492493

493-
let out = &mut stdout();
494-
let mut session = Session::new(config, Some(out));
495-
496-
for pair in FileConfigPairIter::new(&opt, config_path.is_some()) {
497-
let file = pair.file;
498-
499-
if let FileConfig::Local(local_config, config_path) = pair.config {
500-
if let Some(path) = config_path {
501-
if local_config.verbose() == Verbosity::Verbose {
502-
println!(
503-
"Using rustfmt config file {} for {}",
504-
path.display(),
505-
file.display()
506-
);
507-
}
508-
}
509-
510-
session.override_config(local_config, |sess| {
511-
format_and_emit_report(sess, Input::File(file.to_path_buf()))
512-
});
513-
} else {
514-
format_and_emit_report(&mut session, Input::File(file.to_path_buf()));
515-
}
516-
}
517-
518-
let exit_code = if session.has_operational_errors()
519-
|| session.has_parsing_errors()
520-
|| ((session.has_diff() || session.has_check_errors()) && opt.check)
521-
{
522-
1
523-
} else {
524-
0
494+
let setting = OperationSetting {
495+
recursive: opt.recursive,
496+
verbosity: opt.verbosity(),
525497
};
526-
Ok(exit_code)
527-
}
528-
529-
fn format_and_emit_report<T: Write>(session: &mut Session<'_, T>, input: Input) {
530-
match session.format(input) {
531-
Ok(report) => {
532-
if report.has_warnings() {
533-
eprintln!(
534-
"{}",
535-
FormatReportFormatterBuilder::new(&report)
536-
.enable_colors(should_print_with_colors(session))
537-
.build()
538-
);
539-
}
540-
}
541-
Err(msg) => {
542-
eprintln!("Error writing files: {}", msg);
543-
session.add_operational_error();
544-
}
545-
}
546-
}
547498

548-
fn should_print_with_colors<T: Write>(session: &mut Session<'_, T>) -> bool {
549-
match term::stderr() {
550-
Some(ref t)
551-
if session.config.color().use_colored_tty()
552-
&& t.supports_color()
553-
&& t.supports_attr(term::Attr::Bold) =>
554-
{
555-
true
556-
}
557-
_ => false,
558-
}
499+
let inputs = FileConfigPairIter::new(&opt, config_path.is_some()).collect::<Vec<_>>();
500+
let format_report = format_inputs(
501+
inputs.iter().map(|p| {
502+
(
503+
Input::File(p.file.to_path_buf()),
504+
if let FileConfig::Local(ref config, _) = p.config {
505+
config
506+
} else {
507+
&default_config
508+
},
509+
)
510+
}),
511+
setting,
512+
)?;
513+
514+
if format_report.has_errors() {
515+
eprintln!(
516+
"{}",
517+
FormatReportFormatterBuilder::new(&format_report)
518+
.enable_colors(true)
519+
.build()
520+
);
521+
}
522+
523+
let has_diff = emit_format_report(
524+
format_report,
525+
&mut stdout(),
526+
opt.emitter_config(EmitMode::Files),
527+
)?;
528+
529+
Ok(if opt.check && has_diff { 1 } else { 0 })
559530
}
560531

561532
#[cfg(test)]
@@ -567,31 +538,6 @@ mod test {
567538
let _ = env_logger::builder().is_test(true).try_init();
568539
}
569540

570-
#[test]
571-
fn format_lines_errors_are_reported() {
572-
init_log();
573-
let long_identifier = String::from_utf8(vec![b'a'; 239]).unwrap();
574-
let input = Input::Text(format!("fn {}() {{}}", long_identifier));
575-
let mut config = Config::default();
576-
config.set().error_on_line_overflow(true);
577-
let mut session = Session::<io::Stdout>::new(config, None);
578-
session.format(input).unwrap();
579-
assert!(session.has_formatting_errors());
580-
}
581-
582-
#[test]
583-
fn format_lines_errors_are_reported_with_tabs() {
584-
init_log();
585-
let long_identifier = String::from_utf8(vec![b'a'; 97]).unwrap();
586-
let input = Input::Text(format!("fn a() {{\n\t{}\n}}", long_identifier));
587-
let mut config = Config::default();
588-
config.set().error_on_line_overflow(true);
589-
config.set().hard_tabs(true);
590-
let mut session = Session::<io::Stdout>::new(config, None);
591-
session.format(input).unwrap();
592-
assert!(session.has_formatting_errors());
593-
}
594-
595541
struct TempFile {
596542
path: PathBuf,
597543
}
@@ -704,7 +650,7 @@ mod test {
704650
let output = child
705651
.wait_with_output()
706652
.expect("Failed to wait on rustfmt child");
707-
assert!(output.status.success());
653+
assert!(!output.status.success());
708654
assert_eq!(std::str::from_utf8(&output.stdout).unwrap(), "stdin\n");
709655
}
710656

rustfmt-core/rustfmt-bin/src/git-rustfmt/main.rs

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,10 @@ use std::process::Command;
77

88
use structopt::StructOpt;
99

10-
use rustfmt_lib::{load_config, CliOptions, FormatReportFormatterBuilder, Input, Session};
10+
use rustfmt_lib::{
11+
emitter::{emit_format_report, EmitterConfig},
12+
format, load_config, CliOptions, FormatReportFormatterBuilder, Input, OperationSetting,
13+
};
1114

1215
fn prune_files(files: Vec<&str>) -> Vec<&str> {
1316
let prefixes: Vec<_> = files
@@ -56,20 +59,27 @@ fn get_files(input: &str) -> Vec<&str> {
5659
fn fmt_files(files: &[&str]) -> i32 {
5760
let (config, _) =
5861
load_config::<NullOptions>(Some(Path::new(".")), None).expect("couldn't load config");
62+
let setting = OperationSetting::default();
5963

60-
let mut exit_code = 0;
6164
let mut out = stdout();
62-
let mut session = Session::new(config, Some(&mut out));
6365
for file in files {
64-
let report = session.format(Input::File(PathBuf::from(file))).unwrap();
65-
if report.has_warnings() {
66+
let report = match format(Input::File(PathBuf::from(file)), &config, setting) {
67+
Ok(report) => report,
68+
Err(e) => {
69+
eprintln!("{}", e);
70+
return 1;
71+
}
72+
};
73+
if report.has_errors() {
6674
eprintln!("{}", FormatReportFormatterBuilder::new(&report).build());
6775
}
68-
if !session.has_no_errors() {
69-
exit_code = 1;
76+
if let Err(e) = emit_format_report(report, &mut out, EmitterConfig::default()) {
77+
eprintln!("{}", e);
78+
return 1;
7079
}
7180
}
72-
exit_code
81+
82+
0
7383
}
7484

7585
struct NullOptions;

rustfmt-core/rustfmt-bin/tests/rustfmt/main.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -77,9 +77,9 @@ fn inline_config() {
7777
"--print-config",
7878
"current",
7979
".",
80-
"--config=color=Never,edition=2018"
80+
"--config=max_width=50,edition=2018"
8181
],
82-
contains("color = \"Never\"") && contains("edition = \"2018\"")
82+
contains("max_width = 50") && contains("edition = \"2018\"")
8383
);
8484

8585
// multiple overriding invocations
@@ -89,11 +89,11 @@ fn inline_config() {
8989
"current",
9090
".",
9191
"--config",
92-
"color=never,edition=2018",
92+
"max_width=80,edition=2018",
9393
"--config",
94-
"color=always,format_strings=true"
94+
"max_width=60,format_strings=true"
9595
],
96-
contains("color = \"Always\"")
96+
contains("max_width = 60")
9797
&& contains("edition = \"2018\"")
9898
&& contains("format_strings = true")
9999
);

0 commit comments

Comments
 (0)