Skip to content

Commit dcef073

Browse files
committed
Refactor
1 parent d885995 commit dcef073

File tree

27 files changed

+871
-1010
lines changed

27 files changed

+871
-1010
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: 88 additions & 106 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+
load_config, write_all_files, CliOptions, Config, Edition, EmitMode, EmitterConfig, FileLines,
18+
FileName, FormatReport, FormatReportFormatterBuilder, Input, RustFormatterBuilder, Session,
19+
Verbosity,
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,20 @@ 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
421-
};
422-
Ok(exit_code)
417+
let mut session = RustFormatterBuilder::default()
418+
.recursive(opt.recursive)
419+
.verbosity(Verbosity::Quiet)
420+
.build();
421+
let mut format_report = FormatReport::new();
422+
// FIXME: Add error handling.
423+
format_and_emit_report(
424+
&mut session,
425+
Input::Text(input),
426+
&config,
427+
&mut format_report,
428+
);
429+
let has_diff = write_all_files(format_report, out, opt.emitter_config(EmitMode::Stdout))?;
430+
Ok(if opt.check && has_diff { 1 } else { 0 })
423431
}
424432

425433
enum FileConfig {
@@ -484,21 +492,24 @@ fn format(opt: Opt) -> Result<i32> {
484492

485493
let (config, config_path) = load_config(None, Some(&opt))?;
486494

487-
if config.verbose() == Verbosity::Verbose {
495+
if opt.verbose {
488496
if let Some(path) = config_path.as_ref() {
489497
println!("Using rustfmt config file {}", path.display());
490498
}
491499
}
492500

493-
let out = &mut stdout();
494-
let mut session = Session::new(config, Some(out));
501+
let mut session = RustFormatterBuilder::default()
502+
.recursive(opt.recursive)
503+
.verbosity(opt.verbosity())
504+
.build();
505+
let mut format_report = FormatReport::new();
495506

496507
for pair in FileConfigPairIter::new(&opt, config_path.is_some()) {
497508
let file = pair.file;
498509

499510
if let FileConfig::Local(local_config, config_path) = pair.config {
500511
if let Some(path) = config_path {
501-
if local_config.verbose() == Verbosity::Verbose {
512+
if opt.verbose {
502513
println!(
503514
"Using rustfmt config file {} for {}",
504515
path.display(),
@@ -507,54 +518,50 @@ fn format(opt: Opt) -> Result<i32> {
507518
}
508519
}
509520

510-
session.override_config(local_config, |sess| {
511-
format_and_emit_report(sess, Input::File(file.to_path_buf()))
512-
});
521+
format_and_emit_report(
522+
&mut session,
523+
Input::File(file.to_path_buf()),
524+
&local_config,
525+
&mut format_report,
526+
);
513527
} else {
514-
format_and_emit_report(&mut session, Input::File(file.to_path_buf()));
528+
format_and_emit_report(
529+
&mut session,
530+
Input::File(file.to_path_buf()),
531+
&config,
532+
&mut format_report,
533+
);
515534
}
516535
}
517536

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
525-
};
526-
Ok(exit_code)
537+
if format_report.has_errors() {
538+
eprintln!(
539+
"{}",
540+
FormatReportFormatterBuilder::new(&format_report)
541+
.enable_colors(true)
542+
.build()
543+
);
544+
}
545+
546+
let out = &mut stdout();
547+
let has_diff = write_all_files(format_report, out, opt.emitter_config(EmitMode::Files))?;
548+
549+
Ok(if opt.check && has_diff { 1 } else { 0 })
527550
}
528551

529-
fn format_and_emit_report<T: Write>(session: &mut Session<'_, T>, input: Input) {
530-
match session.format(input) {
552+
fn format_and_emit_report(
553+
session: &mut Session,
554+
input: Input,
555+
config: &Config,
556+
format_report: &mut FormatReport,
557+
) {
558+
match session.format(input, config) {
531559
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();
560+
format_report.merge(report);
544561
}
545-
}
546-
}
547-
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
562+
Err(err) => {
563+
eprintln!("{}", err);
556564
}
557-
_ => false,
558565
}
559566
}
560567

@@ -567,31 +574,6 @@ mod test {
567574
let _ = env_logger::builder().is_test(true).try_init();
568575
}
569576

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-
595577
struct TempFile {
596578
path: PathBuf,
597579
}
@@ -704,7 +686,7 @@ mod test {
704686
let output = child
705687
.wait_with_output()
706688
.expect("Failed to wait on rustfmt child");
707-
assert!(output.status.success());
689+
assert!(!output.status.success());
708690
assert_eq!(std::str::from_utf8(&output.stdout).unwrap(), "stdin\n");
709691
}
710692

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

Lines changed: 11 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+
load_config, write_all_files, CliOptions, EmitterConfig, FormatReportFormatterBuilder, Input,
12+
Session,
13+
};
1114

1215
fn prune_files(files: Vec<&str>) -> Vec<&str> {
1316
let prefixes: Vec<_> = files
@@ -57,19 +60,19 @@ fn fmt_files(files: &[&str]) -> i32 {
5760
let (config, _) =
5861
load_config::<NullOptions>(Some(Path::new(".")), None).expect("couldn't load config");
5962

60-
let mut exit_code = 0;
6163
let mut out = stdout();
62-
let mut session = Session::new(config, Some(&mut out));
64+
let mut session = Session::default();
6365
for file in files {
64-
let report = session.format(Input::File(PathBuf::from(file))).unwrap();
66+
let report = session
67+
.format(Input::File(PathBuf::from(file)), &config)
68+
.unwrap();
6569
if report.has_warnings() {
6670
eprintln!("{}", FormatReportFormatterBuilder::new(&report).build());
6771
}
68-
if !session.has_no_errors() {
69-
exit_code = 1;
70-
}
72+
write_all_files(report, &mut out, EmitterConfig::default()).unwrap();
7173
}
72-
exit_code
74+
75+
todo!("Fix error handling")
7376
}
7477

7578
struct NullOptions;

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

Lines changed: 4 additions & 4 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",
9494
"color=always,format_strings=true"
9595
],
96-
contains("color = \"Always\"")
96+
contains("max_width = 80")
9797
&& contains("edition = \"2018\"")
9898
&& contains("format_strings = true")
9999
);

0 commit comments

Comments
 (0)