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
use std::{
collections::BTreeMap,
fmt::{Debug, Display, Formatter},
fs::read_to_string,
ops::Range,
path::{Path, PathBuf},
sync::Arc,
};
use ariadne::{Cache, Label, Source};
use url::Url;
use crate::{FileID, ValkyrieResult};
pub mod list;
pub struct TextManager {
root: PathBuf,
max_id: FileID,
text_map: BTreeMap<FileID, TextItem>,
}
pub struct TextItem {
path: String,
source: Arc<Source>,
}
impl Debug for TextManager {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let files: Vec<&str> = self.text_map.values().map(|v| v.path.as_str()).collect();
f.debug_struct("TextManager").field("root", &self.root.display()).field("files", &files).finish()
}
}
impl TextManager {
pub fn new<P: AsRef<Path>>(root: P) -> Self {
Self { root: root.as_ref().canonicalize().unwrap(), max_id: 0, text_map: BTreeMap::default() }
}
pub fn add_file(&mut self, relative_path: &str) -> ValkyrieResult<FileID> {
let file = self.root.join(&relative_path);
let text = read_to_string(&file)?;
Ok(self.add_text(relative_path, text))
}
pub fn add_text(&mut self, file: impl Into<String>, text: impl Into<String>) -> FileID {
let id = self.max_id;
self.max_id += 1;
self.text_map.insert(id, TextItem { path: file.into(), source: Arc::new(Source::from(text.into())) });
id
}
pub fn get_text(&self, id: FileID) -> String {
match self.text_map.get(&id) {
Some(s) => s.source.chars().collect(),
None => String::new(),
}
}
}
impl Cache<FileID> for TextManager {
fn fetch(&mut self, id: &FileID) -> Result<&Source, Box<dyn Debug + '_>> {
match self.text_map.get(id) {
Some(s) => Ok(s.source.as_ref()),
None => Err(Box::new(format!("FileID `{}` not found", id))),
}
}
fn display<'a>(&self, id: &'a FileID) -> Option<Box<dyn Display + 'a>> {
let item = self.text_map.get(id)?;
let url = Url::from_file_path(&self.root.join(&item.path)).ok()?;
Some(Box::new(url))
}
}