git/orchard/main
updater/render/build.py
424 lines13 KB last change raw · history
  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
"""The live build dashboard.

Layout, top to bottom:

    DONE      completed packages, oldest first, newest appended at the bottom
    BUILDING  the remaining dependency graph, with shared deps marked
    footer    live build/download/time counters

`dashboard=False` renders the DONE feed alone. That is not a degraded mode: it is
the ledger form, where completed packages simply scroll into terminal history
instead of being redrawn. It is what the runtime toggle switches to.
"""

from __future__ import annotations

from dataclasses import dataclass, field

from rich.text import Text

from ..buildgraph import Graph
from ..icons import Glyphs
from ..procwatch import BuildState, format_duration
from ..theme import Theme
from .base import Columns, Screen, human_bytes, truncate

STATE_GLYPH = {"done": "done", "run": "run", "wait": "wait", "fail": "fail"}
STATE_ROLE = {"done": "ok", "run": "accent", "wait": "muted", "fail": "err"}


@dataclass
class FeedEntry:
    """One package that has finished. Enters the feed exactly once."""

    name: str
    version: str = ""
    elapsed: float = 0.0
    state: str = "done"  # done | fail
    shared: bool = False
    note: str = ""

    @property
    def clock(self) -> str:
        return format_duration(self.elapsed)


@dataclass
class Totals:
    """Everything the footer reports. All of it is measured, none of it guessed."""

    total: int = 0
    elapsed: float = 0.0
    eta: float | None = None
    download_bytes: int = 0
    download_rate: float = 0.0
    download_remaining: int = 0
    download_eta: float | None = None


@dataclass
class TreeNode:
    name: str
    version: str = ""
    state: str = "wait"
    note: str = ""
    elapsed: str = ""
    shared: bool = False
    children: list[TreeNode] = field(default_factory=list)


def build_tree(
    graph: Graph,
    *,
    completed: set[str],
    running: set[str],
    failed: set[str],
    states: dict[str, BuildState],
) -> list[TreeNode]:
    """Turn the dependency graph into a display tree of what is left to do.

    A node reached twice is marked shared and not expanded again, which is what
    makes the diamonds (one package two others both need) legible rather than
    duplicated into a wall.
    """
    seen: set[str] = set()

    def state_of(name: str) -> str:
        if name in failed:
            return "fail"
        if name in running:
            return "run"
        if name in completed:
            return "done"
        return "wait"

    def visit(name: str, depth: int) -> TreeNode:
        node = graph.nodes.get(name)
        state = state_of(name)
        already = name in seen
        seen.add(name)

        deps = sorted(node.deps) if node else []
        pending = [d for d in deps if d not in completed and d not in failed]

        note = ""
        elapsed = ""
        known = node.metadata_known if node else False
        if already:
            note = "shared"
        elif not known:
            # deps are unknown, not satisfied: "ready" would be a lie
            note = "metadata missing"
        elif state == "run":
            live = states.get(name)
            note = live.phase if live and live.phase else "building"
            elapsed = live.clock if live else ""
        elif state == "fail":
            note = "failed"
        elif state == "wait":
            blocked_by = sorted(d for d in deps if d in failed)
            if blocked_by:
                note = f"blocked by {', '.join(blocked_by[:2])}"
            elif pending:
                note = f"waiting on {len(pending)} dep{'s' if len(pending) > 1 else ''}"
            else:
                note = "ready"

        children: list[TreeNode] = []
        if not already and state != "done" and depth < 6:
            children = [visit(d, depth + 1) for d in deps if d in graph.nodes]
        return TreeNode(
            name=name,
            version=node.version if node else "",
            state=state,
            note=note,
            elapsed=elapsed,
            shared=already,
            children=children,
        )

    return [visit(root, 0) for root in graph.roots]


def _tree_lines(
    screen: Screen,
    nodes: list[TreeNode],
    cols: Columns,
    bars: list[bool] | None = None,
    root: bool = True,
) -> None:
    g = screen.glyphs
    theme = screen.theme
    for index, node in enumerate(nodes):
        last = index == len(nodes) - 1
        row = screen.row()
        for more in bars or []:
            row.span((g.pipe + "  ") if more else "   ", theme.rule)
        if not root:
            row.span((g.last if last else g.branch) + " ", theme.rule)

        row.span(getattr(g, STATE_GLYPH[node.state]), getattr(theme, STATE_ROLE[node.state]))
        row.span("  ")
        style = {"done": theme.ok, "run": theme.accent, "wait": theme.muted, "fail": theme.err}[
            node.state
        ]
        name_limit = max(8, cols.ver - row.at - 2)
        row.span(truncate(node.name, name_limit), style)
        if node.version and not cols.narrow:
            row.to(cols.ver)
            row.span(truncate(node.version, max(4, cols.note - cols.ver - 2)), theme.ver)

        tail = f"{g.shared} shared" if node.shared else node.note
        if tail and not cols.narrow:
            row.to(cols.note)
            reserve = len(node.elapsed) + 2 if node.elapsed else 0
            row.span(truncate(tail, max(4, cols.right - row.at - reserve)), theme.muted)
        if node.elapsed:
            row.right(node.elapsed, theme.muted)
        screen.finish(row)

        if node.children:
            child_bars = list(bars or []) + ([not last] if not root else [])
            _tree_lines(screen, node.children, cols, child_bars, root=False)


def _feed_lines(screen: Screen, feed: list[FeedEntry], cols: Columns) -> None:
    """Completed packages. The newest is appended at the bottom of the feed."""
    theme, g = screen.theme, screen.glyphs
    for entry in feed:
        row = screen.row(indent=cols.feed_indent)
        row.span(
            getattr(g, STATE_GLYPH.get(entry.state, "done")),
            getattr(theme, STATE_ROLE.get(entry.state, "ok")),
        )
        row.span("  ")
        style = theme.err if entry.state == "fail" else (theme.text or None)
        row.span(truncate(entry.name, max(8, cols.feed_ver - row.at - 2)), style)
        if entry.version and not cols.narrow:
            row.to(cols.feed_ver)
            row.span(entry.version, theme.ver)
        tail = f"{g.shared} shared" if entry.shared else entry.note
        if tail and not cols.narrow:
            row.to(cols.feed_note)
            reserve = len(entry.clock) + 2 if entry.elapsed else 0
            row.span(truncate(tail, max(4, cols.right - row.at - reserve)), theme.muted)
        if entry.elapsed:
            row.right(entry.clock, theme.muted)
        screen.finish(row)


def _footer(
    screen: Screen,
    totals: Totals,
    *,
    done: int,
    running: int,
    failed: int,
    waiting: int,
    cols: Columns,
) -> None:
    theme, g = screen.theme, screen.glyphs
    screen.blank()
    screen.rule()
    screen.blank()

    first = cols.indent
    second = cols.indent + int((cols.width - cols.indent) * 0.30)
    third = cols.indent + int((cols.width - cols.indent) * 0.60)

    def row(a, b, c):
        line = screen.row()
        line.span(a[0], a[1])
        line.to(second)
        line.span(b[0], b[1])
        if c[0]:
            line.to(third)
            line.span(c[0], c[1])
        screen.finish(line)

    del first
    row(("BUILDS", theme.accent), ("DOWNLOADS", theme.accent), ("TIME", theme.accent))
    dl = f"↓ {human_bytes(totals.download_bytes)}" if totals.download_bytes else "idle"
    row(
        (f"{g.run} {running} running", theme.accent),
        (dl, theme.text or None),
        (f"{format_duration(totals.elapsed)} elapsed" if totals.elapsed else "", theme.muted),
    )
    rate = f"{human_bytes(int(totals.download_rate))}/s" if totals.download_rate else "—"
    remaining = (
        f"{human_bytes(totals.download_remaining)} left" if totals.download_remaining else "—"
    )
    eta = f"~{format_duration(totals.eta)} left" if totals.eta else ""
    row((f"{g.done} {done} done", theme.ok), (rate, theme.muted), (eta, theme.muted))
    row(
        (
            f"{g.fail} {failed} failed" if failed else f"{g.wait} 0 failed",
            theme.err if failed else theme.muted,
        ),
        (remaining, theme.muted),
        ("", None),
    )
    row(
        (f"{g.wait} {waiting} waiting", theme.muted),
        (f"Σ {totals.total} packages", theme.text or None),
        ("", None),
    )


def build(
    *,
    graph: Graph,
    theme: Theme,
    glyphs: Glyphs,
    width: int = 100,
    feed: list[FeedEntry] | None = None,
    states: list[BuildState] | None = None,
    completed: set[str] | None = None,
    running: set[str] | None = None,
    failed: set[str] | None = None,
    totals: Totals | None = None,
    parallelism: str = "",
    dashboard: bool = True,
    into: Screen | None = None,
) -> list[Text]:
    """Render the dashboard, or the feed alone when the dashboard is toggled off."""
    feed = list(feed or [])
    states = list(states or [])
    completed = set(completed or ())
    failed = set(failed or ())
    running = set(running or ()) | {s.package for s in states}
    totals = totals or Totals(total=len(graph) if graph else len(feed))

    screen = into or Screen(theme=theme, glyphs=glyphs, columns=Columns.for_width(width))
    cols = screen.columns

    done = sum(1 for e in feed if e.state != "fail")
    feed_failed = sum(1 for e in feed if e.state == "fail")
    waiting = max(0, totals.total - done - feed_failed - len(running))

    if dashboard:
        screen.header(f"arch linux · {parallelism}" if parallelism else "arch linux")

    screen.section(
        "Done" if dashboard else "Completed",
        f"{done} of {totals.total}" if totals.total else f"{done}",
    )

    if not feed:
        screen.add(
            screen.row(indent=cols.feed_indent).span("nothing finished yet", theme.muted).done()
        )

    _feed_lines(screen, feed, cols)

    if not dashboard:
        return screen.render()

    live = build_tree(
        graph,
        completed=completed,
        running=running,
        failed=failed,
        states={s.package: s for s in states},
    )
    screen.section(
        "Building",
        f"{len(running)} running · {waiting} waiting"
        + (f" · {len(failed)} failed" if failed else ""),
    )
    if live:
        _tree_lines(screen, live, cols)
    else:
        screen.add(screen.row().span("no packages left to build", theme.muted).done())

    _unorderable(screen, graph, cols, running=running, completed=completed)

    _footer(
        screen,
        totals,
        done=done,
        running=len(running),
        failed=len(failed),
        waiting=waiting,
        cols=cols,
    )
    screen.hint("", "[v] hide dashboard  [s] skip  [l] log  [q] quit")
    return screen.render()


def _unorderable(
    screen: Screen,
    graph: Graph,
    cols: Columns,
    *,
    running: set[str] | None = None,
    completed: set[str] | None = None,
) -> None:
    """Report anything the build order does not cover.

    An order that silently omits packages is worse than no order: the user would
    watch a build finish and still be missing updates. Missing metadata and
    dependency cycles need completely different fixes, so they are listed
    separately rather than collapsed into one vague warning.

    Anything already started or finished is filtered out: this describes what is
    left to do, and a package cannot be both in flight and waiting on metadata.
    """
    settled = set(running or ()) | set(completed or ())
    unknown = [n for n in (getattr(graph, "unknown", ()) or ()) if n not in settled]
    blocked = [n for n in (getattr(graph, "blocked_by_unknown", ()) or ()) if n not in settled]
    cycles = list(getattr(graph, "cycles", ()) or ())
    if not (unknown or blocked or cycles):
        return

    theme, g = screen.theme, screen.glyphs
    meta = []
    if unknown:
        meta.append(f"{len(unknown)} with no metadata")
    if blocked:
        meta.append(f"{len(blocked)} held behind them")
    if cycles:
        meta.append(f"{len(cycles)} dependency cycle(s)")
    screen.section("Cannot be ordered", " · ".join(meta))

    for name in unknown[:6]:
        row = screen.row()
        row.span(g.warn, theme.warn)
        row.span("  ")
        row.span(truncate(name, max(8, cols.ver - row.at - 2)), theme.text or None)
        if not cols.narrow:
            row.to(cols.note)
            row.span(truncate("dependencies unknown", cols.right - row.at), theme.muted)
        screen.finish(row)
    if len(unknown) > 6:
        screen.add(screen.row().span(f"+ {len(unknown) - 6} more", theme.muted).done())

    for name in blocked[:4]:
        screen.add(
            screen.row()
            .span(f"{g.wait}  ", theme.muted)
            .span(truncate(name, max(8, cols.right - 34)), theme.muted)
            .right("waiting on missing metadata", theme.muted)
            .done()
        )

    for cycle in cycles[:2]:
        screen.add(
            screen.row()
            .span(f"{g.fail}  ", theme.err)
            .span(" → ".join(cycle[:5]), theme.err)
            .done()
        )
        screen.add(
            screen.row(indent=cols.indent + 3)
            .span("circular dependency — unbuildable as declared", theme.muted)
            .done()
        )

    if unknown:
        screen.add(
            screen.row()
            .span("fetch the missing PKGBUILDs before building this set", theme.muted)
            .done()
        )