WIP: move to xtasks

This commit is contained in:
Aleksey Kladov 2019-10-17 19:36:55 +03:00
parent 65ab81e358
commit 7b15c4f7ae
15 changed files with 37 additions and 62 deletions

View file

@ -0,0 +1,31 @@
//! FIXME: write short doc here
use std::process::Command;
use ra_tools::{project_root, run, run_rustfmt, Overwrite, Result};
fn main() -> Result<()> {
run_rustfmt(Overwrite)?;
update_staged()
}
fn update_staged() -> Result<()> {
let root = project_root();
let output = Command::new("git")
.arg("diff")
.arg("--diff-filter=MAR")
.arg("--name-only")
.arg("--cached")
.current_dir(&root)
.output()?;
if !output.status.success() {
Err(format!(
"`git diff --diff-filter=MAR --name-only --cached` exited with {}",
output.status
))?;
}
for line in String::from_utf8(output.stdout)?.lines() {
run(&format!("git update-index --add {}", root.join(line).to_string_lossy()), ".")?;
}
Ok(())
}

View file

@ -0,0 +1,348 @@
//! FIXME: write short doc here
use std::{
collections::BTreeMap,
fs,
io::Write,
process::{Command, Stdio},
};
use proc_macro2::{Punct, Spacing};
use quote::{format_ident, quote};
use ron;
use serde::Deserialize;
use crate::{project_root, update, Mode, Result, AST, GRAMMAR, SYNTAX_KINDS};
pub fn generate_boilerplate(mode: Mode) -> Result<()> {
let grammar = project_root().join(GRAMMAR);
let grammar: Grammar = {
let text = fs::read_to_string(grammar)?;
ron::de::from_str(&text)?
};
let syntax_kinds_file = project_root().join(SYNTAX_KINDS);
let syntax_kinds = generate_syntax_kinds(&grammar)?;
update(syntax_kinds_file.as_path(), &syntax_kinds, mode)?;
let ast_file = project_root().join(AST);
let ast = generate_ast(&grammar)?;
update(ast_file.as_path(), &ast, mode)?;
Ok(())
}
fn generate_ast(grammar: &Grammar) -> Result<String> {
let nodes = grammar.ast.iter().map(|(name, ast_node)| {
let variants =
ast_node.variants.iter().map(|var| format_ident!("{}", var)).collect::<Vec<_>>();
let name = format_ident!("{}", name);
let adt = if variants.is_empty() {
let kind = format_ident!("{}", to_upper_snake_case(&name.to_string()));
quote! {
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct #name {
pub(crate) syntax: SyntaxNode,
}
impl AstNode for #name {
fn can_cast(kind: SyntaxKind) -> bool {
match kind {
#kind => true,
_ => false,
}
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) { Some(Self { syntax }) } else { None }
}
fn syntax(&self) -> &SyntaxNode { &self.syntax }
}
}
} else {
let kinds = variants
.iter()
.map(|name| format_ident!("{}", to_upper_snake_case(&name.to_string())))
.collect::<Vec<_>>();
quote! {
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum #name {
#(#variants(#variants),)*
}
#(
impl From<#variants> for #name {
fn from(node: #variants) -> #name {
#name::#variants(node)
}
}
)*
impl AstNode for #name {
fn can_cast(kind: SyntaxKind) -> bool {
match kind {
#(#kinds)|* => true,
_ => false,
}
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
let res = match syntax.kind() {
#(
#kinds => #name::#variants(#variants { syntax }),
)*
_ => return None,
};
Some(res)
}
fn syntax(&self) -> &SyntaxNode {
match self {
#(
#name::#variants(it) => &it.syntax,
)*
}
}
}
}
};
let traits = ast_node.traits.iter().map(|trait_name| {
let trait_name = format_ident!("{}", trait_name);
quote!(impl ast::#trait_name for #name {})
});
let collections = ast_node.collections.iter().map(|(name, kind)| {
let method_name = format_ident!("{}", name);
let kind = format_ident!("{}", kind);
quote! {
pub fn #method_name(&self) -> AstChildren<#kind> {
AstChildren::new(&self.syntax)
}
}
});
let options = ast_node.options.iter().map(|attr| {
let method_name = match attr {
Attr::Type(t) => format_ident!("{}", to_lower_snake_case(&t)),
Attr::NameType(n, _) => format_ident!("{}", n),
};
let ty = match attr {
Attr::Type(t) | Attr::NameType(_, t) => format_ident!("{}", t),
};
quote! {
pub fn #method_name(&self) -> Option<#ty> {
AstChildren::new(&self.syntax).next()
}
}
});
quote! {
#adt
#(#traits)*
impl #name {
#(#collections)*
#(#options)*
}
}
});
let ast = quote! {
use crate::{
SyntaxNode, SyntaxKind::{self, *},
ast::{self, AstNode, AstChildren},
};
#(#nodes)*
};
let pretty = reformat(ast)?;
Ok(pretty)
}
fn generate_syntax_kinds(grammar: &Grammar) -> Result<String> {
let (single_byte_tokens_values, single_byte_tokens): (Vec<_>, Vec<_>) = grammar
.punct
.iter()
.filter(|(token, _name)| token.len() == 1)
.map(|(token, name)| (token.chars().next().unwrap(), format_ident!("{}", name)))
.unzip();
let punctuation_values = grammar.punct.iter().map(|(token, _name)| {
if "{}[]()".contains(token) {
let c = token.chars().next().unwrap();
quote! { #c }
} else {
let cs = token.chars().map(|c| Punct::new(c, Spacing::Joint));
quote! { #(#cs)* }
}
});
let punctuation =
grammar.punct.iter().map(|(_token, name)| format_ident!("{}", name)).collect::<Vec<_>>();
let full_keywords_values = &grammar.keywords;
let full_keywords =
full_keywords_values.iter().map(|kw| format_ident!("{}_KW", to_upper_snake_case(&kw)));
let all_keywords_values =
grammar.keywords.iter().chain(grammar.contextual_keywords.iter()).collect::<Vec<_>>();
let all_keywords_idents = all_keywords_values.iter().map(|kw| format_ident!("{}", kw));
let all_keywords = all_keywords_values
.iter()
.map(|name| format_ident!("{}_KW", to_upper_snake_case(&name)))
.collect::<Vec<_>>();
let literals =
grammar.literals.iter().map(|name| format_ident!("{}", name)).collect::<Vec<_>>();
let tokens = grammar.tokens.iter().map(|name| format_ident!("{}", name)).collect::<Vec<_>>();
let nodes = grammar.nodes.iter().map(|name| format_ident!("{}", name)).collect::<Vec<_>>();
let ast = quote! {
#![allow(bad_style, missing_docs, unreachable_pub)]
/// The kind of syntax node, e.g. `IDENT`, `USE_KW`, or `STRUCT_DEF`.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[repr(u16)]
pub enum SyntaxKind {
// Technical SyntaxKinds: they appear temporally during parsing,
// but never end up in the final tree
#[doc(hidden)]
TOMBSTONE,
#[doc(hidden)]
EOF,
#(#punctuation,)*
#(#all_keywords,)*
#(#literals,)*
#(#tokens,)*
#(#nodes,)*
// Technical kind so that we can cast from u16 safely
#[doc(hidden)]
__LAST,
}
use self::SyntaxKind::*;
impl SyntaxKind {
pub fn is_keyword(self) -> bool {
match self {
#(#all_keywords)|* => true,
_ => false,
}
}
pub fn is_punct(self) -> bool {
match self {
#(#punctuation)|* => true,
_ => false,
}
}
pub fn is_literal(self) -> bool {
match self {
#(#literals)|* => true,
_ => false,
}
}
pub fn from_keyword(ident: &str) -> Option<SyntaxKind> {
let kw = match ident {
#(#full_keywords_values => #full_keywords,)*
_ => return None,
};
Some(kw)
}
pub fn from_char(c: char) -> Option<SyntaxKind> {
let tok = match c {
#(#single_byte_tokens_values => #single_byte_tokens,)*
_ => return None,
};
Some(tok)
}
}
#[macro_export]
macro_rules! T {
#((#punctuation_values) => { $crate::SyntaxKind::#punctuation };)*
#((#all_keywords_idents) => { $crate::SyntaxKind::#all_keywords };)*
}
};
reformat(ast)
}
fn reformat(text: impl std::fmt::Display) -> Result<String> {
let mut rustfmt = Command::new("rustfmt")
.arg("--config-path")
.arg(project_root().join("rustfmt.toml"))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()?;
write!(rustfmt.stdin.take().unwrap(), "{}", text)?;
let output = rustfmt.wait_with_output()?;
let stdout = String::from_utf8(output.stdout)?;
let preamble = "Generated file, do not edit by hand, see `crate/ra_tools/src/codegen`";
Ok(format!("//! {}\n\n{}", preamble, stdout))
}
#[derive(Deserialize, Debug)]
struct Grammar {
punct: Vec<(String, String)>,
keywords: Vec<String>,
contextual_keywords: Vec<String>,
literals: Vec<String>,
tokens: Vec<String>,
nodes: Vec<String>,
ast: BTreeMap<String, AstNode>,
}
#[derive(Deserialize, Debug)]
struct AstNode {
#[serde(default)]
#[serde(rename = "enum")]
variants: Vec<String>,
#[serde(default)]
traits: Vec<String>,
#[serde(default)]
collections: Vec<(String, String)>,
#[serde(default)]
options: Vec<Attr>,
}
#[derive(Deserialize, Debug)]
#[serde(untagged)]
enum Attr {
Type(String),
NameType(String, String),
}
fn to_upper_snake_case(s: &str) -> String {
let mut buf = String::with_capacity(s.len());
let mut prev_is_upper = None;
for c in s.chars() {
if c.is_ascii_uppercase() && prev_is_upper == Some(false) {
buf.push('_')
}
prev_is_upper = Some(c.is_ascii_uppercase());
buf.push(c.to_ascii_uppercase());
}
buf
}
fn to_lower_snake_case(s: &str) -> String {
let mut buf = String::with_capacity(s.len());
let mut prev_is_upper = None;
for c in s.chars() {
if c.is_ascii_uppercase() && prev_is_upper == Some(false) {
buf.push('_')
}
prev_is_upper = Some(c.is_ascii_uppercase());
buf.push(c.to_ascii_lowercase());
}
buf
}

47
xtask/src/help.rs Normal file
View file

@ -0,0 +1,47 @@
//! FIXME: write short doc here
pub const GLOBAL_HELP: &str = "tasks
USAGE:
ra_tools <SUBCOMMAND>
FLAGS:
-h, --help Prints help information
SUBCOMMANDS:
format
format-hook
fuzz-tests
codegen
gen-tests
install
lint";
pub const INSTALL_HELP: &str = "ra_tools-install
USAGE:
ra_tools.exe install [FLAGS]
FLAGS:
--client-code
-h, --help Prints help information
--jemalloc
--server";
pub fn print_no_param_subcommand_help(subcommand: &str) {
eprintln!(
"ra_tools-{}
USAGE:
ra_tools {}
FLAGS:
-h, --help Prints help information",
subcommand, subcommand
);
}
pub const INSTALL_RA_CONFLICT: &str =
"error: The argument `--server` cannot be used with `--client-code`
For more information try --help";

332
xtask/src/lib.rs Normal file
View file

@ -0,0 +1,332 @@
//! FIXME: write short doc here
mod boilerplate_gen;
use std::{
collections::HashMap,
error::Error,
fs,
io::{Error as IoError, ErrorKind},
path::{Path, PathBuf},
process::{Command, Output, Stdio},
};
use itertools::Itertools;
pub use self::boilerplate_gen::generate_boilerplate;
pub type Result<T> = std::result::Result<T, Box<dyn Error>>;
pub const GRAMMAR: &str = "crates/ra_syntax/src/grammar.ron";
const GRAMMAR_DIR: &str = "crates/ra_parser/src/grammar";
const OK_INLINE_TESTS_DIR: &str = "crates/ra_syntax/test_data/parser/inline/ok";
const ERR_INLINE_TESTS_DIR: &str = "crates/ra_syntax/test_data/parser/inline/err";
pub const SYNTAX_KINDS: &str = "crates/ra_parser/src/syntax_kind/generated.rs";
pub const AST: &str = "crates/ra_syntax/src/ast/generated.rs";
const TOOLCHAIN: &str = "stable";
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Mode {
Overwrite,
Verify,
}
pub use Mode::*;
#[derive(Debug)]
pub struct Test {
pub name: String,
pub text: String,
pub ok: bool,
}
pub fn collect_tests(s: &str) -> Vec<(usize, Test)> {
let mut res = vec![];
let prefix = "// ";
let comment_blocks = s
.lines()
.map(str::trim_start)
.enumerate()
.group_by(|(_idx, line)| line.starts_with(prefix));
'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 mut ok = true;
let (start_line, name) = loop {
match block.next() {
Some((idx, line)) if line.starts_with("test ") => {
break (idx, line["test ".len()..].to_string());
}
Some((idx, line)) if line.starts_with("test_err ") => {
ok = false;
break (idx, line["test_err ".len()..].to_string());
}
Some(_) => (),
None => continue 'outer,
}
};
let text: String =
itertools::join(block.map(|(_, line)| line).chain(::std::iter::once("")), "\n");
assert!(!text.trim().is_empty() && text.ends_with('\n'));
res.push((start_line, Test { name, text, ok }))
}
res
}
pub fn project_root() -> PathBuf {
Path::new(&env!("CARGO_MANIFEST_DIR")).ancestors().nth(1).unwrap().to_path_buf()
}
pub struct Cmd<'a> {
pub unix: &'a str,
pub windows: &'a str,
pub work_dir: &'a str,
}
impl Cmd<'_> {
pub fn run(self) -> Result<()> {
if cfg!(windows) {
run(self.windows, self.work_dir)
} else {
run(self.unix, self.work_dir)
}
}
pub fn run_with_output(self) -> Result<Output> {
if cfg!(windows) {
run_with_output(self.windows, self.work_dir)
} else {
run_with_output(self.unix, self.work_dir)
}
}
}
pub fn run(cmdline: &str, dir: &str) -> Result<()> {
do_run(cmdline, dir, |c| {
c.stdout(Stdio::inherit());
})
.map(|_| ())
}
pub fn run_with_output(cmdline: &str, dir: &str) -> Result<Output> {
do_run(cmdline, dir, |_| {})
}
pub fn run_rustfmt(mode: Mode) -> Result<()> {
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 {
run(&format!("rustup run {} -- cargo fmt -- --check", TOOLCHAIN), ".")?;
} else {
run(&format!("rustup run {} -- cargo fmt", TOOLCHAIN), ".")?;
}
Ok(())
}
pub fn install_rustfmt() -> Result<()> {
run(&format!("rustup install {}", TOOLCHAIN), ".")?;
run(&format!("rustup component add rustfmt --toolchain {}", TOOLCHAIN), ".")
}
pub fn install_format_hook() -> Result<()> {
let result_path = Path::new(if cfg!(windows) {
"./.git/hooks/pre-commit.exe"
} else {
"./.git/hooks/pre-commit"
});
if !result_path.exists() {
run("cargo build --package ra_tools --bin pre-commit", ".")?;
if cfg!(windows) {
fs::copy("./target/debug/pre-commit.exe", result_path)?;
} else {
fs::copy("./target/debug/pre-commit", result_path)?;
}
} else {
Err(IoError::new(ErrorKind::AlreadyExists, "Git hook already created"))?;
}
Ok(())
}
pub fn run_clippy() -> Result<()> {
match Command::new("rustup")
.args(&["run", TOOLCHAIN, "--", "cargo", "clippy", "--version"])
.stderr(Stdio::null())
.stdout(Stdio::null())
.status()
{
Ok(status) if status.success() => (),
_ => install_clippy()?,
};
let allowed_lints = [
"clippy::collapsible_if",
"clippy::map_clone", // FIXME: remove when Iterator::copied stabilizes (1.36.0)
"clippy::needless_pass_by_value",
"clippy::nonminimal_bool",
"clippy::redundant_pattern_matching",
];
run(
&format!(
"rustup run {} -- cargo clippy --all-features --all-targets -- -A {}",
TOOLCHAIN,
allowed_lints.join(" -A ")
),
".",
)?;
Ok(())
}
pub fn install_clippy() -> Result<()> {
run(&format!("rustup install {}", TOOLCHAIN), ".")?;
run(&format!("rustup component add clippy --toolchain {}", TOOLCHAIN), ".")
}
pub fn run_fuzzer() -> Result<()> {
match Command::new("cargo")
.args(&["fuzz", "--help"])
.stderr(Stdio::null())
.stdout(Stdio::null())
.status()
{
Ok(status) if status.success() => (),
_ => run("cargo install cargo-fuzz", ".")?,
};
run("rustup run nightly -- cargo fuzz run parser", "./crates/ra_syntax")
}
pub fn gen_tests(mode: Mode) -> Result<()> {
let tests = tests_from_dir(&project_root().join(Path::new(GRAMMAR_DIR)))?;
fn install_tests(tests: &HashMap<String, Test>, into: &str, mode: Mode) -> Result<()> {
let tests_dir = project_root().join(into);
if !tests_dir.is_dir() {
fs::create_dir_all(&tests_dir)?;
}
// ok is never actually read, but it needs to be specified to create a Test in existing_tests
let existing = existing_tests(&tests_dir, true)?;
for t in existing.keys().filter(|&t| !tests.contains_key(t)) {
panic!("Test is deleted: {}", t);
}
let mut new_idx = existing.len() + 1;
for (name, test) in tests {
let path = match existing.get(name) {
Some((path, _test)) => path.clone(),
None => {
let file_name = format!("{:04}_{}.rs", new_idx, name);
new_idx += 1;
tests_dir.join(file_name)
}
};
update(&path, &test.text, mode)?;
}
Ok(())
}
install_tests(&tests.ok, OK_INLINE_TESTS_DIR, mode)?;
install_tests(&tests.err, ERR_INLINE_TESTS_DIR, mode)
}
fn do_run<F>(cmdline: &str, dir: &str, mut f: F) -> Result<Output>
where
F: FnMut(&mut Command),
{
eprintln!("\nwill run: {}", cmdline);
let proj_dir = project_root().join(dir);
let mut args = cmdline.split_whitespace();
let exec = args.next().unwrap();
let mut cmd = Command::new(exec);
f(cmd.args(args).current_dir(proj_dir).stderr(Stdio::inherit()));
let output = cmd.output()?;
if !output.status.success() {
Err(format!("`{}` exited with {}", cmdline, output.status))?;
}
Ok(output)
}
#[derive(Default, Debug)]
struct Tests {
pub ok: HashMap<String, Test>,
pub err: HashMap<String, Test>,
}
fn tests_from_dir(dir: &Path) -> Result<Tests> {
let mut res = Tests::default();
for entry in ::walkdir::WalkDir::new(dir) {
let entry = entry.unwrap();
if !entry.file_type().is_file() {
continue;
}
if entry.path().extension().unwrap_or_default() != "rs" {
continue;
}
process_file(&mut res, entry.path())?;
}
let grammar_rs = dir.parent().unwrap().join("grammar.rs");
process_file(&mut res, &grammar_rs)?;
return Ok(res);
fn process_file(res: &mut Tests, path: &Path) -> Result<()> {
let text = fs::read_to_string(path)?;
for (_, test) in collect_tests(&text) {
if test.ok {
if let Some(old_test) = res.ok.insert(test.name.clone(), test) {
Err(format!("Duplicate test: {}", old_test.name))?
}
} else {
if let Some(old_test) = res.err.insert(test.name.clone(), test) {
Err(format!("Duplicate test: {}", old_test.name))?
}
}
}
Ok(())
}
}
fn existing_tests(dir: &Path, ok: bool) -> Result<HashMap<String, (PathBuf, Test)>> {
let mut res = HashMap::new();
for file in fs::read_dir(dir)? {
let file = file?;
let path = file.path();
if path.extension().unwrap_or_default() != "rs" {
continue;
}
let name = {
let file_name = path.file_name().unwrap().to_str().unwrap();
file_name[5..file_name.len() - 3].to_string()
};
let text = fs::read_to_string(&path)?;
let test = Test { name: name.clone(), text, ok };
if let Some(old) = res.insert(name, (path, test)) {
println!("Duplicate test: {:?}", old);
}
}
Ok(res)
}
/// A helper to update file on disk if it has changed.
/// With verify = false,
pub fn update(path: &Path, contents: &str, mode: Mode) -> Result<()> {
match fs::read_to_string(path) {
Ok(ref old_contents) if old_contents == contents => {
return Ok(());
}
_ => (),
}
if mode == Verify {
Err(format!("`{}` is not up-to-date", path.display()))?;
}
eprintln!("updating {}", path.display());
fs::write(path, contents)?;
Ok(())
}

218
xtask/src/main.rs Normal file
View file

@ -0,0 +1,218 @@
//! FIXME: write short doc here
mod help;
use core::fmt::Write;
use core::str;
use pico_args::Arguments;
use std::{env, path::PathBuf};
use xtask::{
gen_tests, generate_boilerplate, install_format_hook, run, run_clippy, run_fuzzer, run_rustfmt,
Cmd, Overwrite, Result,
};
struct InstallOpt {
client: Option<ClientOpt>,
server: Option<ServerOpt>,
}
enum ClientOpt {
VsCode,
}
struct ServerOpt {
jemalloc: bool,
}
fn main() -> Result<()> {
let subcommand = match std::env::args_os().nth(1) {
None => {
eprintln!("{}", help::GLOBAL_HELP);
return Ok(());
}
Some(s) => s,
};
let mut matches = Arguments::from_vec(std::env::args_os().skip(2).collect());
let subcommand = &*subcommand.to_string_lossy();
match subcommand {
"install" => {
if matches.contains(["-h", "--help"]) {
eprintln!("{}", help::INSTALL_HELP);
return Ok(());
}
let server = matches.contains("--server");
let client_code = matches.contains("--client-code");
if server && client_code {
eprintln!("{}", help::INSTALL_RA_CONFLICT);
return Ok(());
}
let jemalloc = matches.contains("--jemalloc");
matches.finish().or_else(handle_extra_flags)?;
let opts = InstallOpt {
client: if server { None } else { Some(ClientOpt::VsCode) },
server: if client_code { None } else { Some(ServerOpt { jemalloc: jemalloc }) },
};
install(opts)?
}
"gen-tests" => {
if matches.contains(["-h", "--help"]) {
help::print_no_param_subcommand_help(&subcommand);
return Ok(());
}
gen_tests(Overwrite)?
}
"codegen" => {
if matches.contains(["-h", "--help"]) {
help::print_no_param_subcommand_help(&subcommand);
return Ok(());
}
generate_boilerplate(Overwrite)?
}
"format" => {
if matches.contains(["-h", "--help"]) {
help::print_no_param_subcommand_help(&subcommand);
return Ok(());
}
run_rustfmt(Overwrite)?
}
"format-hook" => {
if matches.contains(["-h", "--help"]) {
help::print_no_param_subcommand_help(&subcommand);
return Ok(());
}
install_format_hook()?
}
"lint" => {
if matches.contains(["-h", "--help"]) {
help::print_no_param_subcommand_help(&subcommand);
return Ok(());
}
run_clippy()?
}
"fuzz-tests" => {
if matches.contains(["-h", "--help"]) {
help::print_no_param_subcommand_help(&subcommand);
return Ok(());
}
run_fuzzer()?
}
_ => eprintln!("{}", help::GLOBAL_HELP),
}
Ok(())
}
fn handle_extra_flags(e: pico_args::Error) -> Result<()> {
if let pico_args::Error::UnusedArgsLeft(flags) = e {
let mut invalid_flags = String::new();
for flag in flags {
write!(&mut invalid_flags, "{}, ", flag)?;
}
let (invalid_flags, _) = invalid_flags.split_at(invalid_flags.len() - 2);
Err(format!("Invalid flags: {}", invalid_flags).into())
} else {
Err(e.to_string().into())
}
}
fn install(opts: InstallOpt) -> Result<()> {
if cfg!(target_os = "macos") {
fix_path_for_mac()?
}
if let Some(server) = opts.server {
install_server(server)?;
}
if let Some(client) = opts.client {
install_client(client)?;
}
Ok(())
}
fn fix_path_for_mac() -> Result<()> {
let mut vscode_path: Vec<PathBuf> = {
const COMMON_APP_PATH: &str =
r"/Applications/Visual Studio Code.app/Contents/Resources/app/bin";
const ROOT_DIR: &str = "";
let home_dir = match env::var("HOME") {
Ok(home) => home,
Err(e) => Err(format!("Failed getting HOME from environment with error: {}.", e))?,
};
[ROOT_DIR, &home_dir]
.iter()
.map(|dir| String::from(*dir) + COMMON_APP_PATH)
.map(PathBuf::from)
.filter(|path| path.exists())
.collect()
};
if !vscode_path.is_empty() {
let vars = match env::var_os("PATH") {
Some(path) => path,
None => Err("Could not get PATH variable from env.")?,
};
let mut paths = env::split_paths(&vars).collect::<Vec<_>>();
paths.append(&mut vscode_path);
let new_paths = env::join_paths(paths)?;
env::set_var("PATH", &new_paths);
}
Ok(())
}
fn install_client(ClientOpt::VsCode: ClientOpt) -> Result<()> {
Cmd { unix: r"npm ci", windows: r"cmd.exe /c npm.cmd ci", work_dir: "./editors/code" }.run()?;
Cmd {
unix: r"npm run package",
windows: r"cmd.exe /c npm.cmd run package",
work_dir: "./editors/code",
}
.run()?;
let code_binary = ["code", "code-insiders", "codium"].iter().find(|bin| {
Cmd {
unix: &format!("{} --version", bin),
windows: &format!("cmd.exe /c {}.cmd --version", bin),
work_dir: "./editors/code",
}
.run()
.is_ok()
});
let code_binary = match code_binary {
Some(it) => it,
None => Err("Can't execute `code --version`. Perhaps it is not in $PATH?")?,
};
Cmd {
unix: &format!(r"{} --install-extension ./ra-lsp-0.0.1.vsix --force", code_binary),
windows: &format!(
r"cmd.exe /c {}.cmd --install-extension ./ra-lsp-0.0.1.vsix --force",
code_binary
),
work_dir: "./editors/code",
}
.run()?;
let output = Cmd {
unix: &format!(r"{} --list-extensions", code_binary),
windows: &format!(r"cmd.exe /c {}.cmd --list-extensions", code_binary),
work_dir: ".",
}
.run_with_output()?;
if !str::from_utf8(&output.stdout)?.contains("ra-lsp") {
Err("Could not install the Visual Studio Code extension. \
Please make sure you have at least NodeJS 10.x installed and try again.")?;
}
Ok(())
}
fn install_server(opts: ServerOpt) -> Result<()> {
if opts.jemalloc {
run("cargo install --path crates/ra_lsp_server --locked --force --features jemalloc", ".")
} else {
run("cargo install --path crates/ra_lsp_server --locked --force", ".")
}
}