Debian Codegraph @

Xtree-house/skidder/src/lib.rs

raw symbols SCIP
1 use std::fs::File;
2 use std::io::{BufReader, Read, Seek, SeekFrom, Write};
3 use std::num::NonZeroUsize;
4 use std::path::{Path, PathBuf};
5 use std::process::{Command, Stdio};
6 use std::sync::atomic::{self, AtomicUsize};
7 use std::sync::Mutex;
8 use std::time::Duration;
9 use std::{fs, io, thread};
10
11 use anyhow::{bail, ensure, Context, Result};
12 use indicatif::{ProgressBar, ProgressStyle};
13 use ruzstd::frame::ReadFrameHeaderError;
14 use ruzstd::frame_decoder::FrameDecoderError;
15 use ruzstd::{BlockDecodingStrategy, FrameDecoder};
16 use serde::{Deserialize, Serialize};
17
18 #[cfg(not(windows))]
19 const LIB_EXTENSION: &str = "so";
20 #[cfg(windows)]
21 const LIB_EXTENSION: &str = "dll";
22
23 mod build;
24
25 #[derive(Debug, Serialize, Deserialize)]
26 pub struct Config {
27 pub repos: Vec<Repo>,
28 pub index: PathBuf,
29 pub verbose: bool,
30 }
31
32 impl Config {
33 pub fn compiled_parser_path(&self, grammar: &str) -> Option<(String, PathBuf)> {
34 let (repo, metadata) = self.repos.iter().find_map(|repo| {
35 let metadata = repo.read_metadata(self, grammar).ok()?;
36 Some((repo, metadata))
37 })?;
38
39 let grammar = match metadata {
40 Metadata::ReuseParser { name, .. } => name,
41 Metadata::ParserDefinition { .. } => grammar.to_string(),
42 };
43
44 let parser = repo
45 .dir(self)
46 .join(&grammar)
47 .join(&grammar)
48 .with_extension(LIB_EXTENSION);
49 parser.exists().then_some((grammar, parser))
50 }
51
52 pub fn grammar_dir(&self, grammar: &str) -> Option<PathBuf> {
53 self.repos.iter().find_map(|repo| {
54 repo.has_grammar(self, grammar)
55 .then(|| repo.dir(self).join(grammar))
56 })
57 }
58
59 fn git(&self, args: &[&str], dir: &Path) -> Result<()> {
60 let mut cmd = Command::new("git");
61 cmd.args(args).current_dir(dir);
62 if self.verbose {
63 println!("{}: git {}", dir.display(), args.join(" "))
64 }
65 let status = if self.verbose {
66 cmd.status().context("failed to invoke git")?
67 } else {
68 let res = cmd.output().context("failed to invoke git")?;
69 if !res.status.success() {
70 let _ = io::stdout().write_all(&res.stdout);
71 let _ = io::stderr().write_all(&res.stderr);
72 }
73 res.status
74 };
75 if !status.success() {
76 bail!("git returned non-zero exit-code: {status}");
77 }
78 Ok(())
79 }
80
81 // TODO: remove?
82 #[allow(dead_code)]
83 fn git_exit_with(&self, args: &[&str], dir: &Path, exitcode: i32) -> Result<bool> {
84 let mut cmd = Command::new("git");
85 cmd.args(args).current_dir(dir);
86 if self.verbose {
87 println!("{}: git {}", dir.display(), args.join(" "))
88 }
89 if !self.verbose {
90 cmd.stdout(Stdio::piped());
91 cmd.stderr(Stdio::piped());
92 }
93 let status = cmd.status().context("failed to invoke git")?;
94 if status.code() == Some(exitcode) {
95 return Ok(true);
96 }
97 if !status.success() {
98 bail!("git returned unexpected exit-code: {status}");
99 }
100 Ok(false)
101 }
102
103 fn git_output(&self, args: &[&str], dir: &Path) -> Result<String> {
104 let mut cmd = Command::new("git");
105 cmd.args(args).current_dir(dir);
106 if self.verbose {
107 println!("{}: git {}", dir.display(), args.join(" "))
108 }
109 let res = cmd.output().context("failed to invoke git")?;
110 if !res.status.success() {
111 let _ = io::stdout().write_all(&res.stdout);
112 let _ = io::stderr().write_all(&res.stderr);
113 bail!("git returned non-zero exit-code: {}", res.status);
114 }
115 String::from_utf8(res.stdout).context("git returned invalid utf8")
116 }
117 }
118
119 #[derive(Clone, Debug, Serialize, Deserialize)]
120 pub enum Repo {
121 Git {
122 name: String,
123 remote: String,
124 branch: String,
125 },
126 Local {
127 path: PathBuf,
128 },
129 }
130
131 impl Repo {
132 pub fn dir(&self, config: &Config) -> PathBuf {
133 match self {
134 Repo::Git { name, .. } => config.index.join(name),
135 Repo::Local { path } => path.clone(),
136 }
137 }
138
139 pub fn has_grammar(&self, config: &Config, grammar: &str) -> bool {
140 self.dir(config)
141 .join(grammar)
142 .join("metadata.json")
143 .exists()
144 }
145
146 pub fn read_metadata(&self, config: &Config, grammar: &str) -> Result<Metadata> {
147 let path = self.dir(config).join(grammar).join("metadata.json");
148 Metadata::read(&path).with_context(|| format!("failed to read metadata for {grammar}"))
149 }
150
151 pub fn list_grammars(&self, config: &Config) -> Result<Vec<PathBuf>> {
152 let dir = self.dir(config);
153 if !dir.exists() {
154 return Ok(vec![]);
155 }
156 fs::read_dir(&dir)
157 .with_context(|| format!("failed to access repository {}", dir.display()))?
158 .map(|dent| {
159 let dent =
160 dent.with_context(|| format!("failed to access repository {}", dir.display()))?;
161 if !dent.file_type()?.is_dir() || dent.file_name().to_str().is_none() {
162 return Ok(None);
163 }
164 let path = dent.path();
165 let metadata_file = path.join("metadata.json");
166 if !metadata_file.exists() {
167 return Ok(None);
168 }
169 let metadata = Metadata::read(&metadata_file).with_context(|| {
170 format!("failed to read metadata file {}", metadata_file.display())
171 })?;
172 Ok(metadata.parser_definition().map(|_| dent.path()))
173 })
174 .filter_map(|res| res.transpose())
175 .collect()
176 }
177
178 pub fn fetch(&self, config: &Config, update: bool) -> Result<()> {
179 let Repo::Git { remote, branch, .. } = self else {
180 return Ok(());
181 };
182 let dir = self.dir(config);
183 if dir.join(".git").exists() {
184 let current_branch = config.git_output(&["rev-parse", "--abbrev-ref", "HEAD"], &dir)?;
185 let switch_branch = current_branch != *branch;
186 if !update && !switch_branch {
187 return Ok(());
188 }
189 if switch_branch {
190 config.git(&["reset", "--hard"], &dir)?;
191 // Cloning with `--single-branch` sets the `remote.origin.fetch`
192 // spec to only fetch the desired branch. Switch this branch to
193 // the new desired branch.
194 config.git(
195 &[
196 "config",
197 "remote.origin.fetch",
198 &format!("+refs/heads/{branch}:refs/remotes/origin/{branch}"),
199 ],
200 &dir,
201 )?;
202 }
203 config.git(&["fetch", "origin", branch], &dir)?;
204 if switch_branch {
205 // Note that `git switch <branch>` exists but is marked as experimental
206 // at time of writing. `git checkout <existing branch>` is the tried and
207 // true alternative.
208 config.git(&["checkout", branch], &dir)?;
209 }
210 config.git(&["reset", "--hard", &format!("origin/{branch}")], &dir)?;
211 return Ok(());
212 }
213 let _ = fs::create_dir_all(&dir);
214 ensure!(dir.exists(), "failed to create directory {}", dir.display());
215
216 // intentionally not doing a shallow clone since that makes
217 // incremental updates more exensive, however partial clones are a great
218 // fit since that avoids fetching old parsers (which are not very useful)
219 config.git(
220 &[
221 "clone",
222 "--single-branch",
223 "--filter=blob:none",
224 "--branch",
225 branch,
226 remote,
227 ".",
228 ],
229 &dir,
230 )
231 }
232 }
233
234 pub fn fetch(config: &Config, update_existing_grammar: bool) -> Result<()> {
235 for repo in &config.repos {
236 repo.fetch(config, update_existing_grammar)?
237 }
238 Ok(())
239 }
240
241 pub fn build_grammar(config: &Config, grammar: &str, force_rebuild: bool) -> Result<PathBuf> {
242 for repo in &config.repos {
243 if repo.has_grammar(config, grammar) {
244 build::build_grammar(grammar, &repo.dir(config).join(grammar), force_rebuild)?;
245 return Ok(repo
246 .dir(config)
247 .join(grammar)
248 .join(grammar)
249 .with_extension(LIB_EXTENSION));
250 }
251 }
252 bail!("grammar not found in any configured repository")
253 }
254
255 pub fn list_grammars(config: &Config) -> Result<Vec<PathBuf>> {
256 let mut res = Vec::new();
257 for repo in &config.repos {
258 res.append(&mut repo.list_grammars(config)?)
259 }
260 res.sort_by(|path1, path2| path1.file_name().cmp(&path2.file_name()));
261 res.dedup_by(|path1, path2| path1.file_name() == path2.file_name());
262 Ok(res)
263 }
264
265 pub fn build_all_grammars(
266 config: &Config,
267 force_rebuild: bool,
268 concurrency: Option<NonZeroUsize>,
269 ) -> Result<usize> {
270 let grammars = list_grammars(config)?;
271 let bar = ProgressBar::new(grammars.len() as u64).with_style(
272 ProgressStyle::with_template("{spinner} {bar:40.cyan/blue} {pos:>7}/{len:7} {msg}")
273 .unwrap(),
274 );
275 bar.set_message("Compiling");
276 bar.enable_steady_tick(Duration::from_millis(100));
277 let i = AtomicUsize::new(0);
278 let concurrency = concurrency
279 .or_else(|| thread::available_parallelism().ok())
280 .map_or(4, usize::from);
281 let failed = Mutex::new(Vec::new());
282 thread::scope(|scope| {
283 for _ in 0..concurrency {
284 scope.spawn(|| loop {
285 let Some(grammar) = grammars.get(i.fetch_add(1, atomic::Ordering::Relaxed)) else {
286 break;
287 };
288 let name = grammar.file_name().unwrap().to_str().unwrap();
289 if let Err(err) = build::build_grammar(name, grammar, force_rebuild) {
290 for err in err.chain() {
291 bar.println(format!("error: {err}"))
292 }
293 failed.lock().unwrap().push(name.to_owned())
294 }
295 bar.inc(1);
296 });
297 }
298 });
299 let failed = failed.into_inner().unwrap();
300 if !failed.is_empty() {
301 bail!("failed to build grammars {failed:?}")
302 }
303 Ok(grammars.len())
304 }
305
306 // TODO: version the metadata? Or allow unknown fields but warn on them?
307 #[derive(Debug, Serialize, Deserialize)]
308 #[serde(rename_all = "kebab-case", untagged)]
309 pub enum Metadata {
310 ParserDefinition(ParserDefinition),
311 ReuseParser {
312 /// The name of the grammar to reuse.
313 /// Grammars should only be reused from the same `Repo`.
314 #[serde(rename = "reuse-parser")]
315 name: String,
316 },
317 }
318
319 impl Metadata {
320 pub fn parser_definition(self) -> Option<ParserDefinition> {
321 match self {
322 Self::ParserDefinition(parser_definition) => Some(parser_definition),
323 Self::ReuseParser { .. } => None,
324 }
325 }
326
327 pub fn read(path: &Path) -> Result<Metadata> {
328 let json = fs::read_to_string(path)
329 .with_context(|| format!("couldn't read {}", path.display()))?;
330 serde_json::from_str(&json)
331 .with_context(|| format!("invalid metadata.json file at {}", path.display()))
332 }
333
334 pub fn write(&self, path: &Path) -> Result<()> {
335 let json = serde_json::to_string_pretty(&self).unwrap();
336 fs::write(path, json).with_context(|| format!("failed to write {}", path.display()))
337 }
338 }
339
340 #[derive(Debug, Serialize, Deserialize)]
341 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
342 pub struct ParserDefinition {
343 /// The git remote of the upstream grammar repository
344 pub repo: String,
345 /// The revision of the git remote when the files were imported
346 pub rev: String,
347 /// The SPDX license identifier of the upstream grammar repository
348 #[serde(default)]
349 pub license: String,
350 /// Whether the `parser.c` file is compressed
351 #[serde(default)]
352 pub compressed: bool,
353 }
354
355 // ruzstd is a bit manual, if they provided a better Reader implementation this
356 // wouldn't be necessary... they don't do that because using zstd efficiently
357 // apparently requires a seekable reader. Most readers are seekable so just
358 // adding an extra trait bound would help... oh well
359
360 /// decompresses a file compressed by skidder
361 pub fn decompress(src: &mut File, mut dst: impl Write) -> Result<()> {
362 const BATCH_SIZE: usize = 8 * 1024;
363 let size = src.metadata()?.len();
364
365 let mut src = BufReader::new(src);
366 let mut decoder = FrameDecoder::new();
367 let mut copy_buffer = [0; BATCH_SIZE];
368
369 while src.stream_position()? < size {
370 match decoder.reset(&mut src) {
371 Err(FrameDecoderError::ReadFrameHeaderError(ReadFrameHeaderError::SkipFrame {
372 length: skip_size,
373 ..
374 })) => {
375 src.seek(SeekFrom::Current(skip_size as i64)).unwrap();
376 continue;
377 }
378 other => other?,
379 }
380 while !decoder.is_finished() {
381 decoder.decode_blocks(&mut src, BlockDecodingStrategy::UptoBytes(BATCH_SIZE))?;
382 while decoder.can_collect() > BATCH_SIZE {
383 let read = decoder.read(&mut copy_buffer).unwrap();
384 assert_eq!(read, BATCH_SIZE);
385 dst.write_all(&copy_buffer)?;
386 }
387 }
388 while decoder.can_collect() != 0 {
389 let read = decoder.read(&mut copy_buffer).unwrap();
390 dst.write_all(&copy_buffer[..read])?;
391 }
392 }
393 Ok(())
394 }