thirdshift 0.14.10

Turn a GitHub issue into a ready-for-review pull request, unattended
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! Time views over the same complete observations as status --all --json.
use std::collections::{BTreeMap, BTreeSet};

use anyhow::Result;
use chrono::{DateTime, FixedOffset, Local};

use crate::config::UserConfig;
use crate::logs::command_record::{Issue, StageName};
use crate::logs::reading::{Command, Entry, Observation, Snapshot};

pub(crate) struct Views {
    pub lanes: Vec<Vec<Run>>,
    pub grids: Vec<Grid>,
    pub start: String,
    pub end: String,
}

#[derive(Clone)]
pub(crate) struct Run {
    pub subject: String,
    pub title: String,
    pub state: String,
    pub selector: String,
    pub peek_url: String,
    pub log_url: String,
    pub issue_url: Option<String>,
    pub issue_label: String,
    pub stages: Vec<Stage>,
    pub context: String,
    pub group_start: bool,
    repository: String,
    started: Option<DateTime<FixedOffset>>,
    ended: Option<i64>,
    stage_metadata: bool,
}

#[derive(Clone)]
pub(crate) struct Stage {
    pub name: String,
    pub running: bool,
    pub text: String,
    pub seconds: String,
    pub usual: String,
    pub left: f64,
    pub width: f64,
}

pub(crate) struct Grid {
    pub repository: String,
    pub groups: Vec<Group>,
    pub runs: Vec<Run>,
    pub rows: Vec<GridRow>,
}

pub(crate) struct GridRow {
    pub name: String,
    pub cells: Vec<Cell>,
}

pub(crate) struct Cell {
    pub text: String,
    pub running: bool,
    pub usual: String,
    pub group_start: bool,
}

#[derive(Clone)]
pub(crate) struct Group {
    pub identity: String,
    pub subject: String,
    pub started: String,
    pub runs: Vec<Run>,
}

impl Group {
    fn new(run: Run, started: &str) -> Self {
        Self {
            identity: run.selector.clone(),
            subject: run.subject.clone(),
            started: if run.started.is_some() {
                started.into()
            } else {
                "unknown".into()
            },
            runs: vec![run],
        }
    }
}

fn timestamp(value: &str) -> Option<i64> {
    DateTime::parse_from_rfc3339(value)
        .ok()
        .map(|time| time.timestamp())
}

fn subject(kind: &str, repository: &str, issue: Option<&Issue>) -> String {
    let kind = crate::logs::display_name(kind);
    issue.map_or_else(
        || format!("{kind} on {repository}"),
        |issue| format!("{kind} · {repository}#{}", issue.number),
    )
}

fn issue_link(issue: Option<&Issue>) -> (Option<String>, String) {
    match issue {
        Some(issue) if issue.url.starts_with("https://") => {
            (Some(issue.url.clone()), format!("Issue #{}", issue.number))
        }
        _ => (None, String::new()),
    }
}

fn run(command: &Command, now: DateTime<Local>, cutoff: i64) -> Run {
    let record = &command.record;
    let selector = Observation::Record(command).selector().unwrap_or_default();
    let live_until = (command.state == "live").then_some(now.fixed_offset());
    let now = now.timestamp();
    let stages = record
        .stage_times(live_until)
        .enumerate()
        .map(|(index, timing)| {
            let stage = timing.stage;
            let began = timing.began.map(|time| time.timestamp());
            let end = timing.ended.map(|time| time.timestamp());
            let seconds = timing.seconds();
            let state = if index + 1 < record.stages.len() {
                "Complete"
            } else if command.state == "live" {
                "Running"
            } else if command.state == "died" {
                "Died"
            } else if record.outcome.as_deref() == Some("merged") {
                "Complete"
            } else {
                record.outcome.as_deref().unwrap_or("Unknown")
            };
            let duration = seconds
                .map(|seconds| super::age(seconds as i64))
                .unwrap_or_else(|| "time unknown".into());
            // Clip only the drawn interval; the text retains the full stage time.
            let (left, width) =
                began
                    .zip(end)
                    .filter(|_| seconds.is_some())
                    .map_or((0.0, 0.0), |(start, end)| {
                        let start = start.clamp(cutoff, now);
                        let end = end.clamp(cutoff, now);
                        let scale = 100.0 / (now - cutoff) as f64;
                        (
                            (start - cutoff) as f64 * scale,
                            (end - start).max(0) as f64 * scale,
                        )
                    });
            Stage {
                name: stage.name.clone(),
                running: command.state == "live" && index + 1 == record.stages.len(),
                text: format!("{state} · {duration}"),
                seconds: seconds
                    .map(|seconds| seconds.to_string())
                    .unwrap_or_default(),
                usual: if StageName::is_dispatch(&stage.name) {
                    "—".into()
                } else {
                    command
                        .usual_ranges
                        .get(&stage.name)
                        .map(|range| range.text())
                        .unwrap_or_else(|| "Not enough samples".into())
                },
                left,
                width,
            }
        })
        .collect();
    let (issue_url, issue_label) = issue_link(record.issue.as_ref());
    Run {
        subject: subject(&record.kind, &record.repository, record.issue.as_ref()),
        title: record
            .issue
            .as_ref()
            .and_then(|issue| issue.title.clone())
            .unwrap_or_else(|| record.name.clone()),
        state: if command.state == "ended" {
            record.outcome.clone().unwrap_or_else(|| "ended".into())
        } else {
            command.state.into()
        },
        peek_url: super::inspect::url("/peek", &selector, None),
        log_url: super::inspect::url("/log", &selector, None),
        issue_url,
        issue_label,
        selector,
        repository: record.repository.clone(),
        context: String::new(),
        group_start: true,
        stages,
        started: DateTime::parse_from_rfc3339(&record.started_at).ok(),
        ended: record.ended_at.as_deref().and_then(timestamp),
        stage_metadata: true,
    }
}

// Membership follows exact recorded ancestry, never an issue number shared by attempts.
fn collect(
    command: &Command,
    now: DateTime<Local>,
    cutoff: i64,
    spec: Option<usize>,
    context: &str,
    groups: &mut Vec<Group>,
    runs: &mut Vec<Run>,
) {
    let mut current = run(command, now, cutoff);
    runs.push(current.clone());
    current.context = context.into();
    let spec = if command.record.kind == "Run"
        && let Some(index) = spec
    {
        current.context = format!(
            "Ticket of {} · Started {}",
            groups[index].subject, groups[index].started
        );
        current.group_start = false;
        groups[index].runs.push(current);
        spec
    } else {
        let index = groups.len();
        groups.push(Group::new(current, &command.record.started_at));
        (command.record.kind == "Spec run").then_some(index)
    };
    let parent = subject(
        &command.record.kind,
        &command.record.repository,
        command.record.issue.as_ref(),
    );
    for dispatched in &command.dispatched {
        collect(
            dispatched,
            now,
            cutoff,
            spec,
            &format!("Dispatched by {parent}"),
            groups,
            runs,
        );
    }
    for child in &command.children {
        collect(
            child,
            now,
            cutoff,
            spec,
            &format!("Child of {parent}"),
            groups,
            runs,
        );
    }
}

fn grid(repository: String, groups: Vec<Group>) -> Grid {
    let runs: Vec<_> = groups.iter().flat_map(|group| group.runs.clone()).collect();
    let names: BTreeSet<_> = runs
        .iter()
        .flat_map(|run| {
            run.stages
                .iter()
                .map(|stage| (StageName::order(&stage.name), stage.name.clone()))
        })
        .collect();
    let rows = names
        .into_iter()
        .map(|(_, name)| {
            let cells = runs
                .iter()
                .map(|run| {
                    let stages: Vec<_> = run
                        .stages
                        .iter()
                        .filter(|stage| stage.name == name)
                        .collect();
                    let text = if !run.stage_metadata {
                        "Unknown · no stage times retained".into()
                    } else if stages.is_empty() {
                        "Not reached · —".into()
                    } else {
                        stages
                            .iter()
                            .map(|stage| stage.text.as_str())
                            .collect::<Vec<_>>()
                            .join("; ")
                    };
                    let usual = if StageName::is_dispatch(&name) {
                        "—".into()
                    } else {
                        runs.iter()
                            .filter(|sample| sample.repository == run.repository)
                            .flat_map(|sample| &sample.stages)
                            .find(|stage| stage.name == name)
                            .map(|stage| stage.usual.clone())
                            .unwrap_or_else(|| "Not enough samples".into())
                    };
                    Cell {
                        text,
                        running: stages.iter().any(|stage| stage.running),
                        usual,
                        group_start: run.group_start,
                    }
                })
                .collect();
            GridRow { name, cells }
        })
        .collect();
    Grid {
        repository,
        groups,
        runs,
        rows,
    }
}

pub(crate) fn load(config: &UserConfig, hours: f64, by_repository: bool) -> Result<Views> {
    let now = Local::now();
    let cutoff = now - chrono::Duration::seconds((hours * 3600.0) as i64);
    let snapshot = Snapshot::load_with_silence(&config.logs_dir, now, config.silent_interval)?;
    let mut lanes = Vec::new();
    let mut groups = Vec::new();
    for entry in snapshot.entries() {
        let mut runs = Vec::new();
        match entry {
            Entry::Record(command) => {
                collect(
                    command,
                    now,
                    cutoff.timestamp(),
                    None,
                    "",
                    &mut groups,
                    &mut runs,
                );
            }
            Entry::History(command) => {
                let selector = Observation::History(command).selector().unwrap_or_default();
                let (issue_url, issue_label) = issue_link(command.issue.as_ref());
                runs.push(Run {
                    subject: subject(&command.kind, &command.repository, command.issue.as_ref()),
                    title: String::new(),
                    state: command
                        .outcome
                        .clone()
                        .unwrap_or_else(|| command.state.into()),
                    peek_url: super::inspect::url("/peek", &selector, None),
                    log_url: super::inspect::url("/log", &selector, None),
                    issue_url,
                    issue_label,
                    selector,
                    repository: command.repository.clone(),
                    context: String::new(),
                    group_start: true,
                    stages: Vec::new(),
                    started: DateTime::parse_from_rfc3339(&command.started_at).ok(),
                    ended: command.ended_at.as_deref().and_then(timestamp),
                    stage_metadata: false,
                });
                groups.push(Group::new(runs[0].clone(), &command.started_at));
            }
        }
        if runs.iter().any(|run| {
            run.state == "live"
                || run.started.is_some_and(|start| {
                    let start = start.timestamp();
                    start <= now.timestamp() && run.ended.unwrap_or(start) > cutoff.timestamp()
                })
        }) {
            lanes.push(runs);
        }
    }
    lanes.sort_by_key(|runs| {
        std::cmp::Reverse(
            runs.first()
                .and_then(|run| run.started.map(|start| start.timestamp())),
        )
    });
    groups.sort_by_key(|group| {
        (
            std::cmp::Reverse(group.runs[0].started),
            group.identity.clone(),
        )
    });
    for group in &mut groups {
        group.runs[1..].sort_by_key(|run| (std::cmp::Reverse(run.started), run.selector.clone()));
    }
    let grids = if by_repository {
        let mut repositories: BTreeMap<String, Vec<Group>> = BTreeMap::new();
        for group in groups {
            repositories
                .entry(group.runs[0].repository.clone())
                .or_default()
                .push(group);
        }
        repositories
            .into_iter()
            .map(|(repository, groups)| grid(repository, groups))
            .collect()
    } else if groups.is_empty() {
        Vec::new()
    } else {
        vec![grid("All runs".into(), groups)]
    };
    Ok(Views {
        lanes,
        grids,
        start: cutoff.format("%Y-%m-%d %H:%M %Z").to_string(),
        end: now.format("%Y-%m-%d %H:%M %Z").to_string(),
    })
}