1mod 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#[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 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#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
85#[serde(rename_all = "camelCase")]
86pub enum Head {
87 Branch(BranchName),
88 Detached(#[serde(with = "crate::platform::path_serde")] PathBuf),
90}
91
92#[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 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#[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#[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 pub comment: Option<crate::types::RunComment>,
132}
133
134#[derive(Debug, Clone, PartialEq, Eq)]
136pub struct Branch {
137 pub place: Place,
138 pub project: String,
140 pub name: String,
142 pub workspace: PathBuf,
145 pub runs: Vec<Chip>,
147}
148
149impl Branch {
150 pub fn running(&self) -> Option<&Chip> {
152 self.runs.last().filter(|chip| chip.status.is_open())
153 }
154
155 pub fn latest(&self) -> Option<Timestamp> {
157 self.runs.last().map(|chip| chip.created_at)
158 }
159}
160
161#[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#[derive(Default)]
174pub struct Discovery {
175 identities: BTreeMap<PathBuf, Identity>,
176 trees: BTreeMap<PathBuf, Vec<Worktree>>,
177}
178
179impl Discovery {
180 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 fn is_folder(&self, path: &Path) -> bool {
194 path.is_dir()
195 }
196
197 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 path: crate::platform::canonicalize(&tree.path).unwrap_or(tree.path),
211 branch: tree.branch,
212 })
213 .collect()
214 })
215 .clone()
216 }
217}
218
219#[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
247fn 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
274fn 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
311pub struct Listing {
313 pub branches: Vec<Branch>,
315 pub labels: Labels,
316 pub launch: Option<Place>,
318}
319
320type Grouped = (Vec<Chip>, Option<(Timestamp, PathBuf)>);
322
323pub 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 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 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}