Skip to main content

artifactize_core/monitor/
live.rs

1//! The live branches of every project with Runs on this machine, as the desktop's pane lists
2//! them: each Git worktree that exists now with the branch it has checked out (a detached one by
3//! its folder), and each folder outside Git that exists now and holds declarations. A branch's
4//! Runs are its project's Runs on that branch, from whichever folder they ran in; who ran them
5//! makes no branch of its own. The terminal monitor keeps its own catalog of scopes.
6mod current;
7mod loader;
8mod query;
9mod starred;
10mod waiting;
11
12#[cfg(test)]
13mod tests;
14
15pub use current::{Current, CurrentArtifact, CurrentEdge, CurrentEval, Plan, scan};
16pub use loader::{Input, Loader, OpenRun, Opened, Snapshot};
17pub use query::{DEFAULT, Query, Sort, complete, show};
18pub use starred::{star, star_artifact, starred, starred_artifacts};
19pub use waiting::{Waiting, waiting};
20
21use crate::{
22    platform::{FileIdentity, paths},
23    repository::{self, Identity, Worktree},
24    store::CatalogRun,
25    types::{RunId, RunStatus, Timestamp},
26};
27use serde::{Deserialize, Serialize};
28use std::{
29    collections::{BTreeMap, BTreeSet},
30    path::{Path, PathBuf},
31};
32
33/// A branch's name as Git accepts one: not empty, and none of the characters or sequences
34/// `git check-ref-format --branch` refuses. Made at the Git and serde boundaries, so no other
35/// name becomes a branch's key.
36#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
37#[serde(try_from = "String", into = "String")]
38pub struct BranchName(String);
39
40impl BranchName {
41    pub fn as_str(&self) -> &str {
42        &self.0
43    }
44}
45
46impl TryFrom<String> for BranchName {
47    type Error = String;
48
49    fn try_from(name: String) -> Result<Self, String> {
50        // Each `/`-separated part is a name of its own: not empty, not starting with `.`, not
51        // ending with `.lock`.
52        let refused = name.starts_with('-')
53            || name.ends_with('.')
54            || name == "@"
55            || name.contains("..")
56            || name.contains("@{")
57            || name
58                .split('/')
59                .any(|part| part.is_empty() || part.starts_with('.') || part.ends_with(".lock"))
60            || name.chars().any(|c| {
61                c.is_control() || matches!(c, ' ' | '~' | '^' | ':' | '?' | '*' | '[' | '\\')
62            });
63        if refused {
64            Err(format!("not a branch name: {name:?}"))
65        } else {
66            Ok(Self(name))
67        }
68    }
69}
70
71impl From<BranchName> for String {
72    fn from(name: BranchName) -> Self {
73        name.0
74    }
75}
76
77impl std::fmt::Display for BranchName {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        f.write_str(&self.0)
80    }
81}
82
83/// How a Git worktree has its project checked out.
84#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
85#[serde(rename_all = "camelCase")]
86pub enum Head {
87    Branch(BranchName),
88    /// A detached worktree, known by its folder.
89    Detached(#[serde(with = "crate::platform::path_serde")] PathBuf),
90}
91
92/// Where a branch lives: a Git repository's checked-out branch, by the repository's common
93/// directory, or a folder outside Git.
94#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
95#[serde(rename_all = "camelCase")]
96pub enum Place {
97    Git {
98        #[serde(with = "crate::platform::path_serde")]
99        common: PathBuf,
100        head: Head,
101    },
102    Folder(#[serde(with = "crate::platform::path_serde")] PathBuf),
103}
104
105impl Place {
106    /// The project the branch belongs to: every branch of a Git repository shares one.
107    pub fn project(&self) -> Project {
108        match self {
109            Self::Git { common, .. } => Project::Git(common.clone()),
110            Self::Folder(path) => Project::Folder(path.clone()),
111        }
112    }
113}
114
115/// A project: a Git repository, by its common directory, or a folder outside Git.
116#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
117#[serde(rename_all = "camelCase")]
118pub enum Project {
119    Git(#[serde(with = "crate::platform::path_serde")] PathBuf),
120    Folder(#[serde(with = "crate::platform::path_serde")] PathBuf),
121}
122
123/// One Run of a branch as its chip shows it.
124#[derive(Debug, Clone, PartialEq, Eq)]
125pub struct Chip {
126    pub id: RunId,
127    pub status: RunStatus,
128    pub created_at: Timestamp,
129    pub completed_at: Option<Timestamp>,
130    /// What the requester said it is working on (`verify --comment`).
131    pub comment: Option<crate::types::RunComment>,
132}
133
134/// A live branch and its Runs.
135#[derive(Debug, Clone, PartialEq, Eq)]
136pub struct Branch {
137    pub place: Place,
138    /// The project's name: its repository's or folder's.
139    pub project: String,
140    /// The branch, a detached worktree's folder name, or empty for a folder outside Git.
141    pub name: String,
142    /// Where its Current is scanned and its Artifacts' tools run: the worktree (or folder) as it
143    /// is now, at the workspace its newest Run used (or the app was started for) within it.
144    pub workspace: PathBuf,
145    /// Its Runs, oldest first.
146    pub runs: Vec<Chip>,
147}
148
149impl Branch {
150    /// The Run in progress a branch's timeline starts with: the newest Run, while it runs.
151    pub fn running(&self) -> Option<&Chip> {
152        self.runs.last().filter(|chip| chip.status.is_open())
153    }
154
155    /// When its newest Run started.
156    pub fn latest(&self) -> Option<Timestamp> {
157        self.runs.last().map(|chip| chip.created_at)
158    }
159}
160
161/// Which project and branch a saved Run ran on, by name, for every Run whether or not its
162/// branch still lives: what a waiting review of it is listed with.
163#[derive(Debug, Clone, Default, PartialEq, Eq)]
164pub struct Label {
165    pub project: String,
166    pub branch: String,
167}
168
169pub type Labels = BTreeMap<RunId, Label>;
170
171/// Cached Git facts. Identities of old Run records without a saved identity are asked of Git
172/// once; which worktrees exist is asked again on every [`Discovery::rescan`].
173#[derive(Default)]
174pub struct Discovery {
175    identities: BTreeMap<PathBuf, Identity>,
176    trees: BTreeMap<PathBuf, Vec<Worktree>>,
177}
178
179impl Discovery {
180    /// Ask Git again which worktrees exist, on the next listing.
181    pub fn rescan(&mut self) {
182        self.trees.clear();
183    }
184
185    fn identify(&mut self, path: &Path) -> Identity {
186        self.identities
187            .entry(path.to_path_buf())
188            .or_insert_with(|| repository::identify(path))
189            .clone()
190    }
191
192    /// Whether `path` is a folder now.
193    fn is_folder(&self, path: &Path) -> bool {
194        path.is_dir()
195    }
196
197    /// Whether the folder `path` holds declarations.
198    fn declares(&self, path: &Path) -> bool {
199        crate::workspace::has_artifact_marker(path).unwrap_or(false)
200    }
201
202    fn worktrees(&mut self, common: &Path) -> Vec<Worktree> {
203        self.trees
204            .entry(common.to_path_buf())
205            .or_insert_with(|| {
206                repository::worktrees(common)
207                    .into_iter()
208                    .map(|tree| Worktree {
209                        // Saved identities are canonical; a detached head is matched by path.
210                        path: crate::platform::canonicalize(&tree.path).unwrap_or(tree.path),
211                        branch: tree.branch,
212                    })
213                    .collect()
214            })
215            .clone()
216    }
217}
218
219/// Pick one usable spelling per physical directory for this listing. Read each distinct
220/// saved spelling only once, even if many Runs were saved from it.
221#[derive(Default)]
222struct DirectoryKeys {
223    by_path: BTreeMap<PathBuf, PathBuf>,
224    by_identity: BTreeMap<FileIdentity, PathBuf>,
225}
226
227impl DirectoryKeys {
228    fn resolve(&mut self, path: &Path) -> PathBuf {
229        if let Some(key) = self.by_path.get(path) {
230            return key.clone();
231        }
232        let key = paths::directory_identity(path).map_or_else(
233            |_| path.to_owned(),
234            |(id, canonical)| self.by_identity.entry(id).or_insert(canonical).clone(),
235        );
236        self.by_path.insert(path.to_owned(), key.clone());
237        key
238    }
239
240    fn head(&mut self, branch: Option<String>, tree: &Path) -> Head {
241        branch
242            .and_then(|name| BranchName::try_from(name).ok())
243            .map_or_else(|| Head::Detached(self.resolve(tree)), Head::Branch)
244    }
245}
246
247/// Where `identity` (of the workspace `repo`) lives, and `repo` relative to its worktree.
248/// The head of the worktree at `tree` with `branch` checked out, or detached without one. A
249/// name Git reports that is no branch name is known by the worktree's folder instead.
250fn place_of(identity: &Identity, repo: &Path, keys: &mut DirectoryKeys) -> (Place, PathBuf) {
251    match (&identity.common_dir, &identity.worktree_path) {
252        (Some(common), Some(tree)) => {
253            let head = keys.head(identity.branch.clone(), tree);
254            let relative = paths::relative_beneath(repo, tree).unwrap_or_default();
255            (
256                Place::Git {
257                    common: keys.resolve(common),
258                    head,
259                },
260                relative,
261            )
262        }
263        _ => (Place::Folder(keys.resolve(repo)), PathBuf::new()),
264    }
265}
266
267fn folder_name(path: &Path) -> String {
268    path.file_name().map_or_else(
269        || crate::platform::path_text(path),
270        |name| name.to_string_lossy().into_owned(),
271    )
272}
273
274/// The project's name: a repository's main folder (the parent of its `.git`), a bare
275/// repository's own folder without `.git`, or the folder outside Git.
276fn project_name(place: &Place) -> String {
277    match place {
278        Place::Git { common, .. } if common.file_name().is_some_and(|name| name == ".git") => {
279            folder_name(common.parent().unwrap_or(common))
280        }
281        Place::Git { common, .. } => {
282            let name = folder_name(common);
283            name.strip_suffix(".git")
284                .map_or(name.clone(), str::to_owned)
285        }
286        Place::Folder(path) => folder_name(path),
287    }
288}
289
290fn branch_name(place: &Place) -> String {
291    match place {
292        Place::Git {
293            head: Head::Branch(branch),
294            ..
295        } => branch.to_string(),
296        Place::Git {
297            head: Head::Detached(tree),
298            ..
299        } => folder_name(tree),
300        Place::Folder(_) => String::new(),
301    }
302}
303
304fn label(place: &Place) -> Label {
305    Label {
306        project: project_name(place),
307        branch: branch_name(place),
308    }
309}
310
311/// What the listing of the branches found.
312pub struct Listing {
313    /// The live branches, the most recent Run first.
314    pub branches: Vec<Branch>,
315    pub labels: Labels,
316    /// The branch of the folder the app was started for, when it lives.
317    pub launch: Option<Place>,
318}
319
320/// A branch's Runs so far, and when its newest started with its workspace in the worktree.
321type Grouped = (Vec<Chip>, Option<(Timestamp, PathBuf)>);
322
323/// The live branches of the projects of `runs`, with their Runs, and the branch of `launch`
324/// (the folder the app was started for) even before its project has a Run.
325pub fn branches(runs: &[CatalogRun], launch: Option<&Path>, discovery: &mut Discovery) -> Listing {
326    let mut grouped: BTreeMap<Place, Grouped> = BTreeMap::new();
327    let mut labels = Labels::new();
328    let mut keys = DirectoryKeys::default();
329    let launched = launch.map(|path| {
330        let (place, _) = place_of(&discovery.identify(path), path, &mut keys);
331        (place, path.to_path_buf())
332    });
333    for run in runs {
334        let identity =
335            if run.repository.common_dir.is_some() && run.repository.worktree_path.is_some() {
336                run.repository.clone()
337            } else {
338                discovery.identify(&run.repo_path)
339            };
340        let (place, relative) = place_of(&identity, &run.repo_path, &mut keys);
341        labels.insert(run.id.clone(), label(&place));
342        let (chips, newest) = grouped.entry(place).or_default();
343        chips.push(Chip {
344            id: run.id.clone(),
345            status: run.status,
346            created_at: run.created_at,
347            completed_at: run.completed_at,
348            comment: run.comment.clone(),
349        });
350        if newest.as_ref().is_none_or(|(at, _)| run.created_at >= *at) {
351            *newest = Some((run.created_at, relative));
352        }
353    }
354    let commons: BTreeSet<PathBuf> = grouped
355        .keys()
356        .chain(launched.iter().map(|(place, _)| place))
357        .filter_map(|place| match place {
358            Place::Git { common, .. } => Some(common.clone()),
359            Place::Folder(_) => None,
360        })
361        .collect();
362    let mut live = Vec::new();
363    for common in commons {
364        live.extend(discovery.worktrees(&common).into_iter().map(|tree| {
365            let head = keys.head(tree.branch, &tree.path);
366            (
367                Place::Git {
368                    common: common.clone(),
369                    head,
370                },
371                tree.path,
372            )
373        }));
374    }
375    let folders: BTreeSet<&PathBuf> = grouped
376        .keys()
377        .chain(launched.iter().map(|(place, _)| place))
378        .filter_map(|place| match place {
379            Place::Folder(path) => Some(path),
380            Place::Git { .. } => None,
381        })
382        .collect();
383    // A Run's folder is live while it still holds declarations; the folder the app was started
384    // for is live while it exists, as the CLI takes any folder as `--repo`, its Artifacts
385    // perhaps only in subfolders.
386    let started = |path: &PathBuf| {
387        launched
388            .as_ref()
389            .is_some_and(|(place, _)| matches!(place, Place::Folder(folder) if folder == path))
390    };
391    live.extend(
392        folders
393            .into_iter()
394            .filter(|path| discovery.is_folder(path) && (started(path) || discovery.declares(path)))
395            .map(|path| (Place::Folder(path.clone()), path.clone())),
396    );
397    // Which newest-Run folders still exist, as the filesystem boundary reports.
398    let present: BTreeSet<PathBuf> = live
399        .iter()
400        .filter_map(|(place, tree)| {
401            let (_, newest) = grouped.get(place)?;
402            let folder = tree.join(&newest.as_ref()?.1);
403            discovery.is_folder(&folder).then_some(folder)
404        })
405        .collect();
406    let mut branches: Vec<Branch> = live
407        .into_iter()
408        .map(|(place, tree)| {
409            let (mut runs, newest) = grouped.remove(&place).unwrap_or_default();
410            runs.sort_by(|a, b| (a.created_at, &a.id).cmp(&(b.created_at, &b.id)));
411            let workspace = match &launched {
412                Some((launch, path)) if *launch == place => path.clone(),
413                _ => newest
414                    .map(|(_, relative)| tree.join(relative))
415                    .filter(|path| present.contains(path))
416                    .unwrap_or(tree),
417            };
418            let Label { project, branch } = label(&place);
419            Branch {
420                place,
421                project,
422                name: branch,
423                workspace,
424                runs,
425            }
426        })
427        .collect();
428    query::order(&mut branches, Sort::Recent);
429    let launch = launched
430        .map(|(place, _)| place)
431        .filter(|place| branches.iter().any(|branch| &branch.place == place));
432    Listing {
433        branches,
434        labels,
435        launch,
436    }
437}