rust-analyzer/crates/tools/src/lib.rs

148 lines
4 KiB
Rust
Raw Normal View History

use std::{
2018-10-15 18:54:27 +00:00
path::{Path, PathBuf},
2018-10-31 20:57:38 +00:00
process::{Command, Stdio},
2018-12-09 10:29:13 +00:00
fs::OpenOptions,
io::{Write, Error, ErrorKind}
};
2018-12-09 10:29:13 +00:00
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
use failure::bail;
2018-10-31 20:41:43 +00:00
use itertools::Itertools;
2018-10-16 17:53:19 +00:00
2018-10-31 20:41:43 +00:00
pub use teraron::{Mode, Overwrite, Verify};
2018-10-16 17:53:19 +00:00
2018-12-06 17:42:03 +00:00
pub type Result<T> = std::result::Result<T, failure::Error>;
2018-07-30 13:16:58 +00:00
2018-10-26 13:08:21 +00:00
pub const GRAMMAR: &str = "crates/ra_syntax/src/grammar.ron";
pub const SYNTAX_KINDS: &str = "crates/ra_syntax/src/syntax_kinds/generated.rs.tera";
pub const AST: &str = "crates/ra_syntax/src/ast/generated.rs.tera";
2018-12-06 17:22:06 +00:00
const TOOLCHAIN: &str = "1.31.0";
2018-10-15 18:54:27 +00:00
2018-07-31 12:30:11 +00:00
#[derive(Debug)]
2018-07-30 13:16:58 +00:00
pub struct Test {
pub name: String,
pub text: String,
}
2018-07-30 13:32:27 +00:00
pub fn collect_tests(s: &str) -> Vec<(usize, Test)> {
2018-07-30 13:16:58 +00:00
let mut res = vec![];
let prefix = "// ";
let comment_blocks = s
.lines()
.map(str::trim_left)
.enumerate()
2018-07-30 13:25:10 +00:00
.group_by(|(_idx, line)| line.starts_with(prefix));
2018-07-30 13:16:58 +00:00
'outer: for (is_comment, block) in comment_blocks.into_iter() {
if !is_comment {
continue;
}
let mut block = block.map(|(idx, line)| (idx, &line[prefix.len()..]));
let (start_line, name) = loop {
match block.next() {
Some((idx, line)) if line.starts_with("test ") => {
2018-12-09 10:29:13 +00:00
break (idx, line["test ".len()..].to_string());
2018-07-31 12:40:40 +00:00
}
2018-07-30 13:16:58 +00:00
Some(_) => (),
None => continue 'outer,
}
};
let text: String = itertools::join(
2018-07-31 12:40:40 +00:00
block.map(|(_, line)| line).chain(::std::iter::once("")),
"\n",
2018-07-30 13:16:58 +00:00
);
assert!(!text.trim().is_empty() && text.ends_with('\n'));
2018-07-31 12:40:40 +00:00
res.push((start_line, Test { name, text }))
2018-07-30 13:16:58 +00:00
}
res
}
2018-10-16 17:53:19 +00:00
pub fn generate(mode: Mode) -> Result<()> {
let grammar = project_root().join(GRAMMAR);
let syntax_kinds = project_root().join(SYNTAX_KINDS);
let ast = project_root().join(AST);
2018-10-31 20:41:43 +00:00
teraron::generate(&syntax_kinds, &grammar, mode)?;
teraron::generate(&ast, &grammar, mode)?;
Ok(())
}
2018-10-15 18:54:27 +00:00
pub fn project_root() -> PathBuf {
Path::new(&std::env::var("CARGO_MANIFEST_DIR").unwrap())
2018-10-26 13:08:21 +00:00
.ancestors()
.nth(2)
.unwrap()
.to_path_buf()
2018-10-15 18:54:27 +00:00
}
pub fn run(cmdline: &str, dir: &str) -> Result<()> {
eprintln!("\nwill run: {}", cmdline);
let project_dir = project_root().join(dir);
let mut args = cmdline.split_whitespace();
let exec = args.next().unwrap();
let status = Command::new(exec)
.args(args)
.current_dir(project_dir)
.status()?;
if !status.success() {
bail!("`{}` exited with {}", cmdline, status);
}
Ok(())
}
pub fn run_rustfmt(mode: Mode) -> Result<()> {
2018-10-31 20:57:38 +00:00
match Command::new("rustup")
.args(&["run", TOOLCHAIN, "--", "cargo", "fmt", "--version"])
.stderr(Stdio::null())
.stdout(Stdio::null())
.status()
{
Ok(status) if status.success() => (),
_ => install_rustfmt()?,
};
if mode == Verify {
2018-10-31 20:41:43 +00:00
run(
&format!("rustup run {} -- cargo fmt -- --check", TOOLCHAIN),
".",
)?;
} else {
run(&format!("rustup run {} -- cargo fmt", TOOLCHAIN), ".")?;
}
Ok(())
}
2018-10-31 20:57:38 +00:00
fn install_rustfmt() -> Result<()> {
run(&format!("rustup install {}", TOOLCHAIN), ".")?;
run(
&format!("rustup component add rustfmt --toolchain {}", TOOLCHAIN),
2018-10-31 20:57:38 +00:00
".",
)
}
2018-12-09 10:29:13 +00:00
pub fn install_format_hook() -> Result<()> {
let path = Path::new("./.git/hooks/pre-commit");
if !path.exists() {
let mut open_options = OpenOptions::new();
#[cfg(unix)]
{
// Set as executable
open_options.mode(0o770);
}
let mut file = open_options.write(true).create(true).open(path)?;
write!(
file,
r#"#!/bin/sh
cargo format
2018-12-09 10:37:04 +00:00
for path in $( git diff --name-only --cached ); do
git update-index --add $path
done"#
2018-12-09 10:29:13 +00:00
)?;
} else {
return Err(Error::new(ErrorKind::AlreadyExists, "Git hook already created").into());
}
Ok(())
}