lib.rs

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