7 io::{Error as IoError, ErrorKind},
9 process::{Command, Output, Stdio},
12 use itertools::Itertools;
14 pub use self::boilerplate_gen::generate_boilerplate;
16 pub type Result<T> = std::result::Result<T, Box<dyn Error>>;
18 pub const GRAMMAR: &str = "crates/ra_syntax/src/grammar.ron";
19 const GRAMMAR_DIR: &str = "crates/ra_parser/src/grammar";
20 const OK_INLINE_TESTS_DIR: &str = "crates/ra_syntax/test_data/parser/inline/ok";
21 const ERR_INLINE_TESTS_DIR: &str = "crates/ra_syntax/test_data/parser/inline/err";
23 pub const SYNTAX_KINDS: &str = "crates/ra_parser/src/syntax_kind/generated.rs";
24 pub const AST: &str = "crates/ra_syntax/src/ast/generated.rs";
25 const TOOLCHAIN: &str = "stable";
27 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
41 pub fn collect_tests(s: &str) -> Vec<(usize, Test)> {
44 let comment_blocks = s
48 .group_by(|(_idx, line)| line.starts_with(prefix));
50 'outer: for (is_comment, block) in comment_blocks.into_iter() {
54 let mut block = block.map(|(idx, line)| (idx, &line[prefix.len()..]));
57 let (start_line, name) = loop {
59 Some((idx, line)) if line.starts_with("test ") => {
60 break (idx, line["test ".len()..].to_string());
62 Some((idx, line)) if line.starts_with("test_err ") => {
64 break (idx, line["test_err ".len()..].to_string());
67 None => continue 'outer,
71 itertools::join(block.map(|(_, line)| line).chain(::std::iter::once("")), "\n");
72 assert!(!text.trim().is_empty() && text.ends_with('\n'));
73 res.push((start_line, Test { name, text, ok }))
78 pub fn project_root() -> PathBuf {
79 Path::new(&env!("CARGO_MANIFEST_DIR")).ancestors().nth(2).unwrap().to_path_buf()
83 pub unix: &'static str,
84 pub windows: &'static str,
85 pub work_dir: &'static str,
89 pub fn run(self) -> Result<()> {
91 run(self.windows, self.work_dir)
93 run(self.unix, self.work_dir)
96 pub fn run_with_output(self) -> Result<Output> {
98 run_with_output(self.windows, self.work_dir)
100 run_with_output(self.unix, self.work_dir)
105 pub fn run(cmdline: &str, dir: &str) -> Result<()> {
106 do_run(cmdline, dir, |c| {
107 c.stdout(Stdio::inherit());
112 pub fn run_with_output(cmdline: &str, dir: &str) -> Result<Output> {
113 do_run(cmdline, dir, |_| {})
116 pub fn run_rustfmt(mode: Mode) -> Result<()> {
117 match Command::new("rustup")
118 .args(&["run", TOOLCHAIN, "--", "cargo", "fmt", "--version"])
119 .stderr(Stdio::null())
120 .stdout(Stdio::null())
123 Ok(status) if status.success() => (),
124 _ => install_rustfmt()?,
128 run(&format!("rustup run {} -- cargo fmt -- --check", TOOLCHAIN), ".")?;
130 run(&format!("rustup run {} -- cargo fmt", TOOLCHAIN), ".")?;
135 pub fn install_rustfmt() -> Result<()> {
136 run(&format!("rustup install {}", TOOLCHAIN), ".")?;
137 run(&format!("rustup component add rustfmt --toolchain {}", TOOLCHAIN), ".")
140 pub fn install_format_hook() -> Result<()> {
141 let result_path = Path::new(if cfg!(windows) {
142 "./.git/hooks/pre-commit.exe"
144 "./.git/hooks/pre-commit"
146 if !result_path.exists() {
147 run("cargo build --package ra_tools --bin pre-commit", ".")?;
149 fs::copy("./target/debug/pre-commit.exe", result_path)?;
151 fs::copy("./target/debug/pre-commit", result_path)?;
154 Err(IoError::new(ErrorKind::AlreadyExists, "Git hook already created"))?;
159 pub fn run_clippy() -> Result<()> {
160 match Command::new("rustup")
161 .args(&["run", TOOLCHAIN, "--", "cargo", "clippy", "--version"])
162 .stderr(Stdio::null())
163 .stdout(Stdio::null())
166 Ok(status) if status.success() => (),
167 _ => install_clippy()?,
170 let allowed_lints = [
171 "clippy::collapsible_if",
172 "clippy::map_clone", // FIXME: remove when Iterator::copied stabilizes (1.36.0)
173 "clippy::needless_pass_by_value",
174 "clippy::nonminimal_bool",
175 "clippy::redundant_pattern_matching",
179 "rustup run {} -- cargo clippy --all-features --all-targets -- -A {}",
181 allowed_lints.join(" -A ")
188 pub fn install_clippy() -> Result<()> {
189 run(&format!("rustup install {}", TOOLCHAIN), ".")?;
190 run(&format!("rustup component add clippy --toolchain {}", TOOLCHAIN), ".")
193 pub fn run_fuzzer() -> Result<()> {
194 match Command::new("cargo")
195 .args(&["fuzz", "--help"])
196 .stderr(Stdio::null())
197 .stdout(Stdio::null())
200 Ok(status) if status.success() => (),
201 _ => run("cargo install cargo-fuzz", ".")?,
204 run("rustup run nightly -- cargo fuzz run parser", "./crates/ra_syntax")
207 pub fn gen_tests(mode: Mode) -> Result<()> {
208 let tests = tests_from_dir(&project_root().join(Path::new(GRAMMAR_DIR)))?;
209 fn install_tests(tests: &HashMap<String, Test>, into: &str, mode: Mode) -> Result<()> {
210 let tests_dir = project_root().join(into);
211 if !tests_dir.is_dir() {
212 fs::create_dir_all(&tests_dir)?;
214 // ok is never actually read, but it needs to be specified to create a Test in existing_tests
215 let existing = existing_tests(&tests_dir, true)?;
216 for t in existing.keys().filter(|&t| !tests.contains_key(t)) {
217 panic!("Test is deleted: {}", t);
220 let mut new_idx = existing.len() + 1;
221 for (name, test) in tests {
222 let path = match existing.get(name) {
223 Some((path, _test)) => path.clone(),
225 let file_name = format!("{:04}_{}.rs", new_idx, name);
227 tests_dir.join(file_name)
230 update(&path, &test.text, mode)?;
234 install_tests(&tests.ok, OK_INLINE_TESTS_DIR, mode)?;
235 install_tests(&tests.err, ERR_INLINE_TESTS_DIR, mode)
238 fn do_run<F>(cmdline: &str, dir: &str, mut f: F) -> Result<Output>
240 F: FnMut(&mut Command),
242 eprintln!("\nwill run: {}", cmdline);
243 let proj_dir = project_root().join(dir);
244 let mut args = cmdline.split_whitespace();
245 let exec = args.next().unwrap();
246 let mut cmd = Command::new(exec);
247 f(cmd.args(args).current_dir(proj_dir).stderr(Stdio::inherit()));
248 let output = cmd.output()?;
249 if !output.status.success() {
250 Err(format!("`{}` exited with {}", cmdline, output.status))?;
255 #[derive(Default, Debug)]
257 pub ok: HashMap<String, Test>,
258 pub err: HashMap<String, Test>,
261 fn tests_from_dir(dir: &Path) -> Result<Tests> {
262 let mut res = Tests::default();
263 for entry in ::walkdir::WalkDir::new(dir) {
264 let entry = entry.unwrap();
265 if !entry.file_type().is_file() {
268 if entry.path().extension().unwrap_or_default() != "rs" {
271 process_file(&mut res, entry.path())?;
273 let grammar_rs = dir.parent().unwrap().join("grammar.rs");
274 process_file(&mut res, &grammar_rs)?;
276 fn process_file(res: &mut Tests, path: &Path) -> Result<()> {
277 let text = fs::read_to_string(path)?;
279 for (_, test) in collect_tests(&text) {
281 if let Some(old_test) = res.ok.insert(test.name.clone(), test) {
282 Err(format!("Duplicate test: {}", old_test.name))?
285 if let Some(old_test) = res.err.insert(test.name.clone(), test) {
286 Err(format!("Duplicate test: {}", old_test.name))?
294 fn existing_tests(dir: &Path, ok: bool) -> Result<HashMap<String, (PathBuf, Test)>> {
295 let mut res = HashMap::new();
296 for file in fs::read_dir(dir)? {
298 let path = file.path();
299 if path.extension().unwrap_or_default() != "rs" {
303 let file_name = path.file_name().unwrap().to_str().unwrap();
304 file_name[5..file_name.len() - 3].to_string()
306 let text = fs::read_to_string(&path)?;
307 let test = Test { name: name.clone(), text, ok };
308 if let Some(old) = res.insert(name, (path, test)) {
309 println!("Duplicate test: {:?}", old);
315 /// A helper to update file on disk if it has changed.
316 /// With verify = false,
317 pub fn update(path: &Path, contents: &str, mode: Mode) -> Result<()> {
318 match fs::read_to_string(path) {
319 Ok(ref old_contents) if old_contents == contents => {
325 Err(format!("`{}` is not up-to-date", path.display()))?;
327 eprintln!("updating {}", path.display());
328 fs::write(path, contents)?;