1 use std::collections::{HashMap, HashSet};
3 use std::io::{BufRead, BufReader, Write};
4 use std::iter::Enumerate;
5 use std::path::{Path, PathBuf};
7 use super::{print_mismatches, write_message, DIFF_CONTEXT_SIZE};
8 use crate::config::{Config, EmitMode, Verbosity};
9 use crate::rustfmt_diff::{make_diff, Mismatch};
10 use crate::{Input, Session};
12 const CONFIGURATIONS_FILE_NAME: &str = "Configurations.md";
14 // This enum is used to represent one of three text features in Configurations.md: a block of code
15 // with its starting line number, the name of a rustfmt configuration option, or the value of a
16 // rustfmt configuration option.
17 enum ConfigurationSection {
18 CodeBlock((String, u32)), // (String: block of code, u32: line number of code block start)
23 impl ConfigurationSection {
24 fn get_section<I: Iterator<Item = String>>(
25 file: &mut Enumerate<I>,
26 ) -> Option<ConfigurationSection> {
28 static ref CONFIG_NAME_REGEX: regex::Regex =
29 regex::Regex::new(r"^## `([^`]+)`").expect("failed creating configuration pattern");
30 static ref CONFIG_VALUE_REGEX: regex::Regex =
31 regex::Regex::new(r#"^#### `"?([^`"]+)"?`"#)
32 .expect("failed creating configuration value pattern");
38 if line.starts_with("```rust") {
39 // Get the lines of the code block.
40 let lines: Vec<String> = file
42 .take_while(|l| !l.starts_with("```"))
44 let block = format!("{}\n", lines.join("\n"));
46 // +1 to translate to one-based indexing
47 // +1 to get to first line of code (line after "```")
48 let start_line = (i + 2) as u32;
50 return Some(ConfigurationSection::CodeBlock((block, start_line)));
51 } else if let Some(c) = CONFIG_NAME_REGEX.captures(&line) {
52 return Some(ConfigurationSection::ConfigName(String::from(&c[1])));
53 } else if let Some(c) = CONFIG_VALUE_REGEX.captures(&line) {
54 return Some(ConfigurationSection::ConfigValue(String::from(&c[1])));
57 None => return None, // reached the end of the file
63 // This struct stores the information about code blocks in the configurations
64 // file, formats the code blocks, and prints formatting errors.
65 struct ConfigCodeBlock {
66 config_name: Option<String>,
67 config_value: Option<String>,
68 code_block: Option<String>,
69 code_block_start: Option<u32>,
72 impl ConfigCodeBlock {
73 fn new() -> ConfigCodeBlock {
78 code_block_start: None,
82 fn set_config_name(&mut self, name: Option<String>) {
83 self.config_name = name;
84 self.config_value = None;
87 fn set_config_value(&mut self, value: Option<String>) {
88 self.config_value = value;
91 fn set_code_block(&mut self, code_block: String, code_block_start: u32) {
92 self.code_block = Some(code_block);
93 self.code_block_start = Some(code_block_start);
96 fn get_block_config(&self) -> Config {
97 let mut config = Config::default();
98 config.set().verbose(Verbosity::Quiet);
99 if self.config_name.is_some() && self.config_value.is_some() {
100 config.override_value(
101 self.config_name.as_ref().unwrap(),
102 self.config_value.as_ref().unwrap(),
108 fn code_block_valid(&self) -> bool {
109 // We never expect to not have a code block.
110 assert!(self.code_block.is_some() && self.code_block_start.is_some());
112 // See if code block begins with #![rustfmt::skip].
113 let fmt_skip = self.fmt_skip();
115 if self.config_name.is_none() && !fmt_skip {
116 write_message(&format!(
117 "No configuration name for {}:{}",
118 CONFIGURATIONS_FILE_NAME,
119 self.code_block_start.unwrap()
123 if self.config_value.is_none() && !fmt_skip {
124 write_message(&format!(
125 "No configuration value for {}:{}",
126 CONFIGURATIONS_FILE_NAME,
127 self.code_block_start.unwrap()
134 /// True if the code block starts with #![rustfmt::skip]
135 fn fmt_skip(&self) -> bool {
142 == "#![rustfmt::skip]"
145 fn has_parsing_errors<T: Write>(&self, session: &Session<'_, T>) -> bool {
146 if session.has_parsing_errors() {
147 write_message(&format!(
148 "\u{261d}\u{1f3fd} Cannot format {}:{}",
149 CONFIGURATIONS_FILE_NAME,
150 self.code_block_start.unwrap()
158 fn print_diff(&self, compare: Vec<Mismatch>) {
159 let mut mismatches = HashMap::new();
160 mismatches.insert(PathBuf::from(CONFIGURATIONS_FILE_NAME), compare);
161 print_mismatches(mismatches, |line_num| {
163 "\nMismatch at {}:{}:",
164 CONFIGURATIONS_FILE_NAME,
165 line_num + self.code_block_start.unwrap() - 1
170 fn formatted_has_diff(&self, text: &str) -> bool {
171 let compare = make_diff(self.code_block.as_ref().unwrap(), text, DIFF_CONTEXT_SIZE);
172 if !compare.is_empty() {
173 self.print_diff(compare);
180 // Return a bool indicating if formatting this code block is an idempotent
181 // operation. This function also triggers printing any formatting failure
183 fn formatted_is_idempotent(&self) -> bool {
184 // Verify that we have all of the expected information.
185 if !self.code_block_valid() {
189 let input = Input::Text(self.code_block.as_ref().unwrap().to_owned());
190 let mut config = self.get_block_config();
191 config.set().emit_mode(EmitMode::Stdout);
192 let mut buf: Vec<u8> = vec![];
195 let mut session = Session::new(config, Some(&mut buf));
196 session.format(input).unwrap();
197 if self.has_parsing_errors(&session) {
202 !self.formatted_has_diff(&String::from_utf8(buf).unwrap())
205 // Extract a code block from the iterator. Behavior:
206 // - Rust code blocks are identifed by lines beginning with "```rust".
207 // - One explicit configuration setting is supported per code block.
208 // - Rust code blocks with no configuration setting are illegal and cause an
209 // assertion failure, unless the snippet begins with #![rustfmt::skip].
210 // - Configuration names in Configurations.md must be in the form of
212 // - Configuration values in Configurations.md must be in the form of
214 fn extract<I: Iterator<Item = String>>(
215 file: &mut Enumerate<I>,
216 prev: Option<&ConfigCodeBlock>,
217 hash_set: &mut HashSet<String>,
218 ) -> Option<ConfigCodeBlock> {
219 let mut code_block = ConfigCodeBlock::new();
220 code_block.config_name = prev.and_then(|cb| cb.config_name.clone());
223 match ConfigurationSection::get_section(file) {
224 Some(ConfigurationSection::CodeBlock((block, start_line))) => {
225 code_block.set_code_block(block, start_line);
228 Some(ConfigurationSection::ConfigName(name)) => {
230 Config::is_valid_name(&name),
231 "an unknown configuration option was found: {}",
235 hash_set.remove(&name),
236 "multiple configuration guides found for option {}",
239 code_block.set_config_name(Some(name));
241 Some(ConfigurationSection::ConfigValue(value)) => {
242 code_block.set_config_value(Some(value));
244 None => return None, // end of file was reached
253 fn configuration_snippet_tests() {
255 let blocks = get_code_blocks();
256 let failures = blocks
258 .filter(|block| !block.fmt_skip())
259 .map(ConfigCodeBlock::formatted_is_idempotent)
260 .fold(0, |acc, r| acc + (!r as u32));
263 println!("Ran {} configurations tests.", blocks.len());
264 assert_eq!(failures, 0, "{} configurations tests failed", failures);
267 // Read Configurations.md and build a `Vec` of `ConfigCodeBlock` structs with one
268 // entry for each Rust code block found.
269 fn get_code_blocks() -> Vec<ConfigCodeBlock> {
270 let mut file_iter = BufReader::new(
271 fs::File::open(Path::new(CONFIGURATIONS_FILE_NAME))
272 .unwrap_or_else(|_| panic!("couldn't read file {}", CONFIGURATIONS_FILE_NAME)),
277 let mut code_blocks: Vec<ConfigCodeBlock> = Vec::new();
278 let mut hash_set = Config::hash_set();
280 while let Some(cb) = ConfigCodeBlock::extract(&mut file_iter, code_blocks.last(), &mut hash_set)
282 code_blocks.push(cb);
285 for name in hash_set {
286 if !Config::is_hidden_option(&name) {
287 panic!("{} does not have a configuration guide", name);
295 fn check_unstable_option_tracking_issue_numbers() {
296 // Ensure that tracking issue links point to the correct issue number
298 regex::Regex::new(r"\(tracking issue: \[#(?P<number>\d+)\]\((?P<link>\S+)\)\)")
299 .expect("failed creating configuration pattern");
301 let lines = BufReader::new(
302 fs::File::open(Path::new(CONFIGURATIONS_FILE_NAME))
303 .unwrap_or_else(|_| panic!("couldn't read file {}", CONFIGURATIONS_FILE_NAME)),
309 for (idx, line) in lines {
310 if let Some(capture) = tracking_issue.captures(&line) {
311 let number = capture.name("number").unwrap().as_str();
312 let link = capture.name("link").unwrap().as_str();
314 link.ends_with(number),
315 "{} on line {} does not point to issue #{}",