tree_sitter_cli/
version.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
use std::{fs, path::PathBuf, process::Command};

use anyhow::{anyhow, Context, Result};
use regex::Regex;
use tree_sitter_loader::TreeSitterJSON;

pub struct Version {
    pub version: String,
    pub current_dir: PathBuf,
}

impl Version {
    #[must_use]
    pub const fn new(version: String, current_dir: PathBuf) -> Self {
        Self {
            version,
            current_dir,
        }
    }

    pub fn run(self) -> Result<()> {
        let tree_sitter_json = self.current_dir.join("tree-sitter.json");

        let tree_sitter_json =
            serde_json::from_str::<TreeSitterJSON>(&fs::read_to_string(tree_sitter_json)?)?;

        let is_multigrammar = tree_sitter_json.grammars.len() > 1;

        self.update_treesitter_json().with_context(|| {
            format!(
                "Failed to update tree-sitter.json at {}",
                self.current_dir.display()
            )
        })?;
        self.update_cargo_toml().with_context(|| {
            format!(
                "Failed to update Cargo.toml at {}",
                self.current_dir.display()
            )
        })?;
        self.update_package_json().with_context(|| {
            format!(
                "Failed to update package.json at {}",
                self.current_dir.display()
            )
        })?;
        self.update_makefile(is_multigrammar).with_context(|| {
            format!(
                "Failed to update Makefile at {}",
                self.current_dir.display()
            )
        })?;
        self.update_cmakelists_txt().with_context(|| {
            format!(
                "Failed to update CMakeLists.txt at {}",
                self.current_dir.display()
            )
        })?;
        self.update_pyproject_toml().with_context(|| {
            format!(
                "Failed to update pyproject.toml at {}",
                self.current_dir.display()
            )
        })?;

        Ok(())
    }

    fn update_treesitter_json(&self) -> Result<()> {
        let tree_sitter_json = &fs::read_to_string(self.current_dir.join("tree-sitter.json"))?;

        let tree_sitter_json = tree_sitter_json
            .lines()
            .map(|line| {
                if line.contains("\"version\":") {
                    let prefix_index = line.find("\"version\":").unwrap() + "\"version\":".len();
                    let start_quote = line[prefix_index..].find('"').unwrap() + prefix_index + 1;
                    let end_quote = line[start_quote + 1..].find('"').unwrap() + start_quote + 1;

                    format!(
                        "{}{}{}",
                        &line[..start_quote],
                        self.version,
                        &line[end_quote..]
                    )
                } else {
                    line.to_string()
                }
            })
            .collect::<Vec<_>>()
            .join("\n")
            + "\n";

        fs::write(self.current_dir.join("tree-sitter.json"), tree_sitter_json)?;

        Ok(())
    }

    fn update_cargo_toml(&self) -> Result<()> {
        if !self.current_dir.join("Cargo.toml").exists() {
            return Ok(());
        }

        let cargo_toml = fs::read_to_string(self.current_dir.join("Cargo.toml"))?;

        let cargo_toml = cargo_toml
            .lines()
            .map(|line| {
                if line.starts_with("version =") {
                    format!("version = \"{}\"", self.version)
                } else {
                    line.to_string()
                }
            })
            .collect::<Vec<_>>()
            .join("\n")
            + "\n";

        fs::write(self.current_dir.join("Cargo.toml"), cargo_toml)?;

        if self.current_dir.join("Cargo.lock").exists() {
            let Ok(cmd) = Command::new("cargo")
                .arg("generate-lockfile")
                .arg("--offline")
                .current_dir(&self.current_dir)
                .output()
            else {
                return Ok(()); // cargo is not `executable`, ignore
            };

            if !cmd.status.success() {
                let stderr = String::from_utf8_lossy(&cmd.stderr);
                return Err(anyhow!(
                    "Failed to run `cargo generate-lockfile`:\n{stderr}"
                ));
            }
        }

        Ok(())
    }

    fn update_package_json(&self) -> Result<()> {
        if !self.current_dir.join("package.json").exists() {
            return Ok(());
        }

        let package_json = &fs::read_to_string(self.current_dir.join("package.json"))?;

        let package_json = package_json
            .lines()
            .map(|line| {
                if line.contains("\"version\":") {
                    let prefix_index = line.find("\"version\":").unwrap() + "\"version\":".len();
                    let start_quote = line[prefix_index..].find('"').unwrap() + prefix_index + 1;
                    let end_quote = line[start_quote + 1..].find('"').unwrap() + start_quote + 1;

                    format!(
                        "{}{}{}",
                        &line[..start_quote],
                        self.version,
                        &line[end_quote..]
                    )
                } else {
                    line.to_string()
                }
            })
            .collect::<Vec<_>>()
            .join("\n")
            + "\n";

        fs::write(self.current_dir.join("package.json"), package_json)?;

        if self.current_dir.join("package-lock.json").exists() {
            let Ok(cmd) = Command::new("npm")
                .arg("install")
                .arg("--package-lock-only")
                .current_dir(&self.current_dir)
                .output()
            else {
                return Ok(()); // npm is not `executable`, ignore
            };

            if !cmd.status.success() {
                let stderr = String::from_utf8_lossy(&cmd.stderr);
                return Err(anyhow!("Failed to run `npm install`:\n{stderr}"));
            }
        }

        Ok(())
    }

    fn update_makefile(&self, is_multigrammar: bool) -> Result<()> {
        let makefile = if is_multigrammar {
            if !self.current_dir.join("common").join("common.mak").exists() {
                return Ok(());
            }

            fs::read_to_string(self.current_dir.join("Makefile"))?
        } else {
            if !self.current_dir.join("Makefile").exists() {
                return Ok(());
            }

            fs::read_to_string(self.current_dir.join("Makefile"))?
        };

        let makefile = makefile
            .lines()
            .map(|line| {
                if line.starts_with("VERSION") {
                    format!("VERSION := {}", self.version)
                } else {
                    line.to_string()
                }
            })
            .collect::<Vec<_>>()
            .join("\n")
            + "\n";

        fs::write(self.current_dir.join("Makefile"), makefile)?;

        Ok(())
    }

    fn update_cmakelists_txt(&self) -> Result<()> {
        if !self.current_dir.join("CMakeLists.txt").exists() {
            return Ok(());
        }

        let cmake = fs::read_to_string(self.current_dir.join("CMakeLists.txt"))?;

        let re = Regex::new(r#"(\s*VERSION\s+)"[0-9]+\.[0-9]+\.[0-9]+""#)?;
        let cmake = re.replace(&cmake, format!(r#"$1"{}""#, self.version));

        fs::write(self.current_dir.join("CMakeLists.txt"), cmake.as_bytes())?;

        Ok(())
    }

    fn update_pyproject_toml(&self) -> Result<()> {
        if !self.current_dir.join("pyproject.toml").exists() {
            return Ok(());
        }

        let pyproject_toml = fs::read_to_string(self.current_dir.join("pyproject.toml"))?;

        let pyproject_toml = pyproject_toml
            .lines()
            .map(|line| {
                if line.starts_with("version =") {
                    format!("version = \"{}\"", self.version)
                } else {
                    line.to_string()
                }
            })
            .collect::<Vec<_>>()
            .join("\n")
            + "\n";

        fs::write(self.current_dir.join("pyproject.toml"), pyproject_toml)?;

        Ok(())
    }
}