forge
Explore
Log in

Don't you dare go Hollow

yumush

Clone
★ 0

0 watching0 forksRustAGPL-3.07.6 MiB189b6d8Tahinli1 hour ago411 commits

ci_view.rs570 lines, 18.7 KiBHistoryRawDownload
1use std::{collections::HashMap, rc::Rc, time::Duration};
2
3use common::call::{CreateTag, GetForge};
4use gpui_kit::{
5 Anchor, AnyElement, App, Context, Div, Entity, Focusable, InteractiveElement, IntoElement,
6 ListHorizontalSizingBehavior, ParentElement, ScrollStrategy, Styled, Window,
7 component::popover::{Popover, PopoverState},
8 div, px, uniform_list,
9};
10
11use super::releases::caption_text;
12use super::ui::{card, list_row};
13use crate::ci::{self, Event, Job, Run, State};
14use crate::gui::builder::BuilderTab;
15use crate::gui::chat::View;
16use crate::gui::{
17 Palette, Trigger, Yumush, entity_action, hoverable, notify_error,
18 parts::{self, Fill, Press},
19 profile::yumush_action,
20 style::{radius, size, space, text},
21 text,
22};
23use crate::lang::w;
24
25const LOG_LINE: f32 = 18.;
26const LOG_MAX: usize = 50_000;
27const TICK: Duration = Duration::from_secs(1);
28
29#[derive(Default)]
30pub(crate) struct Live {
31 repo: Option<String>,
32 watch: Option<ci::Watch>,
33 run: Option<Run>,
34 logs: HashMap<String, Vec<String>>,
35 log_open: Option<String>,
36 seen_live: bool,
37 dismissed: bool,
38 tagging: bool,
39}
40
41impl Live {
42 fn state(&self) -> Option<State> {
43 self.run.as_ref().map(|run| State::of(&run.state))
44 }
45
46 fn live(&self) -> bool {
47 self.state().is_some_and(|state| !state.finished())
48 }
49
50 fn shown(&self) -> bool {
51 self.run.is_some() && self.seen_live && !self.dismissed
52 }
53
54 fn done(&self) -> usize {
55 self.run.as_ref().map_or(0, |run| {
56 run.jobs
57 .iter()
58 .filter(|job| State::of(&job.state).finished())
59 .count()
60 })
61 }
62
63 fn share(&self) -> f32 {
64 let total = self.run.as_ref().map_or(0, |run| run.jobs.len());
65 self.done() as f32 / total.max(1) as f32
66 }
67
68 fn failed(&self) -> bool {
69 self.state() == Some(State::Failed)
70 }
71
72 pub(super) fn tagging(&self) -> bool {
73 self.tagging
74 }
75}
76
77fn span(from: Option<&str>, to: Option<&str>, seconds: bool) -> Option<String> {
78 let from: jiff::Timestamp = from?.parse().ok()?;
79 let to = to
80 .and_then(|to| to.parse().ok())
81 .unwrap_or_else(jiff::Timestamp::now);
82 let total = to.duration_since(from).as_secs().max(0);
83 let (hours, minutes, rest) = (total / 3600, total / 60 % 60, total % 60);
84 Some(match (seconds, hours) {
85 (true, 0) => format!("{minutes}:{rest:02}"),
86 (true, _) => format!("{hours}:{minutes:02}:{rest:02}"),
87 (false, 0) => format!("{minutes}m"),
88 (false, _) => format!("{hours}h {minutes:02}m"),
89 })
90}
91
92fn run_label(state: State) -> &'static str {
93 let w = &w().builder_release;
94 match state {
95 State::Waiting => w.queued,
96 State::Running => w.building,
97 State::Success | State::Skipped => w.built,
98 State::Failed => w.build_failed,
99 }
100}
101
102fn job_status(state: State, palette: Palette) -> Div {
103 let w = &w().builder_release;
104 match state {
105 State::Waiting => caption_text(w.waiting, palette.muted),
106 State::Running => caption_text(w.running, palette.text),
107 State::Success => caption_text(w.done, palette.ok),
108 State::Skipped => caption_text(w.skipped, palette.muted),
109 State::Failed => caption_text(w.failed, palette.danger),
110 }
111}
112
113fn job_row(
114 job: &Job,
115 log: Option<&Vec<String>>,
116 seconds: bool,
117 entity: &Entity<Yumush>,
118 palette: Palette,
119) -> Div {
120 let state = State::of(&job.state);
121 let step = job.steps.last().map(|step| step.name.as_str());
122 let line = log.and_then(|log| log.last()).map(String::as_str);
123 let detail = match (state.finished(), step, line) {
124 (false, Some(step), Some(line)) => Some(format!("{step} · {line}")),
125 (_, Some(step), _) => Some(step.to_string()),
126 (_, None, line) => line.map(str::to_string),
127 };
128 let info = div()
129 .id(format!("ci_job_{}", job.id))
130 .w_full()
131 .flex()
132 .flex_col()
133 .cursor_pointer()
134 .child(
135 div()
136 .text_size(text(text::LABEL))
137 .text_color(palette.text)
138 .child(job.label().to_string()),
139 )
140 .children(detail.map(|detail| caption_text(detail, palette.muted).truncate()));
141 let id = job.id.clone();
142 let entity = entity.clone();
143 list_row()
144 .child(
145 div().flex_1().min_w_0().child(
146 Popover::new(format!("ci_log_{}", job.id))
147 .anchor(Anchor::TopLeft)
148 .appearance(false)
149 .trigger(Trigger::new(info))
150 .content(move |_, window, cx| log_sheet(&id, &entity, window, cx)),
151 ),
152 )
153 .child(job_status(state, palette))
154 .children(
155 span(
156 job.started_at.as_deref(),
157 job.finished_at.as_deref(),
158 seconds,
159 )
160 .map(|time| caption_text(time, palette.muted)),
161 )
162}
163
164fn log_sheet(job: &str, entity: &Entity<Yumush>, window: &mut Window, cx: &mut App) -> Div {
165 let palette = crate::gui::palette(cx);
166 let input = entity.read(cx).log_search.clone();
167 if !input.read(cx).focus_handle(cx).contains_focused(window, cx) {
168 input.update(cx, |state, cx| state.focus(window, cx));
169 }
170 let query = crate::gui::widget::search_text(&input, cx);
171 let yumush = entity.read(cx);
172 let live = &yumush.desk.live;
173 let lines: Rc<Vec<usize>> = Rc::new(
174 live.logs
175 .get(job)
176 .map(|log| {
177 log.iter()
178 .enumerate()
179 .filter(|(_, line)| query.is_empty() || line.to_lowercase().contains(&query))
180 .map(|(index, _)| index)
181 .collect()
182 })
183 .unwrap_or_default(),
184 );
185 let scroll = yumush.log_scroll.clone();
186 let count = lines.len();
187 if live.log_open.as_deref() != Some(job) {
188 scroll.scroll_to_item(count.saturating_sub(1), ScrollStrategy::Bottom);
189 let job = job.to_string();
190 entity.update(cx, |yumush, cx| yumush.open_ci_log(job, cx));
191 }
192 let job = job.to_string();
193 let entity = entity.clone();
194 crate::gui::widget::panel(palette)
195 .w(px(size::PAGE - space::XL))
196 .p(px(space::XS))
197 .flex()
198 .flex_col()
199 .gap(px(space::XS))
200 .child(crate::gui::sidebar::input_box(&input, palette))
201 .child(
202 uniform_list(format!("ci_log_lines_{job}"), count, move |range, _, cx| {
203 let palette = crate::gui::palette(cx);
204 let Some(log) = entity.read(cx).desk.live.logs.get(&job) else {
205 return Vec::new();
206 };
207 lines[range]
208 .iter()
209 .filter_map(|&index| log.get(index))
210 .map(|line| {
211 div()
212 .h(px(LOG_LINE))
213 .px(px(space::XS))
214 .whitespace_nowrap()
215 .text_size(text(text::CAPTION))
216 .text_color(palette.muted)
217 .child(line.clone())
218 })
219 .collect()
220 })
221 .with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained)
222 .track_scroll(&scroll)
223 .h(px((count as f32 * LOG_LINE).clamp(LOG_LINE, size::SHEET))),
224 )
225}
226
227impl Yumush {
228 pub(in crate::gui) fn watch_ci(&mut self, window: &mut Window, cx: &mut Context<Self>) {
229 if !self.is_builder() || self.desk.live.watch.is_some() {
230 return;
231 }
232 let network = self.network.clone();
233 cx.spawn_in(window, async move |this, cx| {
234 let Ok(Some(repo)) = network.call(GetForge).await else {
235 return;
236 };
237 let (watch, mut events) = ci::watch(repo.clone());
238 let started = this.update(cx, |yumush, _| {
239 yumush.desk.live.repo = Some(repo);
240 yumush.desk.live.watch = Some(watch);
241 });
242 if started.is_err() {
243 return;
244 }
245 cx.spawn(async move |cx| {
246 while let Some(event) = events.recv().await {
247 if this
248 .update(cx, |yumush, cx| yumush.ci_event(event, cx))
249 .is_err()
250 {
251 break;
252 }
253 }
254 })
255 .detach();
256 })
257 .detach();
258 cx.spawn_in(window, async move |this, cx| {
259 loop {
260 cx.background_executor().timer(TICK).await;
261 let Ok(watching) = this.update_in(cx, |yumush, window, cx| {
262 if yumush.desk.live.live() {
263 window.refresh();
264 cx.notify();
265 }
266 yumush.desk.live.watch.is_some()
267 }) else {
268 break;
269 };
270 if !watching {
271 break;
272 }
273 }
274 })
275 .detach();
276 }
277
278 fn ci_event(&mut self, event: Event, cx: &mut Context<Self>) {
279 let live = &mut self.desk.live;
280 match event {
281 Event::Run(run) => {
282 if live.run.as_ref().map(|old| old.number) != Some(run.number) {
283 live.logs.clear();
284 live.dismissed = false;
285 live.seen_live = false;
286 }
287 if !State::of(&run.state).finished() {
288 live.seen_live = true;
289 }
290 live.run = Some(run);
291 }
292 Event::Line { job, line } => {
293 let log = live.logs.entry(job).or_default();
294 if log.len() >= LOG_MAX {
295 log.drain(..LOG_MAX / 10);
296 }
297 log.push(line);
298 }
299 }
300 cx.notify();
301 }
302
303 fn open_ci_log(&mut self, job: String, cx: &mut Context<Self>) {
304 let live = &mut self.desk.live;
305 live.log_open = Some(job.clone());
306 let finished = live.run.as_ref().is_some_and(|run| {
307 run.jobs
308 .iter()
309 .any(|item| item.id == job && State::of(&item.state).finished())
310 });
311 let Some(repo) = live.repo.clone().filter(|_| finished) else {
312 return;
313 };
314 if live.logs.get(&job).is_some_and(|log| !log.is_empty()) {
315 return;
316 }
317 cx.spawn(async move |this, cx| {
318 let fetched = cx
319 .background_executor()
320 .spawn({
321 let job = job.clone();
322 async move { ci::whole_log(&repo, &job) }
323 })
324 .await;
325 let Some(text) = fetched else {
326 return;
327 };
328 let _ = this.update(cx, |yumush, cx| {
329 let log: Vec<String> = text
330 .lines()
331 .filter(|line| !ci::marker(line))
332 .map(str::to_string)
333 .collect();
334 let start = log.len().saturating_sub(LOG_MAX);
335 yumush.desk.live.logs.insert(job, log[start..].to_vec());
336 cx.notify();
337 });
338 })
339 .detach();
340 }
341
342 pub(super) fn create_tag(&mut self, window: &mut Window, cx: &mut Context<Self>) {
343 let tag = self.release_tag_text(cx);
344 if tag.is_empty() || self.desk.live.tagging {
345 return;
346 }
347 self.desk.live.tagging = true;
348 cx.notify();
349 let network = self.network.clone();
350 cx.spawn_in(window, async move |this, cx| {
351 let result = network.call(CreateTag { tag }).await;
352 let _ = this.update(cx, |yumush, cx| {
353 yumush.desk.live.tagging = false;
354 cx.notify();
355 });
356 if let Err(error) = result {
357 notify_error(&this, cx, error);
358 }
359 })
360 .detach();
361 }
362
363 fn run_head(&self, palette: Palette) -> Option<Div> {
364 let live = &self.desk.live;
365 let run = live.run.as_ref()?;
366 let state = State::of(&run.state);
367 let time = span(
368 run.started_at.as_deref(),
369 run.finished_at.as_deref(),
370 self.settings.clock_seconds,
371 )
372 .unwrap_or_default();
373 let name = run.tag().unwrap_or(&run.reference);
374 let aside = if state.finished() {
375 time
376 } else {
377 format!("{} / {} · {time}", live.done(), run.jobs.len())
378 };
379 Some(
380 div()
381 .flex()
382 .justify_between()
383 .pb(px(space::XS))
384 .text_size(text(text::LABEL))
385 .child(
386 div()
387 .text_color(if live.failed() {
388 palette.danger
389 } else {
390 palette.text
391 })
392 .child(format!("#{} · {name} · {}", run.number, run_label(state))),
393 )
394 .child(div().text_color(palette.muted).child(aside)),
395 )
396 }
397
398 fn ci_rows(
399 &self,
400 entity: &Entity<Self>,
401 fit: impl Fn(Div) -> Div,
402 palette: Palette,
403 ) -> Vec<Div> {
404 let live = &self.desk.live;
405 let seconds = self.settings.clock_seconds;
406 live.run.as_ref().map_or_else(Vec::new, |run| {
407 run.jobs
408 .iter()
409 .map(|job| {
410 fit(job_row(
411 job,
412 live.logs.get(&job.id),
413 seconds,
414 entity,
415 palette,
416 ))
417 })
418 .collect()
419 })
420 }
421
422 fn import_run_button(&self, entity: &Entity<Self>, palette: Palette) -> Option<AnyElement> {
423 let run = self.desk.live.run.as_ref()?;
424 let tag = run.tag()?.to_string();
425 (State::of(&run.state) == State::Success).then(|| {
426 parts::button(
427 "ci_import",
428 w().builder_release.import,
429 Press::Primary,
430 palette.tokens,
431 entity_action(entity, move |yumush, window, cx| {
432 yumush.import_tag(tag.clone(), window, cx)
433 }),
434 )
435 .into_any_element()
436 })
437 }
438
439 pub(super) fn ci_card(&self, entity: &Entity<Self>, palette: Palette) -> Option<Div> {
440 let head = self.run_head(palette)?;
441 Some(
442 card(palette)
443 .child(head)
444 .child(parts::track(
445 Fill::Part(self.desk.live.share()),
446 self.desk.live.failed(),
447 palette.tokens,
448 ))
449 .children(self.ci_rows(entity, |row| row, palette))
450 .children(
451 self.import_run_button(entity, palette)
452 .map(|button| list_row().justify_end().child(button)),
453 ),
454 )
455 }
456
457 pub(in crate::gui) fn build_control(
458 &self,
459 entity: &Entity<Self>,
460 palette: Palette,
461 ) -> Option<AnyElement> {
462 let live = &self.desk.live;
463 if !live.shown() {
464 return None;
465 }
466 let run = live.run.as_ref()?;
467 let state = State::of(&run.state);
468 let aside = if state.finished() {
469 span(
470 run.started_at.as_deref(),
471 run.finished_at.as_deref(),
472 self.settings.clock_seconds,
473 )
474 .unwrap_or_default()
475 } else {
476 format!("{} / {}", live.done(), run.jobs.len())
477 };
478 let failed = live.failed();
479 let trigger = hoverable(
480 "build_trigger",
481 div()
482 .flex()
483 .flex_col()
484 .gap(px(space::XS))
485 .py(px(space::XS))
486 .px(px(space::SM))
487 .rounded(px(radius::MD))
488 .child(
489 div()
490 .flex()
491 .justify_between()
492 .text_size(text(text::LABEL))
493 .child(
494 div()
495 .text_color(if failed { palette.danger } else { palette.text })
496 .child(run_label(state)),
497 )
498 .child(div().text_color(palette.muted).child(aside)),
499 )
500 .child(parts::track(
501 Fill::Part(live.share()),
502 failed,
503 palette.tokens,
504 )),
505 palette,
506 );
507 let entity = entity.clone();
508 Some(
509 Popover::new("build_status")
510 .anchor(Anchor::BottomLeft)
511 .appearance(false)
512 .trigger(Trigger::new(trigger))
513 .content(move |_, _, cx| {
514 let popover = cx.entity();
515 let palette = crate::gui::palette(cx);
516 entity.read(cx).build_sheet(&entity, &popover, palette)
517 })
518 .into_any_element(),
519 )
520 }
521
522 fn build_sheet(
523 &self,
524 entity: &Entity<Self>,
525 popover: &Entity<PopoverState>,
526 palette: Palette,
527 ) -> Div {
528 let w = &w().builder_release;
529 let open = parts::button(
530 "build_open_releases",
531 w.open_releases,
532 Press::Plain,
533 palette.tokens,
534 yumush_action(entity, popover, |yumush, window, cx| {
535 yumush.show_view(View::Builder, window, cx);
536 yumush.select_builder_tab(BuilderTab::Releases, window, cx);
537 }),
538 );
539 let dismiss = (!self.desk.live.live()).then(|| {
540 parts::button(
541 "build_sheet_dismiss",
542 w.dismiss,
543 Press::Plain,
544 palette.tokens,
545 yumush_action(entity, popover, |yumush, _, cx| {
546 yumush.desk.live.dismissed = true;
547 cx.notify();
548 }),
549 )
550 });
551 parts::popover(palette.tokens)
552 .w(px(size::SHEET))
553 .p(px(space::MD))
554 .children(self.run_head(palette))
555 .children(self.ci_rows(
556 entity,
557 |row| row.min_h(px(size::CONTROL)).py(px(space::XXS)),
558 palette,
559 ))
560 .child(
561 div()
562 .pt(px(space::SM))
563 .flex()
564 .justify_between()
565 .child(open)
566 .children(self.import_run_button(entity, palette))
567 .children(dismiss),
568 )
569 }
570}