valkyrie_errors/managers/
mod.rs

1use std::{
2    collections::BTreeMap,
3    fmt::{Debug, Display, Formatter},
4    fs::read_to_string,
5    ops::Range,
6    path::{Path, PathBuf},
7    sync::Arc,
8};
9
10use ariadne::{Cache, Label, Source};
11use serde::{Deserialize, Serialize};
12use url::Url;
13
14use crate::{FileID, ValkyrieResult};
15
16pub mod list;
17
18pub struct TextManager {
19    // workspace root
20    root: PathBuf,
21    max_id: FileID,
22    text_map: BTreeMap<FileID, TextItem>,
23}
24
25pub struct TextItem {
26    path: String,
27    text: Arc<String>,
28    source: Arc<Source>,
29}
30
31impl Debug for TextManager {
32    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
33        let files: Vec<&str> = self.text_map.values().map(|v| v.path.as_str()).collect();
34        f.debug_struct("TextManager").field("root", &self.root.display()).field("files", &files).finish()
35    }
36}
37
38impl TextManager {
39    pub fn new<P: AsRef<Path>>(root: P) -> Self {
40        Self { root: root.as_ref().canonicalize().unwrap(), max_id: 0, text_map: BTreeMap::default() }
41    }
42    pub fn resolve_file(&self, relative_path: &str) -> PathBuf {
43        self.root.join(&relative_path)
44    }
45    pub fn add_file(&mut self, relative_path: &str) -> ValkyrieResult<FileID> {
46        let text = read_to_string(&self.resolve_file(relative_path))?;
47        Ok(self.add_text(relative_path, text))
48    }
49    pub fn add_text(&mut self, file: impl Into<String>, text: impl Into<String>) -> FileID {
50        let text = Arc::new(text.into());
51        let source = Arc::new(Source::from(text.as_str()));
52        let id = self.max_id;
53        self.max_id += 1;
54        self.text_map.insert(id, TextItem { path: file.into(), text, source });
55        id
56    }
57    // no file and empty file is eqv
58    pub fn get_text(&self, id: FileID) -> &str {
59        match self.text_map.get(&id) {
60            Some(s) => s.text.as_ref(),
61            None => "",
62        }
63    }
64}
65
66impl Cache<FileID> for TextManager {
67    fn fetch(&mut self, id: &FileID) -> Result<&Source, Box<dyn Debug + '_>> {
68        match self.text_map.get(id) {
69            Some(s) => Ok(s.source.as_ref()),
70            None => Err(Box::new(format!("FileID `{}` not found", id))),
71        }
72    }
73
74    fn display<'a>(&self, id: &'a FileID) -> Option<Box<dyn Display + 'a>> {
75        let item = self.text_map.get(id)?;
76        let url = Url::from_file_path(&self.root.join(&item.path)).ok()?;
77        Some(Box::new(url))
78    }
79}