Skip to main content

artifactize_core/monitor/
catalog.rs

1//! Repository/worktree selection and cached Git discovery; no artifact config is read here.
2#[cfg(test)]
3mod tests;
4use super::model::Status;
5use crate::{
6    repository::{self, Identity, Worktree},
7    store::{CatalogRun, Signoff},
8};
9use std::{
10    collections::{BTreeMap, BTreeSet},
11    path::{Path, PathBuf},
12};
13
14#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
15pub enum Repository {
16    Git(PathBuf),
17    Workspace(PathBuf),
18}
19#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
20pub enum Scope {
21    All,
22    Repository(Repository),
23    Worktree(Repository, PathBuf),
24}
25#[derive(Debug, Clone, Default)]
26pub struct Badge {
27    pub waiting: BTreeSet<Signoff>,
28    pub red: u64,
29    pub error: u64,
30    pub running: u64,
31}
32impl Badge {
33    fn add(&mut self, run: &CatalogRun) {
34        self.waiting.extend(run.waiting.iter().cloned());
35        self.red += run.red;
36        self.error += run.error;
37        self.running += u64::from(run.status.is_open());
38    }
39    /// Status glyphs and counts in the urgency order of the header, Runs and the tree:
40    /// `!1 โœ—2 โ—1 ?1`.
41    pub fn parts(&self) -> Vec<(Status, u64)> {
42        let mut parts: Vec<_> = [
43            (Status::WaitingHuman, self.waiting.len() as u64),
44            (Status::Red, self.red),
45            (Status::Error, self.error),
46            (Status::Running, self.running),
47        ]
48        .into_iter()
49        .filter(|(_, count)| *count > 0)
50        .collect();
51        parts.sort_by_key(|(status, _)| *status);
52        parts
53    }
54}
55#[derive(Debug, Clone)]
56pub struct CatalogRow {
57    pub scope: Scope,
58    pub label: String,
59    pub badge: Badge,
60    pub depth: usize,
61    /// A row standing for this repository's worktrees without Runs; Space shows or hides them.
62    pub fold: Option<Repository>,
63}
64/// The representative paths for physical directories in this catalog snapshot.
65#[derive(Default)]
66struct Directories {
67    spellings: BTreeMap<PathBuf, PathBuf>,
68    identities: BTreeMap<crate::platform::FileIdentity, PathBuf>,
69}
70
71impl Directories {
72    fn resolve(&mut self, path: PathBuf) -> PathBuf {
73        self.spellings
74            .entry(path.clone())
75            .or_insert_with(|| {
76                crate::platform::paths::directory_identity(&path).map_or_else(
77                    |_| path,
78                    |(id, canonical)| self.identities.entry(id).or_insert(canonical).clone(),
79                )
80            })
81            .clone()
82    }
83}
84
85#[derive(Clone, Default)]
86pub struct Catalog {
87    facts: std::sync::Arc<Vec<CatalogRun>>,
88    initial_path: Option<PathBuf>,
89    identities: BTreeMap<PathBuf, Identity>,
90    trees: BTreeMap<PathBuf, Vec<Worktree>>,
91    pub rows: Vec<CatalogRow>,
92    paths: BTreeMap<Scope, BTreeSet<PathBuf>>,
93    /// Repositories whose worktrees without Runs are shown.
94    expanded: BTreeSet<Repository>,
95    /// The selected scope stays listed even without Runs.
96    pub selected: Option<Scope>,
97}
98impl Catalog {
99    /// Rediscover Git metadata without losing the selected scope or worktree folds.
100    pub(super) fn reset_git(&mut self) {
101        self.identities.clear();
102        self.trees.clear();
103    }
104    fn identity(&mut self, path: &Path) -> Identity {
105        self.identities
106            .entry(path.to_path_buf())
107            .or_insert_with(|| repository::identify(path))
108            .clone()
109    }
110    fn trees(&mut self, common_dir: &Path) -> Vec<Worktree> {
111        self.trees
112            .entry(common_dir.to_path_buf())
113            .or_insert_with(|| repository::worktrees(common_dir))
114            .clone()
115    }
116    pub fn initial(&mut self, path: Option<&Path>) -> Scope {
117        path.map_or(Scope::All, |path| {
118            let paths = self.paths.clone();
119            self.initial_scope(path, &paths)
120        })
121    }
122    fn initial_scope(&mut self, path: &Path, paths: &BTreeMap<Scope, BTreeSet<PathBuf>>) -> Scope {
123        // Take the filesystem and Git observations here; the choice below takes only facts.
124        let exact = paths.iter().find(|(scope, workspaces)| {
125            matches!(scope, Scope::Worktree(_, tree) if crate::platform::paths_equal(tree, path) || workspaces.iter().any(|workspace| crate::platform::paths_equal(workspace, path)))
126        }).map(|(scope, _)| scope.clone());
127        if let Some(scope) = exact {
128            return scope;
129        }
130        let identity = self.identity(path);
131        let ancestors = if identity.common_dir.is_some() && identity.worktree_path.is_some() {
132            Vec::new()
133        } else {
134            paths
135                .iter()
136                .filter(|(scope, _)| matches!(scope, Scope::Worktree(Repository::Workspace(_), _)))
137                .flat_map(|(scope, workspaces)| {
138                    workspaces
139                        .iter()
140                        .filter(move |workspace| crate::platform::is_within(path, workspace))
141                        .map(move |workspace| (workspace.components().count(), scope))
142                })
143                .collect()
144        };
145        Self::initial_path(path, identity, ancestors.into_iter())
146    }
147
148    fn initial_path<'a>(
149        path: &Path,
150        identity: Identity,
151        ancestors: impl Iterator<Item = (usize, &'a Scope)>,
152    ) -> Scope {
153        if let (Some(common), Some(tree)) = (identity.common_dir, identity.worktree_path) {
154            return Scope::Worktree(Repository::Git(common), tree);
155        }
156        // Initial selection only: a known non-Git workspace can contain cwd. Choose the
157        // closest ancestor by components, never a string prefix or inferred Git grouping.
158        ancestors
159            .max_by_key(|(depth, _)| *depth)
160            .map(|(_, scope)| scope.clone())
161            .unwrap_or_else(|| {
162                Scope::Worktree(
163                    Repository::Workspace(path.to_path_buf()),
164                    path.to_path_buf(),
165                )
166            })
167    }
168    /// Old-path discovery stays cached between resets, including database-only refreshes.
169    pub fn update(&mut self, runs: &[CatalogRun], initial: Option<&Path>) {
170        self.facts = std::sync::Arc::new(runs.to_vec());
171        self.initial_path = initial.map(Path::to_path_buf);
172        let mut badges: BTreeMap<Scope, Badge> = BTreeMap::new();
173        let mut paths: BTreeMap<Scope, BTreeSet<PathBuf>> = BTreeMap::new();
174        let mut branches: BTreeMap<Scope, Option<String>> = BTreeMap::new();
175        let mut directories = Directories::default();
176        for run in runs {
177            let identity =
178                if run.repository.common_dir.is_some() && run.repository.worktree_path.is_some() {
179                    run.repository.clone()
180                } else {
181                    self.identity(&run.repo_path)
182                };
183            let (repository, tree) = match (identity.common_dir, identity.worktree_path) {
184                (Some(common), Some(tree)) => (
185                    Repository::Git(directories.resolve(common)),
186                    directories.resolve(tree),
187                ),
188                _ => {
189                    let path = directories.resolve(run.repo_path.clone());
190                    (Repository::Workspace(path.clone()), path)
191                }
192            };
193            let scope = Scope::Worktree(repository.clone(), tree);
194            branches.insert(scope.clone(), identity.branch);
195            for scope in [Scope::All, Scope::Repository(repository), scope] {
196                paths
197                    .entry(scope.clone())
198                    .or_default()
199                    .insert(run.repo_path.clone());
200                badges.entry(scope).or_default().add(run);
201            }
202        }
203        if let Some(path) = initial
204            && let Scope::Worktree(repository, tree) = self.initial_scope(path, &paths)
205        {
206            let (repository, tree) = match repository {
207                Repository::Git(common) => (
208                    Repository::Git(directories.resolve(common)),
209                    directories.resolve(tree),
210                ),
211                workspace => (workspace, tree),
212            };
213            paths
214                .entry(Scope::Repository(repository.clone()))
215                .or_default();
216            paths.entry(Scope::Worktree(repository, tree)).or_default();
217        }
218        let repositories: Vec<_> = paths
219            .keys()
220            .filter_map(|scope| match scope {
221                Scope::Repository(repo) => Some(repo.clone()),
222                _ => None,
223            })
224            .collect();
225        for repository in &repositories {
226            if let Repository::Git(common) = repository {
227                for tree in self.trees(common) {
228                    let scope = Scope::Worktree(repository.clone(), directories.resolve(tree.path));
229                    paths.entry(scope.clone()).or_default();
230                    branches.entry(scope).or_insert(tree.branch);
231                }
232            }
233        }
234        let mut rows = vec![CatalogRow {
235            scope: Scope::All,
236            label: "ALL".into(),
237            badge: badges.get(&Scope::All).cloned().unwrap_or_default(),
238            depth: 0,
239            fold: None,
240        }];
241        for repository in repositories {
242            let root = match &repository {
243                Repository::Git(path) => path.parent().unwrap_or(path),
244                Repository::Workspace(path) => path.as_path(),
245            };
246            let label = root.file_name().map_or_else(
247                || crate::platform::path_text(root),
248                |name| crate::platform::path_text(Path::new(name)),
249            );
250            // The repository row is the whole repository; there is no separate `ALL` row.
251            let scope = Scope::Repository(repository.clone());
252            rows.push(CatalogRow {
253                scope: scope.clone(),
254                label,
255                badge: badges.get(&scope).cloned().unwrap_or_default(),
256                depth: 0,
257                fold: None,
258            });
259            let mut folded = 0;
260            let expanded = self.expanded.contains(&repository);
261            for (scope, workspaces) in paths.iter().filter(
262                |(scope, _)| matches!(scope, Scope::Worktree(repo, _) if repo == &repository),
263            ) {
264                let Scope::Worktree(_, tree) = scope else {
265                    unreachable!("worktree filter")
266                };
267                if workspaces.is_empty() && !expanded && self.selected.as_ref() != Some(scope) {
268                    folded += 1;
269                    continue;
270                }
271                let branch = branches.get(scope).and_then(Option::as_deref);
272                let name = tree.file_name().map_or_else(
273                    || crate::platform::path_text(tree),
274                    crate::platform::display_name,
275                );
276                let label = match (branch, &repository) {
277                    (Some(branch), _) if branch == name => branch.to_owned(),
278                    (Some(branch), _) => format!("{branch} ยท {name}"),
279                    (None, Repository::Git(_)) => format!("{name} (detached)"),
280                    (None, Repository::Workspace(_)) => format!("{name} (non-Git)"),
281                };
282                rows.push(CatalogRow {
283                    scope: scope.clone(),
284                    label,
285                    badge: badges.get(scope).cloned().unwrap_or_default(),
286                    depth: 1,
287                    fold: None,
288                });
289            }
290            let empty = paths
291                .iter()
292                .filter(|(scope, workspaces)| {
293                    matches!(scope, Scope::Worktree(repo, _) if repo == &repository)
294                        && workspaces.is_empty()
295                })
296                .count();
297            if folded > 0 || expanded && empty > 0 {
298                rows.push(CatalogRow {
299                    scope: scope.clone(),
300                    label: if expanded {
301                        format!("โˆ’ hide {empty} without Runs (Space)")
302                    } else {
303                        format!("+{folded} without Runs (Space)")
304                    },
305                    badge: Badge::default(),
306                    depth: 1,
307                    fold: Some(repository.clone()),
308                });
309            }
310        }
311        self.rows = rows;
312        self.paths = paths;
313    }
314    /// Navigation/fold changes reuse the last accepted database facts, not a catalog query.
315    pub fn rebuild(&mut self) {
316        let facts = self.facts.clone();
317        let initial = self.initial_path.clone();
318        self.update(&facts, initial.as_deref());
319    }
320    /// Show or hide a repository's worktrees without Runs; applied on the next update.
321    pub fn toggle(&mut self, repository: &Repository) {
322        if !self.expanded.remove(repository) {
323            self.expanded.insert(repository.clone());
324        }
325    }
326    /// The name the breadcrumb shows for `scope`: its row's label, else its folder name.
327    pub fn label(&self, scope: &Scope) -> String {
328        if *scope == Scope::All {
329            return "all repositories".into();
330        }
331        self.rows
332            .iter()
333            .find(|row| row.fold.is_none() && row.scope == *scope)
334            .map_or_else(
335                || match scope {
336                    Scope::Worktree(_, path) => path.file_name().map_or_else(
337                        || crate::platform::path_text(path),
338                        crate::platform::display_name,
339                    ),
340                    _ => "repository".into(),
341                },
342                |row| row.label.clone(),
343            )
344    }
345    pub fn paths(&self, scope: &Scope) -> Option<Vec<PathBuf>> {
346        match scope {
347            Scope::All => None,
348            _ => Some(
349                self.paths
350                    .get(scope)
351                    .map_or_else(Vec::new, |paths| paths.iter().cloned().collect()),
352            ),
353        }
354    }
355}