Skip to main content

vvv_engine/
workspace.rs

1//! A root directory viewed through a [`Vfs`].
2
3use std::path::{Path, PathBuf};
4use std::sync::{Arc, OnceLock};
5
6use crate::{DiskVfs, Overlay, Vfs, VfsError};
7use vvv_core::{RelPath, SourceText};
8
9use crate::plan::{ApplyError, Fingerprint};
10
11#[derive(Clone)]
12pub struct Workspace {
13    root: PathBuf,
14    vfs: Arc<dyn Vfs>,
15    execution: bool,
16}
17
18impl Workspace {
19    /// The tree under `root` on disk, `root` made absolute.
20    pub fn disk(root: impl AsRef<Path>) -> Result<Self, VfsError> {
21        let root = root.as_ref();
22        let root = root.canonicalize().map_err(|source| VfsError::Io {
23            path: root.to_path_buf(),
24            source,
25        })?;
26        Ok(Self {
27            root,
28            vfs: Arc::new(DiskVfs::new()),
29            execution: true,
30        })
31    }
32
33    pub fn new(root: impl Into<PathBuf>, vfs: Arc<dyn Vfs>) -> Self {
34        Self {
35            root: root.into(),
36            vfs,
37            execution: false,
38        }
39    }
40
41    /// This workspace as a plan would leave it: the same root over an
42    /// overlay of its file system. Writes land in the overlay; the real
43    /// files are untouched until a plan is applied here.
44    pub fn staged(&self) -> Workspace {
45        Workspace::new(self.root.clone(), Arc::new(Overlay::over(self.vfs.clone())))
46    }
47
48    pub(crate) fn execution_root(&self) -> Option<&Path> {
49        self.execution.then_some(&self.root)
50    }
51
52    pub fn root(&self) -> &Path {
53        &self.root
54    }
55
56    pub fn vfs(&self) -> &dyn Vfs {
57        self.vfs.as_ref()
58    }
59
60    pub fn files(&self) -> Result<Vec<PathBuf>, VfsError> {
61        self.vfs.walk(&self.root)
62    }
63
64    /// Load a file given either an absolute path or one relative to the root.
65    pub fn load(&self, path: &Path) -> Result<SourceFile, VfsError> {
66        let text = self.vfs.read(&self.absolute(path))?;
67        Ok(SourceFile::new(self.relative(path), text))
68    }
69
70    /// A user-supplied path (absolute, `./x`, `a/../b`) as a clean root-relative path.
71    pub fn normalize(&self, path: &Path) -> PathBuf {
72        let mut out = PathBuf::new();
73        for component in self.absolute(path).components() {
74            match component {
75                std::path::Component::CurDir => {}
76                std::path::Component::ParentDir => {
77                    out.pop();
78                }
79                other => out.push(other),
80            }
81        }
82        self.relative(&out)
83    }
84
85    /// Path as handed to the [`Vfs`].
86    pub fn absolute(&self, path: &Path) -> PathBuf {
87        if path.is_absolute() {
88            path.to_path_buf()
89        } else {
90            self.root.join(path)
91        }
92    }
93
94    /// Path as shown to users: relative to the root when possible.
95    pub fn relative(&self, path: &Path) -> PathBuf {
96        path.strip_prefix(&self.root)
97            .map(Path::to_path_buf)
98            .unwrap_or_else(|_| path.to_path_buf())
99    }
100}
101
102impl std::fmt::Debug for Workspace {
103    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104        f.debug_struct("Workspace")
105            .field("root", &self.root)
106            .finish_non_exhaustive()
107    }
108}
109
110/// A loaded file, addressed by its workspace-relative path.
111#[derive(Debug, Clone)]
112pub struct SourceFile {
113    path: PathBuf,
114    source: SourceText,
115    witness: OnceLock<SourceWitness>,
116}
117
118impl SourceFile {
119    /// Bind plugin facts to this source before any caller reads their coordinates.
120    pub(crate) fn facts(
121        &self,
122        language: &dyn vvv_core::Language,
123    ) -> Result<vvv_core::Facts, vvv_core::SearchError> {
124        let facts = language.facts(self.text())?;
125        facts.validate_in(self.text())?;
126        Ok(facts)
127    }
128
129    pub(crate) fn find(
130        &self,
131        language: &dyn vvv_core::Language,
132        query: &vvv_core::Query,
133    ) -> Result<Vec<vvv_core::RawMatch>, vvv_core::SearchError> {
134        let matches = language.find(self.text(), query)?;
135        for matched in &matches {
136            matched.validate_in(self.text())?;
137        }
138        Ok(matches)
139    }
140    pub fn new(path: impl Into<PathBuf>, text: impl Into<SourceText>) -> Self {
141        Self {
142            path: path.into(),
143            source: text.into(),
144            witness: OnceLock::new(),
145        }
146    }
147
148    pub fn path(&self) -> &Path {
149        &self.path
150    }
151
152    /// The identity of the immutable text from which edits are computed.
153    pub(crate) fn witness(&self) -> &SourceWitness {
154        self.witness.get_or_init(|| SourceWitness {
155            path: self.path().into(),
156            fingerprint: Fingerprint::of(self.text()),
157        })
158    }
159
160    pub fn content_id(&self) -> crate::ContentId {
161        crate::ContentId::from_fingerprint(self.witness().fingerprint())
162    }
163
164    pub fn source(&self) -> &SourceText {
165        &self.source
166    }
167
168    pub fn text(&self) -> &str {
169        self.source.as_str()
170    }
171}
172
173/// A file path paired with the content identity of one observed snapshot.
174#[derive(Debug, Clone, PartialEq, Eq)]
175pub(crate) struct SourceWitness {
176    path: RelPath,
177    fingerprint: Fingerprint,
178}
179
180impl SourceWitness {
181    pub fn path(&self) -> &Path {
182        &self.path
183    }
184
185    pub fn fingerprint(&self) -> &Fingerprint {
186        &self.fingerprint
187    }
188
189    pub fn check(&self, other: &Self) -> Result<(), ApplyError> {
190        if self != other {
191            return Err(ApplyError::Stale {
192                path: self.path.clone(),
193            });
194        }
195        Ok(())
196    }
197}