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<crate::scope::Instruction>,
308 pub reads: Vec<String>,
309}
310
311impl From<graph_structure::Structure> for DeclarationView {
312 fn from(graph: graph_structure::Structure) -> Self {
313 use crate::{config::ProfileKind, graph_structure::Criteria};
314 let mut by_target = std::collections::BTreeMap::<_, Vec<_>>::new();
315 for (id, eval) in graph.evals {
316 let (kind, command) = match eval.criteria {
317 Criteria::Agent { .. } => (ProfileKind::Agent, None),
318 Criteria::Human => (ProfileKind::Human, None),
319 Criteria::Runtime { command, .. } => (ProfileKind::Runtime, Some(command)),
320 };
321 by_target
322 .entry(eval.target)
323 .or_default()
324 .push(DeclarationEval {
325 id: id.to_string(),
326 kind,
327 title: eval.title,
328 criteria: if eval.instruction.is_some() {
329 Some(eval.shown_instruction)
330 } else {
331 command.map(crate::scope::Instruction::text)
332 },
333 reads: eval
334 .reads
335 .into_iter()
336 .map(|name| name.to_string())
337 .collect(),
338 });
339 }
340 let edges = graph
341 .relations
342 .into_iter()
343 .filter(|edge| {
344 edge.source != edge.target
345 && graph.artifacts.contains_key(&edge.source)
346 && graph.artifacts.contains_key(&edge.target)
347 })
348 .map(|edge| (edge.source.to_string(), edge.target.to_string()))
349 .collect::<std::collections::BTreeSet<_>>()
350 .into_iter()
351 .collect();
352 let nodes = graph
353 .artifacts
354 .into_iter()
355 .map(|(name, artifact)| DeclarationNode {
356 name: name.to_string(),
357 tools: artifact.toolsets.join(" & "),
358 evals: by_target.remove(&name).unwrap_or_default(),
359 })
360 .collect();
361 Self { nodes, edges }
362 }
363}
364
365fn check_checkout(worktree: &Path, checkout: &repository::Identity) -> Result<(), String> {
366 if worktree.is_dir() && repository::identify(worktree) == *checkout {
367 Ok(())
368 } else {
369 Err("This Artifact Viewer's checkout changed. Reopen the viewer.".into())
370 }
371}