1mod review;
4
5pub use review::{Address, ReviewScope, review_checkout, review_scope};
6
7use std::{
8 fs::File,
9 path::{Path, PathBuf},
10};
11
12use artifactize_tools::scope::{self, InputPath};
13use serde::Serialize;
14
15use crate::{
16 config::{
17 self, Artifact, ArtifactKind, PluginName, RepoConfig,
18 plugins::{BuiltinViewer, ViewerEntry},
19 },
20 graph_structure, platform, repository,
21 types::{ArtifactName, RequestId, ReviewerId},
22};
23
24#[derive(Debug, Clone)]
27pub struct Session {
28 root: PathBuf,
29 checkout: repository::Identity,
30 artifact: Artifact,
31 tool: config::ToolFqn,
33 plugin: PluginName,
34 title: String,
35 entry: ViewerEntry,
36}
37
38#[derive(Debug, Clone, Default, PartialEq, Eq)]
40pub struct Scope {
41 nested: std::collections::BTreeMap<config::ChildPrefix, ArtifactName>,
42 covering_part: Option<ArtifactName>,
43}
44
45#[derive(Debug, Clone)]
46pub struct Review {
47 pub id: RequestId,
48 pub reviewer: ReviewerId,
49}
50
51#[derive(Debug, Serialize)]
52#[serde(rename_all = "camelCase")]
53pub struct Context<'a> {
54 pub artifact: &'a ArtifactName,
55 #[serde(rename = "type")]
56 pub type_name: &'a PluginName,
57 pub title: &'a str,
58 pub target: &'a config::Target,
59 pub target_kind: ArtifactKind,
60 pub review: Option<&'a RequestId>,
61}
62
63#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
64#[serde(rename_all = "lowercase")]
65pub enum EntryKind {
66 File,
67 Directory,
68}
69
70#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
71pub struct FileEntry {
72 pub name: String,
73 pub path: InputPath,
74 pub kind: EntryKind,
75}
76
77impl Session {
78 pub fn open(
79 repo: &Path,
80 artifact: &ArtifactName,
81 tool: &config::ToolFqn,
82 ) -> Result<Self, String> {
83 let config = config::read_workspace_config(repo).map_err(|error| error.to_string())?;
84 Self::from_config(&config, artifact, tool)
85 }
86
87 pub(crate) fn from_config(
88 config: &RepoConfig,
89 artifact: &ArtifactName,
90 tool: &config::ToolFqn,
91 ) -> Result<Self, String> {
92 let artifact = config
93 .artifacts
94 .get(artifact)
95 .ok_or_else(|| format!("Unknown Artifact {artifact}."))?;
96 let Some(config::HumanTool::Viewer(viewer)) = artifact.views.human_tools.get(tool) else {
97 return Err(format!(
98 "Artifact {} has no viewer tool {tool}.",
99 artifact.name
100 ));
101 };
102 let plugin = config
103 .plugins
104 .get(&viewer.plugin)
105 .ok_or_else(|| format!("Plugin {} is not installed.", viewer.plugin))?;
106 let entry = plugin
107 .viewer
108 .clone()
109 .ok_or_else(|| format!("Plugin {} has no viewer.", viewer.plugin))?;
110 crate::scope::validate_file_target(&config.root, artifact)
111 .map_err(|error| error.to_string())?;
112 Ok(Self {
113 root: config.root.clone(),
114 checkout: repository::identify(&config.root),
115 artifact: artifact.clone(),
116 tool: tool.clone(),
117 plugin: plugin.info.name.clone(),
118 title: plugin.info.title.clone(),
119 entry,
120 })
121 }
122
123 pub fn tool(&self) -> &config::ToolFqn {
125 &self.tool
126 }
127
128 pub fn scope(&self) -> Scope {
129 Scope {
130 nested: self.artifact.nested.clone(),
131 covering_part: self.artifact.covering_part.clone(),
132 }
133 }
134
135 pub fn workspace(&self) -> &Path {
136 &self.root
137 }
138
139 pub fn checkout(&self) -> &repository::Identity {
140 &self.checkout
141 }
142
143 pub fn check_checkout(&self) -> Result<(), String> {
145 check_checkout(&self.root, &self.checkout)
146 }
147
148 pub fn check_scope(&self) -> Result<(), String> {
150 self.check_checkout()?;
151 let config =
152 config::read_workspace_config(&self.root).map_err(|error| error.to_string())?;
153 if config
154 .artifacts
155 .get(&self.artifact.name)
156 .is_some_and(|current| {
157 current.path == self.artifact.path
158 && matches!(
159 current.views.human_tools.get(&self.tool),
160 Some(config::HumanTool::Viewer(viewer)) if viewer.plugin == self.plugin
161 )
162 && current.nested == self.artifact.nested
163 && current.covering_part == self.artifact.covering_part
164 })
165 {
166 Ok(())
167 } else {
168 Err("This Artifact's viewer scope has changed. Reopen the viewer.".into())
169 }
170 }
171
172 pub fn entry(&self) -> &ViewerEntry {
173 &self.entry
174 }
175
176 pub fn context<'a>(&'a self, review: Option<&'a Review>) -> Context<'a> {
177 Context {
178 artifact: &self.artifact.name,
179 type_name: &self.plugin,
180 title: &self.title,
181 target: &self.artifact.path,
182 target_kind: self.artifact.kind(),
183 review: review.map(|review| &review.id),
184 }
185 }
186
187 pub async fn pointing(
189 &self,
190 state: &Path,
191 review: &Review,
192 text: &str,
193 ) -> Result<crate::review::Draft, String> {
194 let session = self.clone();
195 crate::task::blocking(move || session.check_scope()).await??;
196 let context = self.context(None);
197 let source = format!("{} ยท {}", context.artifact, context.title);
198 crate::review::append_point(state, &review.id, &review.reviewer, text, &source).await
199 }
200
201 pub fn read_text(&self, path: &InputPath) -> Result<String, String> {
202 self.check_scope()?;
203 let path = self
204 .artifact
205 .file_name()
206 .filter(|_| path.as_str().is_empty())
207 .unwrap_or(path.as_str());
208 config::plugins::read_document(self.open_file(path)?)
209 }
210
211 pub fn files(&self, path: &InputPath) -> Result<Vec<FileEntry>, String> {
214 self.check_scope()?;
215 let path = path.as_str();
216 if path.is_empty()
217 && let Some(name) = self.artifact.file_name()
218 {
219 self.open_file(name)?;
220 return Ok(vec![FileEntry {
221 name: name.into(),
222 path: name
223 .parse()
224 .map_err(|error: scope::ScopeError| error.to_string())?,
225 kind: EntryKind::File,
226 }]);
227 }
228 let directory = self.open_file(path)?;
229 let mut entries = Vec::new();
230 for entry in platform::read_dir(&directory).map_err(|error| error.to_string())? {
231 let entry = entry.map_err(|error| error.to_string())?;
232 let name = entry.file_name();
233 let Some(name) = platform::os_text(&name) else {
234 continue;
235 };
236 let child = if path.is_empty() {
237 name.to_owned()
238 } else {
239 format!("{path}/{name}")
240 };
241 let Ok(child_path) = child.parse::<InputPath>() else {
242 continue;
243 };
244 let kind = match entry.file_type().map_err(|error| error.to_string())? {
245 platform::FileKind::File => EntryKind::File,
246 platform::FileKind::Directory => EntryKind::Directory,
247 _ => continue,
248 };
249 if self.open_file(child_path.as_str()).is_ok() {
250 entries.push(FileEntry {
251 name: name.into(),
252 path: child_path,
253 kind,
254 });
255 }
256 }
257 entries.sort_by(|left, right| left.path.cmp(&right.path));
258 Ok(entries)
259 }
260
261 pub fn declaration_view(&self) -> Result<DeclarationView, String> {
264 let result = self.declarations().map(DeclarationView::from);
265 crate::platform::release_free_memory();
266 result
267 }
268
269 pub fn declarations(&self) -> Result<graph_structure::Structure, String> {
270 self.check_scope()?;
271 if !matches!(
272 self.entry,
273 ViewerEntry::Builtin {
274 viewer: BuiltinViewer::Artifactize
275 }
276 ) {
277 return Err("Only an Artifactize Viewer can read the declared graph.".into());
278 }
279 graph_structure::read_scoped(&self.root, &self.artifact)
280 }
281
282 fn open_file(&self, path: &str) -> Result<File, String> {
283 if self.artifact.covering_part.is_some() {
284 return Err("This Artifact's files belong to a folder part.".into());
285 }
286 scope::open_input(&self.root, &self.artifact.tool_scope(), path)
287 .map_err(|error| error.to_string())
288 }
289}
290
291pub struct DeclarationView {
292 pub nodes: Vec<DeclarationNode>,
293 pub edges: Vec<(String, String)>,
294}
295
296pub struct DeclarationNode {
297 pub name: String,
298 pub tools: String,
299 pub evals: Vec<DeclarationEval>,
300}
301
302pub struct DeclarationEval {
303 pub id: String,
304 pub kind: crate::config::ProfileKind,
305 pub title: String,
306 pub criteria: Option<String>,
307 pub reads: Vec<String>,
308}
309
310impl From<graph_structure::Structure> for DeclarationView {
311 fn from(graph: graph_structure::Structure) -> Self {
312 use crate::{config::ProfileKind, graph_structure::Criteria};
313 let mut by_target = std::collections::BTreeMap::<_, Vec<_>>::new();
314 for (id, eval) in graph.evals {
315 let (kind, command) = match eval.criteria {
316 Criteria::Agent { .. } => (ProfileKind::Agent, None),
317 Criteria::Human => (ProfileKind::Human, None),
318 Criteria::Runtime { command, .. } => (ProfileKind::Runtime, Some(command)),
319 };
320 by_target
321 .entry(eval.target)
322 .or_default()
323 .push(DeclarationEval {
324 id: id.to_string(),
325 kind,
326 title: eval.title,
327 criteria: eval.instruction.or(command),
328 reads: eval
329 .reads
330 .into_iter()
331 .map(|name| name.to_string())
332 .collect(),
333 });
334 }
335 let edges = graph
336 .relations
337 .into_iter()
338 .filter(|edge| {
339 edge.source != edge.target
340 && graph.artifacts.contains_key(&edge.source)
341 && graph.artifacts.contains_key(&edge.target)
342 })
343 .map(|edge| (edge.source.to_string(), edge.target.to_string()))
344 .collect::<std::collections::BTreeSet<_>>()
345 .into_iter()
346 .collect();
347 let nodes = graph
348 .artifacts
349 .into_iter()
350 .map(|(name, artifact)| DeclarationNode {
351 name: name.to_string(),
352 tools: artifact.toolsets.join(" & "),
353 evals: by_target.remove(&name).unwrap_or_default(),
354 })
355 .collect();
356 Self { nodes, edges }
357 }
358}
359
360fn check_checkout(worktree: &Path, checkout: &repository::Identity) -> Result<(), String> {
361 if worktree.is_dir() && repository::identify(worktree) == *checkout {
362 Ok(())
363 } else {
364 Err("This Artifact Viewer's checkout changed. Reopen the viewer.".into())
365 }
366}