aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_tools/src
diff options
context:
space:
mode:
authorAleksey Kladov <[email protected]>2019-06-10 23:47:37 +0100
committerAleksey Kladov <[email protected]>2019-06-10 23:47:37 +0100
commit10d34532e3e96ffd92c11e667deb453188c28282 (patch)
tree095ad479dde329bdbff034af1f3ec587f473b1db /crates/ra_tools/src
parent75e6c03883c4533b1134c806d166b72200b4837d (diff)
rename tools -> ra_tools
This should help with caching on CI I hope (see .travis.yml before_cache)
Diffstat (limited to 'crates/ra_tools/src')
-rw-r--r--crates/ra_tools/src/bin/pre-commit.rs28
-rw-r--r--crates/ra_tools/src/lib.rs290
-rw-r--r--crates/ra_tools/src/main.rs106
3 files changed, 424 insertions, 0 deletions
diff --git a/crates/ra_tools/src/bin/pre-commit.rs b/crates/ra_tools/src/bin/pre-commit.rs
new file mode 100644
index 000000000..c514e992b
--- /dev/null
+++ b/crates/ra_tools/src/bin/pre-commit.rs
@@ -0,0 +1,28 @@
1use std::process::Command;
2
3use failure::bail;
4
5use ra_tools::{Result, run_rustfmt, run, project_root, Overwrite};
6
7fn main() -> Result<()> {
8 run_rustfmt(Overwrite)?;
9 update_staged()
10}
11
12fn update_staged() -> Result<()> {
13 let root = project_root();
14 let output = Command::new("git")
15 .arg("diff")
16 .arg("--diff-filter=MAR")
17 .arg("--name-only")
18 .arg("--cached")
19 .current_dir(&root)
20 .output()?;
21 if !output.status.success() {
22 bail!("`git diff --diff-filter=MAR --name-only --cached` exited with {}", output.status);
23 }
24 for line in String::from_utf8(output.stdout)?.lines() {
25 run(&format!("git update-index --add {}", root.join(line).to_string_lossy()), ".")?;
26 }
27 Ok(())
28}
diff --git a/crates/ra_tools/src/lib.rs b/crates/ra_tools/src/lib.rs
new file mode 100644
index 000000000..61f6b08cd
--- /dev/null
+++ b/crates/ra_tools/src/lib.rs
@@ -0,0 +1,290 @@
1use std::{
2 fs,
3 collections::HashMap,
4 path::{Path, PathBuf},
5 process::{Command, Output, Stdio},
6 io::{Error, ErrorKind}
7};
8
9use failure::bail;
10use itertools::Itertools;
11
12pub use teraron::{Mode, Overwrite, Verify};
13
14pub type Result<T> = std::result::Result<T, failure::Error>;
15
16pub const GRAMMAR: &str = "crates/ra_syntax/src/grammar.ron";
17const GRAMMAR_DIR: &str = "crates/ra_parser/src/grammar";
18const OK_INLINE_TESTS_DIR: &str = "crates/ra_syntax/tests/data/parser/inline/ok";
19const ERR_INLINE_TESTS_DIR: &str = "crates/ra_syntax/tests/data/parser/inline/err";
20
21pub const SYNTAX_KINDS: &str = "crates/ra_parser/src/syntax_kind/generated.rs.tera";
22pub const AST: &str = "crates/ra_syntax/src/ast/generated.rs.tera";
23const TOOLCHAIN: &str = "stable";
24
25#[derive(Debug)]
26pub struct Test {
27 pub name: String,
28 pub text: String,
29 pub ok: bool,
30}
31
32pub fn collect_tests(s: &str) -> Vec<(usize, Test)> {
33 let mut res = vec![];
34 let prefix = "// ";
35 let comment_blocks = s
36 .lines()
37 .map(str::trim_start)
38 .enumerate()
39 .group_by(|(_idx, line)| line.starts_with(prefix));
40
41 'outer: for (is_comment, block) in comment_blocks.into_iter() {
42 if !is_comment {
43 continue;
44 }
45 let mut block = block.map(|(idx, line)| (idx, &line[prefix.len()..]));
46
47 let mut ok = true;
48 let (start_line, name) = loop {
49 match block.next() {
50 Some((idx, line)) if line.starts_with("test ") => {
51 break (idx, line["test ".len()..].to_string());
52 }
53 Some((idx, line)) if line.starts_with("test_err ") => {
54 ok = false;
55 break (idx, line["test_err ".len()..].to_string());
56 }
57 Some(_) => (),
58 None => continue 'outer,
59 }
60 };
61 let text: String =
62 itertools::join(block.map(|(_, line)| line).chain(::std::iter::once("")), "\n");
63 assert!(!text.trim().is_empty() && text.ends_with('\n'));
64 res.push((start_line, Test { name, text, ok }))
65 }
66 res
67}
68
69pub fn generate(mode: Mode) -> Result<()> {
70 let grammar = project_root().join(GRAMMAR);
71 let syntax_kinds = project_root().join(SYNTAX_KINDS);
72 let ast = project_root().join(AST);
73 teraron::generate(&syntax_kinds, &grammar, mode)?;
74 teraron::generate(&ast, &grammar, mode)?;
75 Ok(())
76}
77
78pub fn project_root() -> PathBuf {
79 Path::new(&env!("CARGO_MANIFEST_DIR")).ancestors().nth(2).unwrap().to_path_buf()
80}
81
82pub fn run(cmdline: &str, dir: &str) -> Result<()> {
83 do_run(cmdline, dir, |c| {
84 c.stdout(Stdio::inherit());
85 })
86 .map(|_| ())
87}
88
89pub fn run_with_output(cmdline: &str, dir: &str) -> Result<Output> {
90 do_run(cmdline, dir, |_| {})
91}
92
93pub fn run_rustfmt(mode: Mode) -> Result<()> {
94 match Command::new("rustup")
95 .args(&["run", TOOLCHAIN, "--", "cargo", "fmt", "--version"])
96 .stderr(Stdio::null())
97 .stdout(Stdio::null())
98 .status()
99 {
100 Ok(status) if status.success() => (),
101 _ => install_rustfmt()?,
102 };
103
104 if mode == Verify {
105 run(&format!("rustup run {} -- cargo fmt -- --check", TOOLCHAIN), ".")?;
106 } else {
107 run(&format!("rustup run {} -- cargo fmt", TOOLCHAIN), ".")?;
108 }
109 Ok(())
110}
111
112pub fn install_rustfmt() -> Result<()> {
113 run(&format!("rustup install {}", TOOLCHAIN), ".")?;
114 run(&format!("rustup component add rustfmt --toolchain {}", TOOLCHAIN), ".")
115}
116
117pub fn install_format_hook() -> Result<()> {
118 let result_path = Path::new(if cfg!(windows) {
119 "./.git/hooks/pre-commit.exe"
120 } else {
121 "./.git/hooks/pre-commit"
122 });
123 if !result_path.exists() {
124 run("cargo build --package ra_tools --bin pre-commit", ".")?;
125 if cfg!(windows) {
126 fs::copy("./target/debug/pre-commit.exe", result_path)?;
127 } else {
128 fs::copy("./target/debug/pre-commit", result_path)?;
129 }
130 } else {
131 return Err(Error::new(ErrorKind::AlreadyExists, "Git hook already created").into());
132 }
133 Ok(())
134}
135
136pub fn run_clippy() -> Result<()> {
137 match Command::new("rustup")
138 .args(&["run", TOOLCHAIN, "--", "cargo", "clippy", "--version"])
139 .stderr(Stdio::null())
140 .stdout(Stdio::null())
141 .status()
142 {
143 Ok(status) if status.success() => (),
144 _ => install_clippy()?,
145 };
146
147 let allowed_lints = [
148 "clippy::collapsible_if",
149 "clippy::map_clone", // FIXME: remove when Iterator::copied stabilizes (1.36.0)
150 "clippy::needless_pass_by_value",
151 "clippy::nonminimal_bool",
152 "clippy::redundant_pattern_matching",
153 ];
154 run(
155 &format!(
156 "rustup run {} -- cargo clippy --all-features --all-targets -- -A {}",
157 TOOLCHAIN,
158 allowed_lints.join(" -A ")
159 ),
160 ".",
161 )?;
162 Ok(())
163}
164
165pub fn install_clippy() -> Result<()> {
166 run(&format!("rustup install {}", TOOLCHAIN), ".")?;
167 run(&format!("rustup component add clippy --toolchain {}", TOOLCHAIN), ".")
168}
169
170pub fn run_fuzzer() -> Result<()> {
171 match Command::new("cargo")
172 .args(&["fuzz", "--help"])
173 .stderr(Stdio::null())
174 .stdout(Stdio::null())
175 .status()
176 {
177 Ok(status) if status.success() => (),
178 _ => run("cargo install cargo-fuzz", ".")?,
179 };
180
181 run("rustup run nightly -- cargo fuzz run parser", "./crates/ra_syntax")
182}
183
184pub fn gen_tests(mode: Mode) -> Result<()> {
185 let tests = tests_from_dir(&project_root().join(Path::new(GRAMMAR_DIR)))?;
186 fn install_tests(tests: &HashMap<String, Test>, into: &str, mode: Mode) -> Result<()> {
187 let tests_dir = project_root().join(into);
188 if !tests_dir.is_dir() {
189 fs::create_dir_all(&tests_dir)?;
190 }
191 // ok is never actually read, but it needs to be specified to create a Test in existing_tests
192 let existing = existing_tests(&tests_dir, true)?;
193 for t in existing.keys().filter(|&t| !tests.contains_key(t)) {
194 panic!("Test is deleted: {}", t);
195 }
196
197 let mut new_idx = existing.len() + 1;
198 for (name, test) in tests {
199 let path = match existing.get(name) {
200 Some((path, _test)) => path.clone(),
201 None => {
202 let file_name = format!("{:04}_{}.rs", new_idx, name);
203 new_idx += 1;
204 tests_dir.join(file_name)
205 }
206 };
207 teraron::update(&path, &test.text, mode)?;
208 }
209 Ok(())
210 }
211 install_tests(&tests.ok, OK_INLINE_TESTS_DIR, mode)?;
212 install_tests(&tests.err, ERR_INLINE_TESTS_DIR, mode)
213}
214
215fn do_run<F>(cmdline: &str, dir: &str, mut f: F) -> Result<Output>
216where
217 F: FnMut(&mut Command),
218{
219 eprintln!("\nwill run: {}", cmdline);
220 let proj_dir = project_root().join(dir);
221 let mut args = cmdline.split_whitespace();
222 let exec = args.next().unwrap();
223 let mut cmd = Command::new(exec);
224 f(cmd.args(args).current_dir(proj_dir).stderr(Stdio::inherit()));
225 let output = cmd.output()?;
226 if !output.status.success() {
227 bail!("`{}` exited with {}", cmdline, output.status);
228 }
229 Ok(output)
230}
231
232#[derive(Default, Debug)]
233struct Tests {
234 pub ok: HashMap<String, Test>,
235 pub err: HashMap<String, Test>,
236}
237
238fn tests_from_dir(dir: &Path) -> Result<Tests> {
239 let mut res = Tests::default();
240 for entry in ::walkdir::WalkDir::new(dir) {
241 let entry = entry.unwrap();
242 if !entry.file_type().is_file() {
243 continue;
244 }
245 if entry.path().extension().unwrap_or_default() != "rs" {
246 continue;
247 }
248 process_file(&mut res, entry.path())?;
249 }
250 let grammar_rs = dir.parent().unwrap().join("grammar.rs");
251 process_file(&mut res, &grammar_rs)?;
252 return Ok(res);
253 fn process_file(res: &mut Tests, path: &Path) -> Result<()> {
254 let text = fs::read_to_string(path)?;
255
256 for (_, test) in collect_tests(&text) {
257 if test.ok {
258 if let Some(old_test) = res.ok.insert(test.name.clone(), test) {
259 bail!("Duplicate test: {}", old_test.name)
260 }
261 } else {
262 if let Some(old_test) = res.err.insert(test.name.clone(), test) {
263 bail!("Duplicate test: {}", old_test.name)
264 }
265 }
266 }
267 Ok(())
268 }
269}
270
271fn existing_tests(dir: &Path, ok: bool) -> Result<HashMap<String, (PathBuf, Test)>> {
272 let mut res = HashMap::new();
273 for file in fs::read_dir(dir)? {
274 let file = file?;
275 let path = file.path();
276 if path.extension().unwrap_or_default() != "rs" {
277 continue;
278 }
279 let name = {
280 let file_name = path.file_name().unwrap().to_str().unwrap();
281 file_name[5..file_name.len() - 3].to_string()
282 };
283 let text = fs::read_to_string(&path)?;
284 let test = Test { name: name.clone(), text, ok };
285 if let Some(old) = res.insert(name, (path, test)) {
286 println!("Duplicate test: {:?}", old);
287 }
288 }
289 Ok(res)
290}
diff --git a/crates/ra_tools/src/main.rs b/crates/ra_tools/src/main.rs
new file mode 100644
index 000000000..285071ea5
--- /dev/null
+++ b/crates/ra_tools/src/main.rs
@@ -0,0 +1,106 @@
1use clap::{App, SubCommand};
2use core::str;
3use failure::bail;
4use ra_tools::{
5 generate, gen_tests, install_format_hook, run, run_with_output, run_rustfmt,
6 Overwrite, Result, run_fuzzer, run_clippy,
7};
8use std::{path::{PathBuf}, env};
9
10fn main() -> Result<()> {
11 let matches = App::new("tasks")
12 .setting(clap::AppSettings::SubcommandRequiredElseHelp)
13 .subcommand(SubCommand::with_name("gen-syntax"))
14 .subcommand(SubCommand::with_name("gen-tests"))
15 .subcommand(SubCommand::with_name("install-code"))
16 .subcommand(SubCommand::with_name("format"))
17 .subcommand(SubCommand::with_name("format-hook"))
18 .subcommand(SubCommand::with_name("fuzz-tests"))
19 .subcommand(SubCommand::with_name("lint"))
20 .get_matches();
21 match matches.subcommand_name().expect("Subcommand must be specified") {
22 "install-code" => {
23 if cfg!(target_os = "macos") {
24 fix_path_for_mac()?;
25 }
26 install_code_extension()?;
27 }
28 "gen-tests" => gen_tests(Overwrite)?,
29 "gen-syntax" => generate(Overwrite)?,
30 "format" => run_rustfmt(Overwrite)?,
31 "format-hook" => install_format_hook()?,
32 "lint" => run_clippy()?,
33 "fuzz-tests" => run_fuzzer()?,
34 _ => unreachable!(),
35 }
36 Ok(())
37}
38
39fn install_code_extension() -> Result<()> {
40 run("cargo install --path crates/ra_lsp_server --force", ".")?;
41 if cfg!(windows) {
42 run(r"cmd.exe /c npm.cmd ci", "./editors/code")?;
43 run(r"cmd.exe /c npm.cmd run package", "./editors/code")?;
44 } else {
45 run(r"npm ci", "./editors/code")?;
46 run(r"npm run package", "./editors/code")?;
47 }
48 if cfg!(windows) {
49 run(
50 r"cmd.exe /c code.cmd --install-extension ./ra-lsp-0.0.1.vsix --force",
51 "./editors/code",
52 )?;
53 } else {
54 run(r"code --install-extension ./ra-lsp-0.0.1.vsix --force", "./editors/code")?;
55 }
56 verify_installed_extensions()?;
57 Ok(())
58}
59
60fn verify_installed_extensions() -> Result<()> {
61 let exts = if cfg!(windows) {
62 run_with_output(r"cmd.exe /c code.cmd --list-extensions", ".")?
63 } else {
64 run_with_output(r"code --list-extensions", ".")?
65 };
66 if !str::from_utf8(&exts.stdout)?.contains("ra-lsp") {
67 bail!(
68 "Could not install the Visual Studio Code extension. Please make sure you \
69 have at least NodeJS 10.x installed and try again."
70 );
71 }
72 Ok(())
73}
74
75fn fix_path_for_mac() -> Result<()> {
76 let mut vscode_path: Vec<PathBuf> = {
77 const COMMON_APP_PATH: &str =
78 r"/Applications/Visual Studio Code.app/Contents/Resources/app/bin";
79 const ROOT_DIR: &str = "";
80 let home_dir = match env::var("HOME") {
81 Ok(home) => home,
82 Err(e) => bail!("Failed getting HOME from environment with error: {}.", e),
83 };
84
85 [ROOT_DIR, &home_dir]
86 .iter()
87 .map(|dir| String::from(*dir) + COMMON_APP_PATH)
88 .map(PathBuf::from)
89 .filter(|path| path.exists())
90 .collect()
91 };
92
93 if !vscode_path.is_empty() {
94 let vars = match env::var_os("PATH") {
95 Some(path) => path,
96 None => bail!("Could not get PATH variable from env."),
97 };
98
99 let mut paths = env::split_paths(&vars).collect::<Vec<_>>();
100 paths.append(&mut vscode_path);
101 let new_paths = env::join_paths(paths)?;
102 env::set_var("PATH", &new_paths);
103 }
104
105 Ok(())
106}