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    /// A saved or live checkout's branch. Both the workspace and Git identity are canonical.
107    pub fn for_checkout(workspace: &Path, identity: &Identity) -> Self {
108        match (&identity.common_dir, &identity.worktree_path) {
109            (Some(common), Some(tree)) => Self::Git {
110                common: common.clone(),
111                head: checkout_head(identity.branch.clone(), || tree.clone()),
112            },
113            _ => Self::Folder(workspace.to_owned()),
114        }
115    }
116
117    /// The Run's original branch, even when no worktree currently has it checked out.
118    pub fn recorded_run(run: &crate::store::Run) -> Self {
119        Self::for_checkout(&run.repo_path, &run.repository)
120    }
121
122    /// Refuse a stale path rather than scanning or editing a different branch.
123    pub async fn checked_workspace(&self, workspace: PathBuf) -> Result<PathBuf, String> {
124        let place = self.clone();
125        crate::task::blocking(move || {
126            if !workspace.is_dir() {
127                return Err("This worktree no longer exists.".into());
128            }
129            let path =
130                crate::platform::canonicalize(&workspace).map_err(|error| error.to_string())?;
131            if Self::for_checkout(&path, &repository::identify(&path)) != place {
132                return Err("This branch is no longer checked out in the worktree.".into());
133            }
134            Ok(path)
135        })
136        .await?
137    }
138
139    /// The project the branch belongs to: every branch of a Git repository shares one.
140    pub fn project(&self) -> Project {
141        match self {
142            Self::Git { common, .. } => Project::Git(common.clone()),
143            Self::Folder(path) => Project::Folder(path.clone()),
144        }
145    }
146}
147
148/// A project: a Git repository, by its common directory, or a folder outside Git.
149#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
150#[serde(rename_all = "camelCase")]
151pub enum Project {
152    Git(#[serde(with = "crate::platform::path_serde")] PathBuf),
153    Folder(#[serde(with = "crate::platform::path_serde")] PathBuf),
154}
155
156impl Project {
157    pub fn path(&self) -> &Path {
158        match self {
159            Self::Git(path) | Self::Folder(path) => path,
160        }
161    }
162}
163
164/// One Run of a branch as its chip shows it.
165#[derive(Debug, Clone, PartialEq, Eq)]
166pub struct Chip {
167    pub id: RunId,
168    pub status: RunStatus,
169    pub created_at: Timestamp,
170    pub completed_at: Option<Timestamp>,
171    /// What the requester said it is working on (`verify --comment`).
172    pub comment: Option<crate::types::RunComment>,
173}
174
175/// A live branch and its Runs.
176#[derive(Debug, Clone, PartialEq, Eq)]
177pub struct Branch {
178    pub place: Place,
179    /// The project's name: its repository's or folder's.
180    pub project: String,
181    /// The branch, a detached worktree's folder name, or empty for a folder outside Git.
182    pub name: String,
183    /// Where its Current is scanned and its Artifacts' tools run: the worktree (or folder) as it
184    /// is now, at the workspace its newest Run used (or the app was started for) within it.
185    pub workspace: PathBuf,
186    /// Its Runs, oldest first.
187    pub runs: Vec<Chip>,
188}
189
190impl Branch {
191    /// A saved Run on an absent branch, shown only while following its exact reference.
192    pub fn historical(run: &crate::store::Run) -> Self {
193        let place = Place::recorded_run(run);
194        let Label {
195            project,
196            branch: name,
197            ..
198        } = label(&place);
199        Self {
200            place,
201            project,
202            name,
203            workspace: run.repo_path.clone(),
204            runs: vec![Chip {
205                id: run.id.clone(),
206                status: run.status(),
207                created_at: run.created_at,
208                completed_at: run.completed_at(),
209                comment: run.comment.clone(),
210            }],
211        }
212    }
213
214    /// In-progress Runs first, then ended Runs, newest first within each group.
215    pub fn timeline(&self) -> impl Iterator<Item = &Chip> {
216        let newest = self.runs.iter().rev();
217        newest
218            .clone()
219            .filter(|chip| chip.status.is_open())
220            .chain(newest.filter(|chip| !chip.status.is_open()))
221    }
222
223    /// The newest Run still in progress, even if a later one already ended.
224    pub fn running(&self) -> Option<&Chip> {
225        self.runs.iter().rev().find(|chip| chip.status.is_open())
226    }
227
228    /// When its newest Run started.
229    pub fn latest(&self) -> Option<Timestamp> {
230        self.runs.last().map(|chip| chip.created_at)
231    }
232}
233
234/// Which project and branch a saved Run ran on, by name, for every Run whether or not its
235/// branch still lives: what a waiting review of it is listed with.
236#[derive(Debug, Clone, Default, PartialEq, Eq)]
237pub struct Label {
238    pub project: String,
239    pub project_key: Option<Project>,
240    pub branch: String,
241}
242
243pub type Labels = BTreeMap<RunId, Label>;
244
245/// Cached Git facts. Identities of old Run records without a saved identity are asked of Git
246/// once; which worktrees exist is asked again on every [`Discovery::rescan`].
247#[derive(Default)]
248pub struct Discovery {
249    identities: BTreeMap<PathBuf, Identity>,
250    trees: BTreeMap<PathBuf, Vec<Worktree>>,
251}
252
253impl Discovery {
254    /// Ask Git again which worktrees exist, on the next listing.
255    pub fn rescan(&mut self) {
256        self.trees.clear();
257    }
258
259    fn identify(&mut self, path: &Path) -> Identity {
260        self.identities
261            .entry(path.to_path_buf())
262            .or_insert_with(|| repository::identify(path))
263            .clone()
264    }
265
266    /// Whether `path` is a folder now.
267    fn is_folder(&self, path: &Path) -> bool {
268        crate::platform::is_directory(path)
269    }
270
271    /// Whether the folder `path` holds declarations.
272    fn declares(&self, path: &Path) -> bool {
273        crate::workspace::has_artifact_marker(path).unwrap_or(false)
274    }
275
276    fn worktrees(&mut self, common: &Path) -> Vec<Worktree> {
277        self.trees
278            .entry(common.to_path_buf())
279            .or_insert_with(|| {
280                repository::worktrees(common)
281                    .into_iter()
282                    .map(|tree| Worktree {
283                        // Saved identities are canonical; a detached head is matched by path.
284                        path: crate::platform::canonicalize(&tree.path).unwrap_or(tree.path),
285                        branch: tree.branch,
286                    })
287                    .collect()
288            })
289            .clone()
290    }
291}
292
293/// Pick one usable spelling per physical directory for this listing. Read each distinct
294/// saved spelling only once, even if many Runs were saved from it.
295#[derive(Default)]
296struct DirectoryKeys {
297    by_path: BTreeMap<PathBuf, PathBuf>,
298    by_identity: BTreeMap<FileIdentity, PathBuf>,
299}
300
301impl DirectoryKeys {
302    fn resolve(&mut self, path: &Path) -> PathBuf {
303        if let Some(key) = self.by_path.get(path) {
304            return key.clone();
305        }
306        let key = paths::directory_identity(path).map_or_else(
307            |_| path.to_owned(),
308            |(id, canonical)| self.by_identity.entry(id).or_insert(canonical).clone(),
309        );
310        self.by_path.insert(path.to_owned(), key.clone());
311        key
312    }
313
314    fn head(&mut self, branch: Option<String>, tree: &Path) -> Head {
315        checkout_head(branch, || self.resolve(tree))
316    }
317}
318
319fn checkout_head(branch: Option<String>, detached: impl FnOnce() -> PathBuf) -> Head {
320    branch
321        .and_then(|name| BranchName::try_from(name).ok())
322        .map_or_else(|| Head::Detached(detached()), Head::Branch)
323}
324
325/// Where `identity` (of the workspace `repo`) lives, and `repo` relative to its worktree.
326/// The head of the worktree at `tree` with `branch` checked out, or detached without one. A
327/// name Git reports that is no branch name is known by the worktree's folder instead.
328fn place_of(identity: &Identity, repo: &Path, keys: &mut DirectoryKeys) -> (Place, PathBuf) {
329    match (&identity.common_dir, &identity.worktree_path) {
330        (Some(common), Some(tree)) => {
331            let head = keys.head(identity.branch.clone(), tree);
332            let relative = paths::relative_beneath(repo, tree).unwrap_or_default();
333            (
334                Place::Git {
335                    common: keys.resolve(common),
336                    head,
337                },
338                relative,
339            )
340        }
341        _ => (Place::Folder(keys.resolve(repo)), PathBuf::new()),
342    }
343}
344
345fn folder_name(path: &Path) -> String {
346    path.file_name().map_or_else(
347        || crate::platform::path_text(path),
348        crate::platform::display_name,
349    )
350}
351
352/// The project's name: a repository's main folder (the parent of its `.git`), a bare
353/// repository's own folder without `.git`, or the folder outside Git.
354fn project_name(place: &Place) -> String {
355    match place {
356        Place::Git { common, .. } if common.file_name().is_some_and(|name| name == ".git") => {
357            folder_name(common.parent().unwrap_or(common))
358        }
359        Place::Git { common, .. } => {
360            let name = folder_name(common);
361            name.strip_suffix(".git")
362                .map_or(name.clone(), str::to_owned)
363        }
364        Place::Folder(path) => folder_name(path),
365    }
366}
367
368fn branch_name(place: &Place) -> String {
369    match place {
370        Place::Git {
371            head: Head::Branch(branch),
372            ..
373        } => branch.to_string(),
374        Place::Git {
375            head: Head::Detached(tree),
376            ..
377        } => folder_name(tree),
378        Place::Folder(_) => String::new(),
379    }
380}
381
382fn label(place: &Place) -> Label {
383    Label {
384        project: project_name(place),
385        project_key: Some(place.project()),
386        branch: branch_name(place),
387    }
388}
389
390impl Label {
391    /// Name a worktree whose Run is not in the current monitor snapshot.
392    pub fn at(repo: &Path) -> Self {
393        Self::for_identity(repo, &crate::repository::identify(repo))
394    }
395
396    /// Name the saved Git head of a worktree, not the branch checked out there today.
397    pub fn for_identity(repo: &Path, identity: &crate::repository::Identity) -> Self {
398        let (place, _) = place_of(identity, repo, &mut DirectoryKeys::default());
399        label(&place)
400    }
401}
402
403/// What the listing of the branches found.
404pub struct Listing {
405    /// The live branches, the most recent Run first.
406    pub branches: Vec<Branch>,
407    pub labels: Labels,
408    /// The branch of the folder the app was started for, when it lives.
409    pub launch: Option<Place>,
410}
411
412/// A branch's Runs so far, and when its newest started with its workspace in the worktree.
413type Grouped = (Vec<Chip>, Option<(Timestamp, PathBuf)>);
414
415/// Resolve only one Run's live branch using the same identities as the timeline listing.
416fn branch_for(run: &crate::store::Run, discovery: &mut Discovery) -> Option<Place> {
417    let row = CatalogRun {
418        id: run.id.clone(),
419        created_at: run.created_at,
420        completed_at: run.completed_at(),
421        repo_path: run.repo_path.clone(),
422        repository: run.repository.clone(),
423        status: run.status(),
424        comment: run.comment.clone(),
425        red: 0,
426        error: 0,
427        waiting: Vec::new(),
428    };
429    branches(&[row], None, discovery)
430        .branches
431        .into_iter()
432        .find(|branch| branch.runs.iter().any(|chip| chip.id == run.id))
433        .map(|branch| branch.place)
434}
435
436/// The live branches of the projects of `runs`, with their Runs, and the branch of `launch`
437/// (the folder the app was started for) even before its project has a Run.
438pub fn branches(runs: &[CatalogRun], launch: Option<&Path>, discovery: &mut Discovery) -> Listing {
439    let mut grouped: BTreeMap<Place, Grouped> = BTreeMap::new();
440    let mut labels = Labels::new();
441    let mut keys = DirectoryKeys::default();
442    let launched = launch.map(|path| {
443        let (place, _) = place_of(&discovery.identify(path), path, &mut keys);
444        (place, path.to_path_buf())
445    });
446    for run in runs {
447        let identity =
448            if run.repository.common_dir.is_some() && run.repository.worktree_path.is_some() {
449                run.repository.clone()
450            } else {
451                discovery.identify(&run.repo_path)
452            };
453        let (place, relative) = place_of(&identity, &run.repo_path, &mut keys);
454        labels.insert(run.id.clone(), label(&place));
455        let (chips, newest) = grouped.entry(place).or_default();
456        chips.push(Chip {
457            id: run.id.clone(),
458            status: run.status,
459            created_at: run.created_at,
460            completed_at: run.completed_at,
461            comment: run.comment.clone(),
462        });
463        if newest.as_ref().is_none_or(|(at, _)| run.created_at >= *at) {
464            *newest = Some((run.created_at, relative));
465        }
466    }
467    let commons: BTreeSet<PathBuf> = grouped
468        .keys()
469        .chain(launched.iter().map(|(place, _)| place))
470        .filter_map(|place| match place {
471            Place::Git { common, .. } => Some(common.clone()),
472            Place::Folder(_) => None,
473        })
474        .collect();
475    let mut live = Vec::new();
476    for common in commons {
477        live.extend(discovery.worktrees(&common).into_iter().map(|tree| {
478            let head = keys.head(tree.branch, &tree.path);
479            (
480                Place::Git {
481                    common: common.clone(),
482                    head,
483                },
484                tree.path,
485            )
486        }));
487    }
488    let folders: BTreeSet<&PathBuf> = grouped
489        .keys()
490        .chain(launched.iter().map(|(place, _)| place))
491        .filter_map(|place| match place {
492            Place::Folder(path) => Some(path),
493            Place::Git { .. } => None,
494        })
495        .collect();
496    // A Run's folder is live while it still holds declarations; the folder the app was started
497    // for is live while it exists, as the CLI takes any folder as `--repo`, its Artifacts
498    // perhaps only in subfolders.
499    let started = |path: &PathBuf| {
500        launched
501            .as_ref()
502            .is_some_and(|(place, _)| matches!(place, Place::Folder(folder) if folder == path))
503    };
504    live.extend(
505        folders
506            .into_iter()
507            .filter(|path| discovery.is_folder(path) && (started(path) || discovery.declares(path)))
508            .map(|path| (Place::Folder(path.clone()), path.clone())),
509    );
510    // Which newest-Run folders still exist, as the filesystem boundary reports.
511    let present: BTreeSet<PathBuf> = live
512        .iter()
513        .filter_map(|(place, tree)| {
514            let (_, newest) = grouped.get(place)?;
515            let folder = tree.join(&newest.as_ref()?.1);
516            discovery.is_folder(&folder).then_some(folder)
517        })
518        .collect();
519    let mut branches: Vec<Branch> = live
520        .into_iter()
521        .map(|(place, tree)| {
522            let (mut runs, newest) = grouped.remove(&place).unwrap_or_default();
523            runs.sort_by(|a, b| (a.created_at, &a.id).cmp(&(b.created_at, &b.id)));
524            let workspace = match &launched {
525                Some((launch, path)) if *launch == place => path.clone(),
526                _ => newest
527                    .map(|(_, relative)| tree.join(relative))
528                    .filter(|path| present.contains(path))
529                    .unwrap_or(tree),
530            };
531            let Label {
532                project, branch, ..
533            } = label(&place);
534            Branch {
535                place,
536                project,
537                name: branch,
538                workspace,
539                runs,
540            }
541        })
542        .collect();
543    query::order(&mut branches, Sort::Recent);
544    let launch = launched
545        .map(|(place, _)| place)
546        .filter(|place| branches.iter().any(|branch| &branch.place == place));
547    Listing {
548        branches,
549        labels,
550        launch,
551    }
552}