lib.rs

 1use plugin::prelude::*;
 2use serde::Deserialize;
 3use std::fs;
 4use std::path::PathBuf;
 5
 6#[import]
 7fn command(string: &str) -> Option<Vec<u8>>;
 8
 9const BIN_PATH: &'static str =
10    "node_modules/vscode-json-languageserver/bin/vscode-json-languageserver";
11
12#[export]
13pub fn name() -> &'static str {
14    "vscode-json-languageserver"
15}
16
17#[export]
18pub fn server_args() -> Vec<String> {
19    vec!["--stdio".into()]
20}
21
22#[export]
23pub fn fetch_latest_server_version() -> Option<String> {
24    #[derive(Deserialize)]
25    struct NpmInfo {
26        versions: Vec<String>,
27    }
28
29    let output =
30        command("npm info vscode-json-languageserver --json").expect("could not run command");
31    let output = String::from_utf8(output).unwrap();
32
33    let mut info: NpmInfo = serde_json::from_str(&output).ok()?;
34    info.versions.pop()
35}
36
37#[export]
38pub fn fetch_server_binary(container_dir: PathBuf, version: String) -> Result<PathBuf, String> {
39    let version_dir = container_dir.join(version.as_str());
40    fs::create_dir_all(&version_dir)
41        .map_err(|_| "failed to create version directory".to_string())?;
42    let binary_path = version_dir.join(BIN_PATH);
43
44    if fs::metadata(&binary_path).is_err() {
45        let output = command(&format!(
46            "npm install vscode-json-languageserver@{}",
47            version
48        ));
49        let output = output.map(String::from_utf8);
50        if output.is_none() {
51            return Err("failed to install vscode-json-languageserver".to_string());
52        }
53
54        if let Some(mut entries) = fs::read_dir(&container_dir).ok() {
55            while let Some(entry) = entries.next() {
56                if let Some(entry) = entry.ok() {
57                    let entry_path = entry.path();
58                    if entry_path.as_path() != version_dir {
59                        fs::remove_dir_all(&entry_path).ok();
60                    }
61                }
62            }
63        }
64    }
65
66    Ok(binary_path)
67}
68
69#[export]
70pub fn cached_server_binary(container_dir: PathBuf) -> Option<PathBuf> {
71    let mut last_version_dir = None;
72    let mut entries = fs::read_dir(&container_dir).ok()?;
73
74    while let Some(entry) = entries.next() {
75        let entry = entry.ok()?;
76        if entry.file_type().ok()?.is_dir() {
77            last_version_dir = Some(entry.path());
78        }
79    }
80
81    let last_version_dir = last_version_dir?;
82    let bin_path = last_version_dir.join(BIN_PATH);
83    if bin_path.exists() {
84        Some(bin_path)
85    } else {
86        println!("no binary found");
87        None
88    }
89}
90
91#[export]
92pub fn initialization_options() -> Option<String> {
93    Some("{ \"provideFormatter\": true }".to_string())
94}
95
96#[export]
97pub fn language_ids() -> Vec<(String, String)> {
98    vec![("JSON".into(), "jsonc".into())]
99}