]> git.lizzy.rs Git - rust.git/blob - crates/tools/src/lib.rs
Use stable toolchain
[rust.git] / crates / tools / src / lib.rs
1 use std::{
2     path::{Path, PathBuf},
3     process::{Command, Stdio},
4     fs::copy,
5     io::{Error, ErrorKind}
6 };
7
8 use failure::bail;
9 use itertools::Itertools;
10
11 pub use teraron::{Mode, Overwrite, Verify};
12
13 pub type Result<T> = std::result::Result<T, failure::Error>;
14
15 pub const GRAMMAR: &str = "crates/ra_syntax/src/grammar.ron";
16 pub const SYNTAX_KINDS: &str = "crates/ra_syntax/src/syntax_kinds/generated.rs.tera";
17 pub const AST: &str = "crates/ra_syntax/src/ast/generated.rs.tera";
18 const TOOLCHAIN: &str = "stable";
19
20 #[derive(Debug)]
21 pub struct Test {
22     pub name: String,
23     pub text: String,
24     pub ok: bool,
25 }
26
27 pub fn collect_tests(s: &str) -> Vec<(usize, Test)> {
28     let mut res = vec![];
29     let prefix = "// ";
30     let comment_blocks = s
31         .lines()
32         .map(str::trim_start)
33         .enumerate()
34         .group_by(|(_idx, line)| line.starts_with(prefix));
35
36     'outer: for (is_comment, block) in comment_blocks.into_iter() {
37         if !is_comment {
38             continue;
39         }
40         let mut block = block.map(|(idx, line)| (idx, &line[prefix.len()..]));
41
42         let mut ok = true;
43         let (start_line, name) = loop {
44             match block.next() {
45                 Some((idx, line)) if line.starts_with("test ") => {
46                     break (idx, line["test ".len()..].to_string());
47                 }
48                 Some((idx, line)) if line.starts_with("test_err ") => {
49                     ok = false;
50                     break (idx, line["test_err ".len()..].to_string());
51                 }
52                 Some(_) => (),
53                 None => continue 'outer,
54             }
55         };
56         let text: String = itertools::join(
57             block.map(|(_, line)| line).chain(::std::iter::once("")),
58             "\n",
59         );
60         assert!(!text.trim().is_empty() && text.ends_with('\n'));
61         res.push((start_line, Test { name, text, ok }))
62     }
63     res
64 }
65
66 pub fn generate(mode: Mode) -> Result<()> {
67     let grammar = project_root().join(GRAMMAR);
68     let syntax_kinds = project_root().join(SYNTAX_KINDS);
69     let ast = project_root().join(AST);
70     teraron::generate(&syntax_kinds, &grammar, mode)?;
71     teraron::generate(&ast, &grammar, mode)?;
72     Ok(())
73 }
74
75 pub fn project_root() -> PathBuf {
76     Path::new(&env!("CARGO_MANIFEST_DIR"))
77         .ancestors()
78         .nth(2)
79         .unwrap()
80         .to_path_buf()
81 }
82
83 pub fn run(cmdline: &str, dir: &str) -> Result<()> {
84     eprintln!("\nwill run: {}", cmdline);
85     let project_dir = project_root().join(dir);
86     let mut args = cmdline.split_whitespace();
87     let exec = args.next().unwrap();
88     let status = Command::new(exec)
89         .args(args)
90         .current_dir(project_dir)
91         .status()?;
92     if !status.success() {
93         bail!("`{}` exited with {}", cmdline, status);
94     }
95     Ok(())
96 }
97
98 pub fn run_rustfmt(mode: Mode) -> Result<()> {
99     match Command::new("rustup")
100         .args(&["run", TOOLCHAIN, "--", "cargo", "fmt", "--version"])
101         .stderr(Stdio::null())
102         .stdout(Stdio::null())
103         .status()
104     {
105         Ok(status) if status.success() => (),
106         _ => install_rustfmt()?,
107     };
108
109     if mode == Verify {
110         run(
111             &format!("rustup run {} -- cargo fmt -- --check", TOOLCHAIN),
112             ".",
113         )?;
114     } else {
115         run(&format!("rustup run {} -- cargo fmt", TOOLCHAIN), ".")?;
116     }
117     Ok(())
118 }
119
120 pub fn install_rustfmt() -> Result<()> {
121     run(&format!("rustup install {}", TOOLCHAIN), ".")?;
122     run(
123         &format!("rustup component add rustfmt --toolchain {}", TOOLCHAIN),
124         ".",
125     )
126 }
127
128 pub fn install_format_hook() -> Result<()> {
129     let result_path = Path::new("./.git/hooks/pre-commit");
130     if !result_path.exists() {
131         run("cargo build --package tools --bin pre-commit", ".")?;
132         if cfg!(windows) {
133             copy("./target/debug/pre-commit.exe", result_path)?;
134         } else {
135             copy("./target/debug/pre-commit", result_path)?;
136         }
137     } else {
138         return Err(Error::new(ErrorKind::AlreadyExists, "Git hook already created").into());
139     }
140     Ok(())
141 }
142
143 pub fn run_fuzzer() -> Result<()> {
144     match Command::new("cargo")
145         .args(&["fuzz", "--help"])
146         .stderr(Stdio::null())
147         .stdout(Stdio::null())
148         .status()
149     {
150         Ok(status) if status.success() => (),
151         _ => run("cargo install cargo-fuzz", ".")?,
152     };
153
154     run(
155         "rustup run nightly -- cargo fuzz run parser",
156         "./crates/ra_syntax",
157     )
158 }