vig 0.16.0

Read-only TUI cockpit for busy repositories - git, GitHub PRs/CI/projects, containers and processes at a glance
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
//! Date math and span resolution for the Roadmap layout. No date crate:
//! days are counted from the civil epoch (1970-01-01) with Howard
//! Hinnant's algorithm, which is all a timeline needs.

use crate::projects::domain::types::{Board, ProjectItem};
use serde::{Deserialize, Serialize};

/// Days since 1970-01-01 for a civil date.
pub fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
    let y = if m <= 2 { y - 1 } else { y };
    let era = if y >= 0 { y } else { y - 399 } / 400;
    let yoe = y - era * 400;
    let mp = (m + 9) % 12;
    let doy = (153 * mp + 2) / 5 + d - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    era * 146097 + doe - 719468
}

/// Civil date for days since 1970-01-01.
pub fn civil_from_days(z: i64) -> (i64, i64, i64) {
    let z = z + 719468;
    let era = if z >= 0 { z } else { z - 146096 } / 146097;
    let doe = z - era * 146097;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    (if m <= 2 { y + 1 } else { y }, m, d)
}

/// `YYYY-MM-DD` → days since the epoch.
pub fn parse_date(s: &str) -> Option<i64> {
    let s = s.get(..10)?;
    let mut parts = s.split('-');
    let y: i64 = parts.next()?.parse().ok()?;
    let m: i64 = parts.next()?.parse().ok()?;
    let d: i64 = parts.next()?.parse().ok()?;
    if !(1..=12).contains(&m) || !(1..=31).contains(&d) {
        return None;
    }
    // Impossible days (2026-02-31) would silently shift into the next
    // month; only dates that survive the round trip are real.
    let days = days_from_civil(y, m, d);
    (civil_from_days(days) == (y, m, d)).then_some(days)
}

/// Days since the epoch for "now".
pub fn today() -> i64 {
    let secs = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0);
    secs.div_euclid(86400)
}

/// Where an item's span comes from: a start / end date field pair, a
/// single date field, or an iteration field — resolved once per board.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SpanSpec {
    /// Item key of the start date field.
    pub start: Option<String>,
    /// Item key of the end date field.
    pub end: Option<String>,
    /// Item key of the iteration field (used when the dates say nothing).
    pub iteration: Option<String>,
}

/// Find the fields that give items a time span. Date fields are `.fields`
/// entries whose value on some item looks like `YYYY-MM-DD`; a name
/// containing `start` is the span start, one containing `target`, `end`
/// or `due` the span end. A single date field is both. Iteration values
/// (objects with `startDate` / `duration`) fill in for items without
/// dates.
pub fn span_spec(board: &Board) -> SpanSpec {
    let mut dates: Vec<(String, String)> = Vec::new(); // (name lowercased, key)
    let mut iteration = None;
    for field in &board.fields {
        let key = field.item_key();
        if field.kind == "ProjectV2IterationField" {
            iteration.get_or_insert(key);
            continue;
        }
        let has_date = board.items.iter().any(|i| {
            matches!(i.fields.get(&key), Some(serde_json::Value::String(s)) if parse_date(s).is_some())
        });
        if has_date {
            dates.push((field.name.to_lowercase(), key));
        }
    }
    let find = |words: &[&str]| {
        dates
            .iter()
            .find(|(name, _)| words.iter().any(|w| name.contains(w)))
            .map(|(_, key)| key.clone())
    };
    let mut start = find(&["start", "begin"]);
    let mut end = find(&["target", "end", "due", "finish"]);
    if start.is_none() && end.is_none() {
        // A single (or first) date field is both ends of a point span.
        if let Some((_, key)) = dates.first() {
            start = Some(key.clone());
            end = Some(key.clone());
        }
    }
    SpanSpec {
        start,
        end,
        iteration,
    }
}

/// The item's `(start, end)` in epoch days, if any of the span fields has
/// a value. A single date gives a one-day span; a start / end pair takes
/// whichever ends are present; an iteration covers its start + duration.
pub fn item_span(item: &ProjectItem, spec: &SpanSpec) -> Option<(i64, i64)> {
    let date_of = |key: &Option<String>| {
        key.as_ref()
            .and_then(|k| item.fields.get(k))
            .and_then(|v| v.as_str())
            .and_then(parse_date)
    };
    let (s, e) = (date_of(&spec.start), date_of(&spec.end));
    if s.is_some() || e.is_some() {
        let start = s.or(e).unwrap();
        let end = e.or(s).unwrap();
        return Some((start.min(end), start.max(end)));
    }
    let it = spec
        .iteration
        .as_ref()
        .and_then(|k| item.fields.get(k))?
        .as_object()?;
    let start = it
        .get("startDate")
        .and_then(|v| v.as_str())
        .and_then(parse_date)?;
    let days = it
        .get("duration")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(14);
    Some((start, start + days.max(1) - 1))
}

/// One iteration seen on the board's items: a shaded band on the scale.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Iteration {
    pub title: String,
    pub start: i64,
    pub end: i64,
}

/// Distinct iterations across the items, sorted by start.
pub fn iterations(board: &Board, spec: &SpanSpec) -> Vec<Iteration> {
    let Some(key) = &spec.iteration else {
        return Vec::new();
    };
    let mut out: Vec<Iteration> = Vec::new();
    for item in &board.items {
        let Some(it) = item.fields.get(key).and_then(|v| v.as_object()) else {
            continue;
        };
        let Some(start) = it
            .get("startDate")
            .and_then(|v| v.as_str())
            .and_then(parse_date)
        else {
            continue;
        };
        let days = it
            .get("duration")
            .and_then(serde_json::Value::as_i64)
            .unwrap_or(14);
        let title = it
            .get("title")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();
        let iter = Iteration {
            title,
            start,
            end: start + days.max(1) - 1,
        };
        if !out.contains(&iter) {
            out.push(iter);
        }
    }
    out.sort_by_key(|i| i.start);
    out
}

/// Where the roadmap opens and at which scale, from the config
/// (`projects-roadmap { … }`, overridden per view by `roadmap { … }`).
/// `None` keeps the built-in behaviour: the timeline starts at the
/// earliest span, at the week scale.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct RoadmapSettings {
    /// First visible day as an offset from today, in days (`"-7d"`).
    /// Earlier items are reachable by scrolling left.
    #[serde(default)]
    pub start: Option<i64>,
    /// The initial zoom.
    #[serde(default)]
    pub zoom: Option<Zoom>,
}

impl RoadmapSettings {
    /// These settings with `base` filling what they leave unset.
    pub fn or(self, base: RoadmapSettings) -> Self {
        Self {
            start: self.start.or(base.start),
            zoom: self.zoom.or(base.zoom),
        }
    }
}

/// A day offset such as `"-7d"`, `"+2w"`, `"-1m"` or `"0d"` (a month is
/// 30 days) in days. `None` for anything else.
pub fn parse_offset(s: &str) -> Option<i64> {
    let s = s.trim();
    let (sign, rest) = match s.strip_prefix('-') {
        Some(r) => (-1, r),
        None => (1, s.strip_prefix('+').unwrap_or(s)),
    };
    let (num, unit) = rest.split_at(rest.len().checked_sub(1)?);
    let num = num.trim();
    if num.is_empty() || !num.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    let n: i64 = num.parse().ok()?;
    let per_unit = match unit {
        "d" => 1,
        "w" => 7,
        "m" => 30,
        _ => return None,
    };
    Some(sign * n * per_unit)
}

/// Zoom level of the time scale.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Zoom {
    /// 1 cell = 3 days.
    Month,
    /// 1 cell = 1 day.
    Week,
    /// 3 cells = 1 day.
    Day,
}

impl Zoom {
    /// `"month"` / `"week"` / `"day"` as the config spells them.
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "month" => Some(Self::Month),
            "week" => Some(Self::Week),
            "day" => Some(Self::Day),
            _ => None,
        }
    }

    pub fn label(self) -> &'static str {
        match self {
            Self::Month => "month",
            Self::Week => "week",
            Self::Day => "day",
        }
    }

    pub fn zoom_in(self) -> Self {
        match self {
            Self::Month => Self::Week,
            Self::Week | Self::Day => Self::Day,
        }
    }

    pub fn zoom_out(self) -> Self {
        match self {
            Self::Day => Self::Week,
            Self::Week | Self::Month => Self::Month,
        }
    }

    /// Cell column for a day, relative to `origin` (may be negative).
    pub fn x(self, day: i64, origin: i64) -> i64 {
        let d = day - origin;
        match self {
            Self::Month => d.div_euclid(3),
            Self::Week => d,
            Self::Day => d * 3,
        }
    }

    /// The last cell column a day covers (bars end inclusively).
    pub fn x_end(self, day: i64, origin: i64) -> i64 {
        match self {
            Self::Day => self.x(day, origin) + 2,
            _ => self.x(day, origin),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::projects::domain::types::tests::board;

    #[test]
    fn civil_round_trip_and_parse() {
        for (y, m, d) in [(1970, 1, 1), (2026, 9, 7), (2000, 2, 29), (1969, 12, 31)] {
            let z = days_from_civil(y, m, d);
            assert_eq!(civil_from_days(z), (y, m, d));
        }
        assert_eq!(parse_date("1970-01-01"), Some(0));
        assert_eq!(parse_date("1970-01-02"), Some(1));
        assert_eq!(parse_date("2026-13-01"), None);
        assert_eq!(parse_date("2026-02-31"), None);
        assert_eq!(parse_date("2026-02-29"), None); // not a leap year
        assert!(parse_date("2028-02-29").is_some());
        assert_eq!(parse_date("not a date"), None);
        // Timestamps work too (only the date part is read).
        assert_eq!(parse_date("1970-01-02T10:00:00Z"), Some(1));
    }

    #[test]
    fn span_spec_finds_start_and_iteration_fields() {
        // The fixture's I2 carries `"start date": "2026-08-25"` and a
        // Sprint 3 iteration, so both resolve from the items.
        let spec = span_spec(&board());
        assert_eq!(spec.start.as_deref(), Some("start date"));
        // No end-named date field exists.
        assert_eq!(spec.end, None);
        assert_eq!(spec.iteration.as_deref(), Some("iteration"));

        // A board whose only date field is end-named gives a point span.
        let mut b = board();
        for item in &mut b.items {
            item.fields.remove("start date");
        }
        b.fields.push(crate::projects::domain::types::ProjectField {
            id: "FX".into(),
            name: "Due date".into(),
            kind: "ProjectV2Field".into(),
            options: vec![],
        });
        b.items[0].fields.insert(
            "due date".into(),
            serde_json::Value::String("2026-09-05".into()),
        );
        let spec = span_spec(&b);
        assert_eq!(spec.start, None);
        assert_eq!(spec.end.as_deref(), Some("due date"));
    }

    #[test]
    fn item_spans_from_dates_and_iterations() {
        let spec = SpanSpec {
            start: Some("start date".into()),
            end: Some("target date".into()),
            iteration: Some("iteration".into()),
        };
        let mut item = board().items[0].clone();
        item.fields.insert(
            "start date".into(),
            serde_json::Value::String("2026-09-01".into()),
        );
        item.fields.insert(
            "target date".into(),
            serde_json::Value::String("2026-09-05".into()),
        );
        let (s, e) = item_span(&item, &spec).unwrap();
        assert_eq!(e - s, 4);

        // End only: a one-day span at the end date.
        let mut only_end = board().items[0].clone();
        only_end.fields.insert(
            "target date".into(),
            serde_json::Value::String("2026-09-05".into()),
        );
        let (s, e) = item_span(&only_end, &spec).unwrap();
        assert_eq!(s, e);

        // Iteration fallback: start + duration - 1.
        let mut it = board().items[0].clone();
        it.fields.insert(
            "iteration".into(),
            serde_json::json!({"title": "It 1", "startDate": "2026-09-01", "duration": 14}),
        );
        let (s, e) = item_span(&it, &spec).unwrap();
        assert_eq!(e - s, 13);

        // Nothing set: no span.
        assert_eq!(item_span(&board().items[0], &spec), None);
    }

    #[test]
    fn iterations_are_distinct_and_sorted() {
        let mut b = board();
        let spec = SpanSpec {
            iteration: Some("iteration".into()),
            ..Default::default()
        };
        for (i, start) in [(0usize, "2026-09-15"), (1, "2026-09-01"), (3, "2026-09-01")] {
            b.items[i].fields.insert(
                "iteration".into(),
                serde_json::json!({"title": start, "startDate": start, "duration": 14}),
            );
        }
        let its = iterations(&b, &spec);
        assert_eq!(its.len(), 2);
        assert!(its[0].start < its[1].start);
    }

    #[test]
    fn zoom_scales_and_cycles() {
        assert_eq!(Zoom::Week.x(10, 0), 10);
        assert_eq!(Zoom::Day.x(2, 0), 6);
        assert_eq!(Zoom::Month.x(6, 0), 2);
        assert_eq!(Zoom::Month.x(-3, 0), -1);
        assert_eq!(Zoom::Week.zoom_in(), Zoom::Day);
        assert_eq!(Zoom::Day.zoom_in(), Zoom::Day);
        assert_eq!(Zoom::Week.zoom_out(), Zoom::Month);
        assert_eq!(Zoom::Month.zoom_out(), Zoom::Month);
    }

    #[test]
    fn offsets_parse_in_days_weeks_and_months() {
        assert_eq!(parse_offset("-7d"), Some(-7));
        assert_eq!(parse_offset("+2w"), Some(14));
        assert_eq!(parse_offset("2w"), Some(14));
        assert_eq!(parse_offset("-1m"), Some(-30));
        assert_eq!(parse_offset("0d"), Some(0));
        assert_eq!(parse_offset(" -3d "), Some(-3));
        for bad in ["", "d", "7", "-7x", "seven d", "-7 days", "--7d"] {
            assert_eq!(parse_offset(bad), None, "{bad:?}");
        }
        assert_eq!(Zoom::parse("month"), Some(Zoom::Month));
        assert_eq!(Zoom::parse("Week"), None);
        let view = RoadmapSettings {
            start: None,
            zoom: Some(Zoom::Day),
        };
        let base = RoadmapSettings {
            start: Some(-7),
            zoom: Some(Zoom::Month),
        };
        assert_eq!(
            view.or(base),
            RoadmapSettings {
                start: Some(-7),
                zoom: Some(Zoom::Day)
            }
        );
    }
}