1mod current;
7mod loader;
8mod query;
9mod starred;
10mod waiting;
11
12#[cfg(test)]
13mod tests;
14
15pub use crate::store::Unreadable;
16pub use current::{Current, CurrentArtifact, CurrentEdge, CurrentEval, Plan, scan};
17pub use loader::{Input, Loader, OpenRun, Opened, Snapshot};
18pub use query::{DEFAULT, Query, Sort, complete, show};
19pub use starred::{star, star_artifact, starred, starred_artifacts};
20pub use waiting::{Waiting, waiting};
21
22use crate::{
23 platform::{FileIdentity, paths},
24 repository::{self, Identity, Worktree},
25 store::CatalogRun,
26 types::{RunId, RunStatus, Timestamp},
27};
28use serde::{Deserialize, Serialize};
29use std::{
30 collections::{BTreeMap, BTreeSet},
31 path::{Path, PathBuf},
32};
33
34#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
38#[serde(try_from = "String", into = "String")]
39pub struct BranchName(String);
40
41impl BranchName {
42 pub fn as_str(&self) -> &str {
43 &self.0
44 }
45}
46
47impl TryFrom<String> for BranchName {
48 type Error = String;
49
50 fn try_from(name: String) -> Result<Self, String> {
51 let refused = name.starts_with('-')
54 || name.ends_with('.')
55 || name == "@"
56 || name.contains("..")
57 || name.contains("@{")
58 || name
59 .split('/')
60 .any(|part| part.is_empty() || part.starts_with('.') || part.ends_with(".lock"))
61 || name.chars().any(|c| {
62 c.is_control() || matches!(c, ' ' | '~' | '^' | ':' | '?' | '*' | '[' | '\\')
63 });
64 if refused {
65 Err(format!("not a branch name: {name:?}"))
66 } else {
67 Ok(Self(name))
68 }
69 }
70}
71
72impl From<BranchName> for String {
73 fn from(name: BranchName) -> Self {
74 name.0
75 }
76}
77
78impl std::fmt::Display for BranchName {
79 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80 f.write_str(&self.0)
81 }
82}
83
84#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
86#[serde(rename_all = "camelCase")]
87pub enum Head {
88 Branch(BranchName),
89 Detached(#[serde(with = "crate::platform::path_serde")] PathBuf),
91}
92
93#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
96#[serde(rename_all = "camelCase")]
97pub enum Place {
98 Git {
99 #[serde(with = "crate::platform::path_serde")]
100 common: PathBuf,
101 head: Head,
102 },
103 Folder(#[serde(with = "crate::platform::path_serde")] PathBuf),
104}
105
106impl Place {
107 pub fn for_checkout(workspace: &Path, identity: &Identity) -> Self {
109 match (&identity.common_dir, &identity.worktree_path) {
110 (Some(common), Some(tree)) => Self::Git {
111 common: common.clone(),
112 head: checkout_head(identity.branch.clone(), || tree.clone()),
113 },
114 _ => Self::Folder(workspace.to_owned()),
115 }
116 }
117
118 pub fn recorded_run(run: &crate::store::Run) -> Self {
120 Self::for_checkout(&run.repo_path, &run.repository)
121 }
122
123 pub async fn checked_workspace(&self, workspace: PathBuf) -> Result<PathBuf, String> {
125 let place = self.clone();
126 crate::task::blocking(move || {
127 if !crate::platform::paths::target_is_dir(&workspace) {
128 return Err("This worktree no longer exists.".into());
129 }
130 let path =
131 crate::platform::canonicalize(&workspace).map_err(|error| error.to_string())?;
132 if Self::for_checkout(&path, &repository::identify(&path)) != place {
133 return Err("This branch is no longer checked out in the worktree.".into());
134 }
135 Ok(path)
136 })
137 .await?
138 }
139
140 pub fn project(&self) -> Project {
142 match self {
143 Self::Git { common, .. } => Project::Git(common.clone()),
144 Self::Folder(path) => Project::Folder(path.clone()),
145 }
146 }
147}
148
149#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
151#[serde(rename_all = "camelCase")]
152pub enum Project {
153 Git(#[serde(with = "crate::platform::path_serde")] PathBuf),
154 Folder(#[serde(with = "crate::platform::path_serde")] PathBuf),
155}
156
157impl Project {
158 pub fn path(&self) -> &Path {
159 match self {
160 Self::Git(path) | Self::Folder(path) => path,
161 }
162 }
163}
164
165#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
167#[serde(rename_all = "camelCase")]
168pub struct Chip {
169 pub id: RunId,
170 pub status: RunStatus,
171 pub created_at: Timestamp,
172 pub completed_at: Option<Timestamp>,
173 pub comment: Option<crate::types::RunComment>,
175}
176
177#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
179pub struct Branch {
180 pub place: Place,
181 pub project: String,
183 pub name: String,
185 #[serde(with = "crate::platform::path_serde")]
188 pub workspace: PathBuf,
189 pub runs: Vec<Chip>,
191}
192
193impl Branch {
194 pub fn historical(run: &crate::store::Run) -> Self {
196 let place = Place::recorded_run(run);
197 let Label {
198 project,
199 branch: name,
200 ..
201 } = label(&place);
202 Self {
203 place,
204 project,
205 name,
206 workspace: run.repo_path.clone(),
207 runs: vec![Chip {
208 id: run.id.clone(),
209 status: run.status(),
210 created_at: run.created_at,
211 completed_at: run.completed_at(),
212 comment: run.comment.clone(),
213 }],
214 }
215 }
216
217 pub fn timeline(&self) -> impl Iterator<Item = &Chip> {
219 let newest = self.runs.iter().rev();
220 newest
221 .clone()
222 .filter(|chip| chip.status.is_open())
223 .chain(newest.filter(|chip| !chip.status.is_open()))
224 }
225
226 pub fn running(&self) -> Option<&Chip> {
228 self.runs.iter().rev().find(|chip| chip.status.is_open())
229 }
230
231 pub fn latest(&self) -> Option<Timestamp> {
233 self.runs.last().map(|chip| chip.created_at)
234 }
235}
236
237#[derive(Debug, Clone, Default, PartialEq, Eq)]
240pub struct Label {
241 pub project: String,
242 pub project_key: Option<Project>,
243 pub branch: String,
244}
245
246pub type Labels = BTreeMap<RunId, Label>;
247
248#[derive(Default)]
251pub struct Discovery {
252 identities: BTreeMap<PathBuf, Identity>,
253 trees: BTreeMap<PathBuf, Vec<Worktree>>,
254}
255
256impl Discovery {
257 pub fn rescan(&mut self) {
259 self.trees.clear();
260 }
261
262 fn identify(&mut self, path: &Path) -> Identity {
263 self.identities
264 .entry(path.to_path_buf())
265 .or_insert_with(|| repository::identify(path))
266 .clone()
267 }
268
269 fn is_folder(&self, path: &Path) -> bool {
271 crate::platform::is_directory(path)
272 }
273
274 fn declares(&self, path: &Path) -> bool {
276 crate::workspace::has_artifact_marker(path).unwrap_or(false)
277 }
278
279 fn worktrees(&mut self, common: &Path) -> Vec<Worktree> {
280 self.trees
281 .entry(common.to_path_buf())
282 .or_insert_with(|| {
283 repository::worktrees(common)
284 .into_iter()
285 .map(|tree| Worktree {
286 path: crate::platform::canonicalize(&tree.path).unwrap_or(tree.path),
288 branch: tree.branch,
289 })
290 .collect()
291 })
292 .clone()
293 }
294}
295
296#[derive(Default)]
299struct DirectoryKeys {
300 by_path: BTreeMap<PathBuf, PathBuf>,
301 by_identity: BTreeMap<FileIdentity, PathBuf>,
302}
303
304impl DirectoryKeys {
305 fn resolve(&mut self, path: &Path) -> PathBuf {
306 if let Some(key) = self.by_path.get(path) {
307 return key.clone();
308 }
309 let key = paths::directory_identity(path).map_or_else(
310 |_| path.to_owned(),
311 |(id, canonical)| self.by_identity.entry(id).or_insert(canonical).clone(),
312 );
313 self.by_path.insert(path.to_owned(), key.clone());
314 key
315 }
316
317 fn head(&mut self, branch: Option<String>, tree: &Path) -> Head {
318 checkout_head(branch, || self.resolve(tree))
319 }
320}
321
322fn checkout_head(branch: Option<String>, detached: impl FnOnce() -> PathBuf) -> Head {
323 branch
324 .and_then(|name| BranchName::try_from(name).ok())
325 .map_or_else(|| Head::Detached(detached()), Head::Branch)
326}
327
328fn place_of(identity: &Identity, repo: &Path, keys: &mut DirectoryKeys) -> (Place, PathBuf) {
332 match (&identity.common_dir, &identity.worktree_path) {
333 (Some(common), Some(tree)) => {
334 let head = keys.head(identity.branch.clone(), tree);
335 let relative = paths::relative_beneath(repo, tree).unwrap_or_default();
336 (
337 Place::Git {
338 common: keys.resolve(common),
339 head,
340 },
341 relative,
342 )
343 }
344 _ => (Place::Folder(keys.resolve(repo)), PathBuf::new()),
345 }
346}
347
348fn folder_name(path: &Path) -> String {
349 path.file_name().map_or_else(
350 || crate::platform::path_text(path),
351 crate::platform::display_name,
352 )
353}
354
355fn project_name(place: &Place) -> String {
358 match place {
359 Place::Git { common, .. } if common.file_name().is_some_and(|name| name == ".git") => {
360 folder_name(common.parent().unwrap_or(common))
361 }
362 Place::Git { common, .. } => {
363 let name = folder_name(common);
364 name.strip_suffix(".git")
365 .map_or(name.clone(), str::to_owned)
366 }
367 Place::Folder(path) => folder_name(path),
368 }
369}
370
371fn branch_name(place: &Place) -> String {
372 match place {
373 Place::Git {
374 head: Head::Branch(branch),
375 ..
376 } => branch.to_string(),
377 Place::Git {
378 head: Head::Detached(tree),
379 ..
380 } => folder_name(tree),
381 Place::Folder(_) => String::new(),
382 }
383}
384
385fn label(place: &Place) -> Label {
386 Label {
387 project: project_name(place),
388 project_key: Some(place.project()),
389 branch: branch_name(place),
390 }
391}
392
393impl Label {
394 pub fn at(repo: &Path) -> Self {
396 Self::for_identity(repo, &crate::repository::identify(repo))
397 }
398
399 pub fn for_identity(repo: &Path, identity: &crate::repository::Identity) -> Self {
401 let (place, _) = place_of(identity, repo, &mut DirectoryKeys::default());
402 label(&place)
403 }
404}
405
406pub struct Listing {
408 pub branches: Vec<Branch>,
410 pub labels: Labels,
411 pub launch: Option<Place>,
413}
414
415type Grouped = (Vec<Chip>, Option<(Timestamp, PathBuf)>);
417
418fn branch_for(run: &crate::store::Run, discovery: &mut Discovery) -> Option<Place> {
420 let row = CatalogRun {
421 id: run.id.clone(),
422 created_at: run.created_at,
423 completed_at: run.completed_at(),
424 repo_path: run.repo_path.clone(),
425 repository: run.repository.clone(),
426 status: run.status(),
427 comment: run.comment.clone(),
428 red: 0,
429 error: 0,
430 waiting: Vec::new(),
431 };
432 branches(&[row], None, discovery)
433 .branches
434 .into_iter()
435 .find(|branch| branch.runs.iter().any(|chip| chip.id == run.id))
436 .map(|branch| branch.place)
437}
438
439pub fn branches(runs: &[CatalogRun], launch: Option<&Path>, discovery: &mut Discovery) -> Listing {
442 let mut grouped: BTreeMap<Place, Grouped> = BTreeMap::new();
443 let mut labels = Labels::new();
444 let mut keys = DirectoryKeys::default();
445 let launched = launch.map(|path| {
446 let (place, _) = place_of(&discovery.identify(path), path, &mut keys);
447 (place, path.to_path_buf())
448 });
449 for run in runs {
450 let identity =
451 if run.repository.common_dir.is_some() && run.repository.worktree_path.is_some() {
452 run.repository.clone()
453 } else {
454 discovery.identify(&run.repo_path)
455 };
456 let (place, relative) = place_of(&identity, &run.repo_path, &mut keys);
457 labels.insert(run.id.clone(), label(&place));
458 let (chips, newest) = grouped.entry(place).or_default();
459 chips.push(Chip {
460 id: run.id.clone(),
461 status: run.status,
462 created_at: run.created_at,
463 completed_at: run.completed_at,
464 comment: run.comment.clone(),
465 });
466 if newest.as_ref().is_none_or(|(at, _)| run.created_at >= *at) {
467 *newest = Some((run.created_at, relative));
468 }
469 }
470 let commons: BTreeSet<PathBuf> = grouped
471 .keys()
472 .chain(launched.iter().map(|(place, _)| place))
473 .filter_map(|place| match place {
474 Place::Git { common, .. } => Some(common.clone()),
475 Place::Folder(_) => None,
476 })
477 .collect();
478 let mut live = Vec::new();
479 for common in commons {
480 live.extend(discovery.worktrees(&common).into_iter().map(|tree| {
481 let head = keys.head(tree.branch, &tree.path);
482 (
483 Place::Git {
484 common: common.clone(),
485 head,
486 },
487 tree.path,
488 )
489 }));
490 }
491 let folders: BTreeSet<&PathBuf> = grouped
492 .keys()
493 .chain(launched.iter().map(|(place, _)| place))
494 .filter_map(|place| match place {
495 Place::Folder(path) => Some(path),
496 Place::Git { .. } => None,
497 })
498 .collect();
499 let started = |path: &PathBuf| {
503 launched
504 .as_ref()
505 .is_some_and(|(place, _)| matches!(place, Place::Folder(folder) if folder == path))
506 };
507 live.extend(
508 folders
509 .into_iter()
510 .filter(|path| discovery.is_folder(path) && (started(path) || discovery.declares(path)))
511 .map(|path| (Place::Folder(path.clone()), path.clone())),
512 );
513 let present: BTreeSet<PathBuf> = live
515 .iter()
516 .filter_map(|(place, tree)| {
517 let (_, newest) = grouped.get(place)?;
518 let folder = tree.join(&newest.as_ref()?.1);
519 discovery.is_folder(&folder).then_some(folder)
520 })
521 .collect();
522 let mut branches: Vec<Branch> = live
523 .into_iter()
524 .map(|(place, tree)| {
525 let (mut runs, newest) = grouped.remove(&place).unwrap_or_default();
526 runs.sort_by(|a, b| (a.created_at, &a.id).cmp(&(b.created_at, &b.id)));
527 let workspace = match &launched {
528 Some((launch, path)) if *launch == place => path.clone(),
529 _ => newest
530 .map(|(_, relative)| tree.join(relative))
531 .filter(|path| present.contains(path))
532 .unwrap_or(tree),
533 };
534 let Label {
535 project, branch, ..
536 } = label(&place);
537 Branch {
538 place,
539 project,
540 name: branch,
541 workspace,
542 runs,
543 }
544 })
545 .collect();
546 query::order(&mut branches, Sort::Recent);
547 let launch = launched
548 .map(|(place, _)| place)
549 .filter(|place| branches.iter().any(|branch| &branch.place == place));
550 Listing {
551 branches,
552 labels,
553 launch,
554 }
555}