Skip to main content

artifactize_core/
viewer.rs

1//! The desktop hosts a viewer; this library decides what its bridge can read.
2
3use std::{
4    fs::File,
5    path::{Path, PathBuf},
6};
7
8use artifactize_tools::scope::{self, InputPath};
9use serde::Serialize;
10
11use crate::{
12    config::{
13        self, Artifact, ArtifactKind, ArtifactType, RepoConfig,
14        plugins::{BuiltinViewer, ViewerEntry},
15    },
16    graph_structure, platform, repository,
17    types::{ArtifactName, RequestId, ReviewerId},
18};
19
20/// Relative file reads and directory listings use the selected Artifact's own scope, not the
21/// workspace or the rest of the review's scope. A viewer cannot choose its own scope.
22#[derive(Debug, Clone)]
23pub struct Session {
24    root: PathBuf,
25    checkout: repository::Identity,
26    artifact: Artifact,
27    entry: ViewerEntry,
28}
29
30/// The ownership boundaries that can change while the Artifact's target remains the same.
31#[derive(Debug, Clone, Default, PartialEq, Eq)]
32pub struct Scope {
33    nested: std::collections::BTreeMap<config::ChildPrefix, ArtifactName>,
34    covering_part: Option<ArtifactName>,
35}
36
37#[derive(Debug, Clone)]
38pub struct Review {
39    pub id: RequestId,
40    pub reviewer: ReviewerId,
41}
42
43#[derive(Debug, Serialize)]
44#[serde(rename_all = "camelCase")]
45pub struct Context<'a> {
46    pub artifact: &'a ArtifactName,
47    #[serde(rename = "type")]
48    pub type_name: &'a ArtifactType,
49    pub title: &'a str,
50    pub target: &'a config::Target,
51    pub target_kind: ArtifactKind,
52    pub review: Option<&'a RequestId>,
53}
54
55#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
56#[serde(rename_all = "lowercase")]
57pub enum EntryKind {
58    File,
59    Directory,
60}
61
62#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
63pub struct FileEntry {
64    pub name: String,
65    pub path: InputPath,
66    pub kind: EntryKind,
67}
68
69impl Session {
70    pub fn open(repo: &Path, artifact: &ArtifactName) -> Result<Self, String> {
71        let config = config::read_workspace_config(repo).map_err(|error| error.to_string())?;
72        Self::from_config(&config, artifact)
73    }
74
75    pub(crate) fn from_config(
76        config: &RepoConfig,
77        artifact: &ArtifactName,
78    ) -> Result<Self, String> {
79        let artifact = config
80            .artifacts
81            .get(artifact)
82            .ok_or_else(|| format!("Unknown Artifact {artifact}."))?;
83        let entry = artifact
84            .plugin
85            .as_ref()
86            .and_then(|plugin| plugin.viewer.clone())
87            .ok_or_else(|| format!("Artifact {} does not declare a viewer.", artifact.name))?;
88        if !artifact
89            .views
90            .human_tools
91            .values()
92            .any(|tool| tool.kind() == config::HumanToolKind::Viewer)
93        {
94            return Err(format!(
95                "Artifact {} has no viewer Human tool.",
96                artifact.name
97            ));
98        }
99        crate::scope::validate_file_target(&config.root, artifact)
100            .map_err(|error| error.to_string())?;
101        Ok(Self {
102            root: config.root.clone(),
103            checkout: repository::identify(&config.root),
104            artifact: artifact.clone(),
105            entry,
106        })
107    }
108
109    pub fn scope(&self) -> Scope {
110        Scope {
111            nested: self.artifact.nested.clone(),
112            covering_part: self.artifact.covering_part.clone(),
113        }
114    }
115
116    pub fn workspace(&self) -> &Path {
117        &self.root
118    }
119
120    pub fn checkout(&self) -> &repository::Identity {
121        &self.checkout
122    }
123
124    /// The same path may later hold different branch contents and must not be reused.
125    pub fn check_checkout(&self) -> Result<(), String> {
126        check_checkout(&self.root, &self.checkout)
127    }
128
129    /// An already-open viewer's scope cannot authorize access after a declaration changes.
130    pub fn check_scope(&self) -> Result<(), String> {
131        self.check_checkout()?;
132        let config =
133            config::read_workspace_config(&self.root).map_err(|error| error.to_string())?;
134        if config
135            .artifacts
136            .get(&self.artifact.name)
137            .is_some_and(|current| {
138                current.path == self.artifact.path
139                    && current.type_name == self.artifact.type_name
140                    && current.nested == self.artifact.nested
141                    && current.covering_part == self.artifact.covering_part
142            })
143        {
144            Ok(())
145        } else {
146            Err("This Artifact's viewer scope has changed. Reopen the viewer.".into())
147        }
148    }
149
150    pub fn entry(&self) -> &ViewerEntry {
151        &self.entry
152    }
153
154    pub fn context<'a>(&'a self, review: Option<&'a Review>) -> Context<'a> {
155        let plugin = self.artifact.plugin.as_ref().expect("viewer has a plugin");
156        Context {
157            artifact: &self.artifact.name,
158            type_name: &plugin.info.name,
159            title: &plugin.info.title,
160            target: &self.artifact.path,
161            target_kind: self.artifact.kind(),
162            review: review.map(|review| &review.id),
163        }
164    }
165
166    /// Append a Point to the host-selected review; the store rechecks its claim atomically.
167    pub async fn pointing(
168        &self,
169        state: &Path,
170        review: &Review,
171        text: &str,
172    ) -> Result<crate::review::Draft, String> {
173        let session = self.clone();
174        crate::task::blocking(move || session.check_scope()).await??;
175        let context = self.context(None);
176        let source = format!("{} ยท {}", context.artifact, context.title);
177        crate::review::append_point(state, &review.id, &review.reviewer, text, &source).await
178    }
179
180    pub fn read_text(&self, path: &InputPath) -> Result<String, String> {
181        self.check_scope()?;
182        let path = self
183            .artifact
184            .file_name()
185            .filter(|_| path.as_str().is_empty())
186            .unwrap_or(path.as_str());
187        config::plugins::read_document(self.open_file(path)?)
188    }
189
190    /// Read one directory at a time. Never list non-owned siblings of a file Artifact or
191    /// directories outside an aspect's selection.
192    pub fn files(&self, path: &InputPath) -> Result<Vec<FileEntry>, String> {
193        self.check_scope()?;
194        let path = path.as_str();
195        if path.is_empty()
196            && let Some(name) = self.artifact.file_name()
197        {
198            self.open_file(name)?;
199            return Ok(vec![FileEntry {
200                name: name.into(),
201                path: name
202                    .parse()
203                    .map_err(|error: scope::ScopeError| error.to_string())?,
204                kind: EntryKind::File,
205            }]);
206        }
207        let directory = self.open_file(path)?;
208        let mut entries = Vec::new();
209        for entry in platform::read_dir(&directory).map_err(|error| error.to_string())? {
210            let entry = entry.map_err(|error| error.to_string())?;
211            let name = entry.file_name();
212            let Some(name) = platform::os_text(&name) else {
213                continue;
214            };
215            let child = if path.is_empty() {
216                name.to_owned()
217            } else {
218                format!("{path}/{name}")
219            };
220            let Ok(child_path) = child.parse::<InputPath>() else {
221                continue;
222            };
223            let kind = match entry.file_type().map_err(|error| error.to_string())? {
224                platform::FileKind::File => EntryKind::File,
225                platform::FileKind::Directory => EntryKind::Directory,
226                _ => continue,
227            };
228            if self.open_file(child_path.as_str()).is_ok() {
229                entries.push(FileEntry {
230                    name: name.into(),
231                    path: child_path,
232                    kind,
233                });
234            }
235        }
236        entries.sort_by(|left, right| left.path.cmp(&right.path));
237        Ok(entries)
238    }
239
240    pub fn declarations(&self) -> Result<graph_structure::Structure, String> {
241        self.check_scope()?;
242        if !matches!(
243            self.entry,
244            ViewerEntry::Builtin {
245                viewer: BuiltinViewer::Artifactize
246            }
247        ) {
248            return Err("Only an Artifactize Viewer can read the declared graph.".into());
249        }
250        graph_structure::read_scoped(&self.root, &self.artifact)
251    }
252
253    fn open_file(&self, path: &str) -> Result<File, String> {
254        if self.artifact.covering_part.is_some() {
255            return Err("This Artifact's files belong to a folder part.".into());
256        }
257        scope::open_input(&self.root, &self.artifact.tool_scope(), path)
258            .map_err(|error| error.to_string())
259    }
260}
261
262fn check_checkout(worktree: &Path, checkout: &repository::Identity) -> Result<(), String> {
263    if worktree.is_dir() && repository::identify(worktree) == *checkout {
264        Ok(())
265    } else {
266        Err("This Artifact Viewer's checkout changed. Reopen the viewer.".into())
267    }
268}