Skip to content

Fix rust analyzer #911

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ exercises/clippy/Cargo.lock
.idea
.vscode
*.iml
rust-project.json
27 changes: 19 additions & 8 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ console = "0.7.7"
notify = "4.0.15"
toml = "0.4.10"
regex = "1.1.6"
serde = {version = "1.0.10", features = ["derive"]}
serde = { version = "1.0.133", features = ["derive"] }
glob = "0.3.0"
serde_json = "1.0.74"
home = "0.5.3"

[[bin]]
name = "rustlings"
Expand Down
100 changes: 100 additions & 0 deletions src/fix_rust_analyzer.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
/// because `rustlings` is a special type of project where we don't have a
/// cargo.toml linking to each exercise, we need a way to tell `rust-analyzer`
/// how to parse the exercises. This functionality is built into rust-analyzer
/// by putting a `rust-project.json` at the root of the repository. This module generates
/// that file by finding the default toolchain used and looping through each exercise
/// to build the configuration in a way that allows rust-analyzer to work with the exercises.
use glob::glob;
use serde::{Deserialize, Serialize};
use std::error::Error;
use std::process::Command;

/// Contains the structure of resulting rust-project.json file
/// and functions to build the data required to create the file
#[derive(Serialize, Deserialize)]
pub struct RustAnalyzerProject {
sysroot_src: String,
crates: Vec<Crate>,
}

#[derive(Serialize, Deserialize)]
struct Crate {
root_module: String,
edition: String,
deps: Vec<String>,
}

impl RustAnalyzerProject {
pub fn new() -> RustAnalyzerProject {
RustAnalyzerProject {
sysroot_src: String::new(),
crates: Vec::new(),
}
}

/// Write rust-project.json to disk
pub fn write_to_disk(&self) -> Result<(), std::io::Error> {
std::fs::write(
"./rust-project.json",
serde_json::to_vec(&self).expect("Failed to serialize to JSON"),
)?;
Ok(())
}

/// If path contains .rs extension, add a crate to `rust-project.json`
fn path_to_json(&mut self, path: String) {
if let Some((_, ext)) = path.split_once(".") {
if ext == "rs" {
self.crates.push(Crate {
root_module: path,
edition: "2021".to_string(),
deps: Vec::new(),
})
}
}
}

/// Parse the exercises folder for .rs files, any matches will create
/// a new `crate` in rust-project.json which allows rust-analyzer to
/// treat it like a normal binary
pub fn exercies_to_json(&mut self) -> Result<(), Box<dyn Error>> {
let glob = glob("./exercises/**/*")?;
for e in glob {
let path = e?.to_string_lossy().to_string();
self.path_to_json(path);
}
Ok(())
}

/// Use `rustup` command to determine the default toolchain, if it exists
/// it will be put in RustAnalyzerProject.sysroot_src, otherwise an error will be returned
pub fn get_sysroot_src(&mut self) -> Result<(), Box<dyn Error>> {
let mut sysroot_src = home::rustup_home()?.to_string_lossy().to_string();

let output = Command::new("rustup").arg("default").output()?;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can use rustc --print sysroot instead. This also works when you don't have rustup installed.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks I changed this in new pr: #1026


let toolchain = String::from_utf8_lossy(&output.stdout).to_string();

sysroot_src += "/toolchains/";
sysroot_src += toolchain
.split_once(' ')
.ok_or("Unable to determine toolchain")?
.0;
sysroot_src += "/lib/rustlib/src/rust/library";
println!(
"Determined toolchain to use with Rustlings: {}",
sysroot_src
);
self.sysroot_src = sysroot_src;
Ok(())
}
}

#[test]
fn parses_exercises() {
let mut rust_project = RustAnalyzerProject::new();
rust_project
.exercies_to_json()
.expect("Failed to parse exercises");
assert_eq!(rust_project.crates.len() > 0, true);
}
22 changes: 22 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::exercise::{Exercise, ExerciseList};
use crate::fix_rust_analyzer::RustAnalyzerProject;
use crate::run::run;
use crate::verify::verify;
use argh::FromArgs;
Expand All @@ -20,6 +21,7 @@ use std::time::Duration;
mod ui;

mod exercise;
mod fix_rust_analyzer;
mod run;
mod verify;

Expand All @@ -37,6 +39,9 @@ struct Args {
version: bool,
#[argh(subcommand)]
nested: Option<Subcommands>,
/// skip rust-analyzer fix check
#[argh(switch, short = 'x')]
skipfix: bool,
}

#[derive(FromArgs, PartialEq, Debug)]
Expand Down Expand Up @@ -128,6 +133,10 @@ fn main() {
std::process::exit(1);
}

if !Path::new("rust-project.json").exists() && !args.skipfix {
fix_rust_analyzer();
}

if !rustc_exists() {
println!("We cannot find `rustc`.");
println!("Try running `rustc --version` to diagnose your problem.");
Expand Down Expand Up @@ -404,3 +413,16 @@ fn rustc_exists() -> bool {
.map(|status| status.success())
.unwrap_or(false)
}

fn fix_rust_analyzer() {
let mut rust_project = RustAnalyzerProject::new();
if let Err(err) = rust_project.get_sysroot_src() {
println!("Couldn't find toolchain path for rust-analyzer: {}", &err)
}
if let Err(err) = rust_project.exercies_to_json() {
println!("Couldn't parse exercises for rust-analyzer: {}", &err)
}
if let Err(_) = rust_project.write_to_disk() {
println!("Failed to write rust-project.json to disk for rust-analyzer");
};
}
1 change: 1 addition & 0 deletions tests/fixture/failure/rust-project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"sysroot_src":"/home/jacko/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library","crates":[]}
1 change: 1 addition & 0 deletions tests/fixture/state/rust-project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"sysroot_src":"/home/jacko/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library","crates":[]}
1 change: 1 addition & 0 deletions tests/fixture/success/rust-project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"sysroot_src":"/home/jacko/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library","crates":[]}