status: Use 'define-immutable-record-type' and its functional setters.
[jackhill/guix/guix.git] / guix / status.scm
1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2017, 2018, 2019 Ludovic Courtès <ludo@gnu.org>
3 ;;; Copyright © 2018, 2019 Ricardo Wurmus <rekado@elephly.net>
4 ;;;
5 ;;; This file is part of GNU Guix.
6 ;;;
7 ;;; GNU Guix is free software; you can redistribute it and/or modify it
8 ;;; under the terms of the GNU General Public License as published by
9 ;;; the Free Software Foundation; either version 3 of the License, or (at
10 ;;; your option) any later version.
11 ;;;
12 ;;; GNU Guix is distributed in the hope that it will be useful, but
13 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ;;; GNU General Public License for more details.
16 ;;;
17 ;;; You should have received a copy of the GNU General Public License
18 ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
19
20 (define-module (guix status)
21 #:use-module (guix records)
22 #:use-module (guix i18n)
23 #:use-module ((guix ui) #:select (colorize-string))
24 #:use-module (guix progress)
25 #:autoload (guix build syscalls) (terminal-columns)
26 #:use-module ((guix build download)
27 #:select (nar-uri-abbreviation))
28 #:use-module (guix store)
29 #:use-module (guix derivations)
30 #:use-module (guix memoization)
31 #:use-module (srfi srfi-1)
32 #:use-module (srfi srfi-9)
33 #:use-module (srfi srfi-9 gnu)
34 #:use-module (srfi srfi-19)
35 #:use-module (srfi srfi-26)
36 #:use-module (ice-9 regex)
37 #:use-module (ice-9 match)
38 #:use-module (ice-9 format)
39 #:use-module (ice-9 binary-ports)
40 #:autoload (ice-9 rdelim) (read-string)
41 #:use-module (rnrs bytevectors)
42 #:use-module ((system foreign)
43 #:select (bytevector->pointer pointer->bytevector))
44 #:export (build-event-output-port
45 compute-status
46
47 build-status
48 build-status?
49 build-status-building
50 build-status-downloading
51 build-status-builds-completed
52 build-status-downloads-completed
53
54 build?
55 build
56 build-derivation
57 build-system
58
59 download?
60 download
61 download-item
62 download-uri
63 download-size
64 download-start
65 download-end
66 download-transferred
67
68 build-status-updater
69 print-build-event
70 print-build-event/quiet
71 print-build-status
72
73 with-status-report
74 with-status-verbosity))
75
76 ;;; Commentary:
77 ;;;
78 ;;; This module provides facilities to track the status of ongoing builds and
79 ;;; downloads in a given session, as well as tools to report about the current
80 ;;; status to user interfaces. It does so by analyzing the output of
81 ;;; 'current-build-output-port'. The build status is maintained in a
82 ;;; <build-status> record.
83 ;;;
84 ;;; Code:
85
86 \f
87 ;;;
88 ;;; Build status tracking.
89 ;;;
90
91 ;; Builds and substitutions performed by the daemon.
92 (define-record-type* <build-status> build-status make-build-status
93 build-status?
94 (building build-status-building ;list of <build>
95 (default '()))
96 (downloading build-status-downloading ;list of <download>
97 (default '()))
98 (builds-completed build-status-builds-completed ;list of <build>
99 (default '()))
100 (downloads-completed build-status-downloads-completed ;list of <download>
101 (default '())))
102
103 ;; On-going or completed build.
104 (define-immutable-record-type <build>
105 (%build derivation id system log-file completion)
106 build?
107 (derivation build-derivation) ;string (.drv file name)
108 (id build-id) ;#f | integer
109 (system build-system) ;string
110 (log-file build-log-file) ;#f | string
111 (completion build-completion ;#f | integer (percentage)
112 set-build-completion))
113
114 (define* (build derivation system #:key id log-file completion)
115 "Return a new build."
116 (%build derivation id system log-file completion))
117
118 ;; On-going or completed downloads. Downloads can be stem from substitutes
119 ;; and from "builtin:download" fixed-output derivations.
120 (define-record-type <download>
121 (%download item uri size start end transferred)
122 download?
123 (item download-item) ;store item
124 (uri download-uri) ;string | #f
125 (size download-size) ;integer | #f
126 (start download-start) ;<time>
127 (end download-end) ;#f | <time>
128 (transferred download-transferred)) ;integer
129
130 (define* (download item uri
131 #:key size
132 (start (current-time time-monotonic)) end
133 (transferred 0))
134 "Return a new download."
135 (%download item uri size start end transferred))
136
137 (define (matching-build drv)
138 "Return a predicate that matches builds of DRV."
139 (lambda (build)
140 (string=? drv (build-derivation build))))
141
142 (define (matching-download item)
143 "Return a predicate that matches downloads of ITEM."
144 (lambda (download)
145 (string=? item (download-item download))))
146
147 (define %percentage-line-rx
148 ;; Things like CMake write lines like "[ 10%] gcc -c …". This regexp
149 ;; matches them.
150 (make-regexp "^[[:space:]]*\\[ *([0-9]+)%\\]"))
151
152 (define %fraction-line-rx
153 ;; The 'compiled-modules' derivations and Ninja produce reports like
154 ;; "[ 1/32]" at the beginning of each line, while GHC prints "[ 6 of 45]".
155 ;; This regexp matches these.
156 (make-regexp "^[[:space:]]*\\[ *([0-9]+) *(/|of) *([0-9]+)\\]"))
157
158 (define (update-build status id line)
159 "Update STATUS based on LINE, a build output line for ID that might contain
160 a completion indication."
161 (define (find-build)
162 (find (lambda (build)
163 (and (build-id build)
164 (= (build-id build) id)))
165 (build-status-building status)))
166
167 (define (update %)
168 (let ((build (find-build)))
169 (build-status
170 (inherit status)
171 (building (cons (set-build-completion build %)
172 (delq build (build-status-building status)))))))
173
174 (cond ((string-any #\nul line)
175 ;; Don't try to match a regexp here.
176 status)
177 ((regexp-exec %percentage-line-rx line)
178 =>
179 (lambda (match)
180 (let ((% (string->number (match:substring match 1))))
181 (update %))))
182 ((regexp-exec %fraction-line-rx line)
183 =>
184 (lambda (match)
185 (let ((done (string->number (match:substring match 1)))
186 (total (string->number (match:substring match 3))))
187 (update (* 100. (/ done total))))))
188 (else
189 status)))
190
191 (define* (compute-status event status
192 #:key
193 (current-time current-time)
194 (derivation-path->output-path
195 derivation-path->output-path))
196 "Given EVENT, a tuple like (build-started \"/gnu/store/...-foo.drv\" ...),
197 compute a new status based on STATUS."
198 (match event
199 (('build-started drv "-" system log-file . rest)
200 (let ((build (build drv system
201 #:id (match rest
202 ((pid . _) (string->number pid))
203 (_ #f))
204 #:log-file (if (string-null? log-file)
205 #f
206 log-file))))
207 (build-status
208 (inherit status)
209 (building (cons build (build-status-building status))))))
210 (((or 'build-succeeded 'build-failed) drv _ ...)
211 (let ((build (find (matching-build drv)
212 (build-status-building status))))
213 ;; If BUILD is #f, this may be because DRV corresponds to a
214 ;; fixed-output derivation that is listed as a download.
215 (if build
216 (build-status
217 (inherit status)
218 (building (delq build (build-status-building status)))
219 (builds-completed
220 (cons build (build-status-builds-completed status))))
221 status)))
222
223 ;; Note: Ignore 'substituter-started' and 'substituter-succeeded' because
224 ;; they're not as informative as 'download-started' and
225 ;; 'download-succeeded'.
226
227 (('download-started item uri (= string->number size))
228 ;; This is presumably a fixed-output derivation so move it from
229 ;; 'building' to 'downloading'. XXX: This doesn't work in 'check' mode
230 ;; because ITEM is different from DRV's output.
231 (build-status
232 (inherit status)
233 (building (remove (lambda (build)
234 (let ((drv (build-derivation build)))
235 (equal? (false-if-exception
236 (derivation-path->output-path drv))
237 item)))
238 (build-status-building status)))
239 (downloading (cons (download item uri #:size size
240 #:start (current-time time-monotonic))
241 (build-status-downloading status)))))
242 (('download-succeeded item uri (= string->number size))
243 (let ((current (find (matching-download item)
244 (build-status-downloading status))))
245 (build-status
246 (inherit status)
247 (downloading (delq current (build-status-downloading status)))
248 (downloads-completed
249 (cons (download item uri
250 #:size size
251 #:start (download-start current)
252 #:transferred size
253 #:end (current-time time-monotonic))
254 (build-status-downloads-completed status))))))
255 (('substituter-succeeded item _ ...)
256 (match (find (matching-download item)
257 (build-status-downloading status))
258 (#f
259 ;; Presumably we already got a 'download-succeeded' event for ITEM,
260 ;; everything is fine.
261 status)
262 (current
263 ;; Maybe the build process didn't emit a 'download-succeeded' event
264 ;; for ITEM, so remove CURRENT from the queue now.
265 (build-status
266 (inherit status)
267 (downloading (delq current (build-status-downloading status)))
268 (downloads-completed
269 (cons (download item (download-uri current)
270 #:size (download-size current)
271 #:start (download-start current)
272 #:transferred (download-size current)
273 #:end (current-time time-monotonic))
274 (build-status-downloads-completed status)))))))
275 (('download-progress item uri
276 (= string->number size)
277 (= string->number transferred))
278 (let ((downloads (remove (matching-download item)
279 (build-status-downloading status)))
280 (current (find (matching-download item)
281 (build-status-downloading status))))
282 (build-status
283 (inherit status)
284 (downloading (cons (download item uri
285 #:size size
286 #:start
287 (or (and current
288 (download-start current))
289 (current-time time-monotonic))
290 #:transferred transferred)
291 downloads)))))
292 (('build-log (? integer? pid) line)
293 (update-build status pid line))
294 (_
295 status)))
296
297 (define (simultaneous-jobs status)
298 "Return the number of on-going builds and downloads for STATUS."
299 (+ (length (build-status-building status))
300 (length (build-status-downloading status))))
301
302 \f
303 ;;;
304 ;;; Rendering.
305 ;;;
306
307 (define (extended-build-trace-supported?)
308 "Return true if the currently used store is known to support \"extended
309 build traces\" such as \"@ download-progress\" traces."
310 ;; Support for extended build traces was added in protocol version #x162.
311 (and (current-store-protocol-version)
312 (>= (current-store-protocol-version) #x162)))
313
314 (define (multiplexed-output-supported?)
315 "Return true if the daemon supports \"multiplexed output\"--i.e., \"@
316 build-log\" traces."
317 (and (current-store-protocol-version)
318 (>= (current-store-protocol-version) #x163)))
319
320 (define isatty?*
321 (mlambdaq (port)
322 (isatty? port)))
323
324 (define spin!
325 (let ((steps (circular-list "\\" "|" "/" "-")))
326 (lambda (port)
327 "Display a spinner on PORT."
328 (when (isatty?* port)
329 (match steps
330 ((first . rest)
331 (set! steps rest)
332 (display "\r\x1b[K" port)
333 (display first port)
334 (force-output port)))))))
335
336 (define (color-output? port)
337 "Return true if we should write colored output to PORT."
338 (and (not (getenv "INSIDE_EMACS"))
339 (not (getenv "NO_COLOR"))
340 (isatty?* port)))
341
342 (define-syntax color-rules
343 (syntax-rules ()
344 "Return a procedure that colorizes the string it is passed according to
345 the given rules. Each rule has the form:
346
347 (REGEXP COLOR1 COLOR2 ...)
348
349 where COLOR1 specifies how to colorize the first submatch of REGEXP, and so
350 on."
351 ((_ (regexp colors ...) rest ...)
352 (let ((next (color-rules rest ...))
353 (rx (make-regexp regexp)))
354 (lambda (str)
355 (if (string-index str #\nul)
356 str
357 (match (regexp-exec rx str)
358 (#f (next str))
359 (m (let loop ((n 1)
360 (c '(colors ...))
361 (result '()))
362 (match c
363 (()
364 (string-concatenate-reverse result))
365 ((first . tail)
366 (loop (+ n 1) tail
367 (cons (colorize-string (match:substring m n)
368 first)
369 result)))))))))))
370 ((_)
371 (lambda (str)
372 str))))
373
374 (define colorize-log-line
375 ;; Take a string and return a possibly colorized string according to the
376 ;; rules below.
377 (color-rules
378 ("^(phase)(.*)(succeeded after)(.*)(seconds)(.*)"
379 GREEN BOLD GREEN RESET GREEN BLUE)
380 ("^(phase)(.*)(failed after)(.*)(seconds)(.*)"
381 RED BLUE RED BLUE RED BLUE)
382 ("^(.*)(error|fail|failed|\\<FAIL|FAILED)([[:blank:]]*)(:)(.*)"
383 RESET RED BOLD BOLD BOLD)
384 ("^(.*)(warning)([[:blank:]]*)(:)(.*)"
385 RESET MAGENTA BOLD BOLD BOLD)))
386
387 (define (hook-message hook-type)
388 "Return a human-readable string for the profile hook type HOOK-TYPE."
389 (match hook-type
390 ('info-dir
391 (G_ "building directory of Info manuals..."))
392 ('ghc-package-cache
393 (G_ "building GHC package cache..."))
394 ('ca-certificate-bundle
395 (G_ "building CA certificate bundle..."))
396 ('glib-schemas
397 (G_ "generating GLib schema cache..."))
398 ('gtk-icon-themes
399 (G_ "creating GTK+ icon theme cache..."))
400 ('gtk-im-modules
401 (G_ "building cache files for GTK+ input methods..."))
402 ('xdg-desktop-database
403 (G_ "building XDG desktop file cache..."))
404 ('xdg-mime-database
405 (G_ "building XDG MIME database..."))
406 ('fonts-dir
407 (G_ "building fonts directory..."))
408 ('texlive-configuration
409 (G_ "building TeX Live configuration..."))
410 ('manual-database
411 (G_ "building database for manual pages..."))
412 ('package-cache ;package cache generated by 'guix pull'
413 (G_ "building package cache..."))
414 (_ #f)))
415
416 (define* (print-build-event event old-status status
417 #:optional (port (current-error-port))
418 #:key
419 (colorize? (color-output? port))
420 (print-log? #t))
421 "Print information about EVENT and STATUS to PORT. When COLORIZE? is true,
422 produce colorful output. When PRINT-LOG? is true, display the build log in
423 addition to build events."
424 (define info
425 (if colorize?
426 (cut colorize-string <> 'BOLD)
427 identity))
428
429 (define success
430 (if colorize?
431 (cut colorize-string <> 'GREEN 'BOLD)
432 identity))
433
434 (define failure
435 (if colorize?
436 (cut colorize-string <> 'RED 'BOLD)
437 identity))
438
439 (define (report-build-progress %)
440 (let ((% (min (max % 0) 100))) ;sanitize
441 (erase-current-line port)
442 (format port "~3d% " (inexact->exact (round %)))
443 (display (progress-bar % (- (current-terminal-columns) 5))
444 port)
445 (force-output port)))
446
447 (define print-log-line
448 (if print-log?
449 (if colorize?
450 (lambda (id line)
451 (display (colorize-log-line line) port))
452 (lambda (id line)
453 (display line port)))
454 (lambda (id line)
455 (match (build-status-building status)
456 ((build) ;single job
457 (match (build-completion build)
458 ((? number? %) (report-build-progress %))
459 (_ (spin! port))))
460 (_
461 (spin! port))))))
462
463 (define erase-current-line*
464 (if (isatty?* port)
465 (lambda (port)
466 (erase-current-line port)
467 (force-output port))
468 (const #t)))
469
470 (unless print-log?
471 (erase-current-line* port)) ;clear the spinner or progress bar
472 (match event
473 (('build-started drv . _)
474 (let ((properties (derivation-properties
475 (read-derivation-from-file drv))))
476 (match (assq-ref properties 'type)
477 ('graft
478 (let ((count (match (assq-ref properties 'graft)
479 (#f 0)
480 (lst (or (assq-ref lst 'count) 0)))))
481 (format port (info (N_ "applying ~a graft for ~a..."
482 "applying ~a grafts for ~a..."
483 count))
484 count drv)))
485 ('profile-hook
486 (let ((hook-type (assq-ref properties 'hook)))
487 (or (and=> (hook-message hook-type)
488 (lambda (msg)
489 (format port (info msg))))
490 (format port (info (G_ "running profile hook of type '~a'..."))
491 hook-type))))
492 (_
493 (format port (info (G_ "building ~a...")) drv))))
494 (newline port))
495 (('build-succeeded drv . _)
496 (when (or print-log? (not (extended-build-trace-supported?)))
497 (format port (success (G_ "successfully built ~a")) drv)
498 (newline port))
499 (match (build-status-building status)
500 (() #t)
501 (ongoing ;when max-jobs > 1
502 (format port
503 (N_ "The following build is still in progress:~%~{ ~a~%~}~%"
504 "The following builds are still in progress:~%~{ ~a~%~}~%"
505 (length ongoing))
506 (map build-derivation ongoing)))))
507 (('build-failed drv . _)
508 (format port (failure (G_ "build of ~a failed")) drv)
509 (newline port)
510 (match (derivation-log-file drv)
511 (#f
512 (format port (failure (G_ "Could not find build log for '~a'."))
513 drv))
514 (log
515 (format port (info (G_ "View build log at '~a'.")) log)))
516 (newline port))
517 (('substituter-started item _ ...)
518 (when (or print-log? (not (extended-build-trace-supported?)))
519 (format port (info (G_ "substituting ~a...")) item)
520 (newline port)))
521 (('download-started item uri _ ...)
522 (format port (info (G_ "downloading from ~a...")) uri)
523 (newline port))
524 (('download-progress item uri
525 (= string->number size)
526 (= string->number transferred))
527 ;; Print a progress bar, but only if there's only one on-going
528 ;; job--otherwise the output would be intermingled.
529 (when (= 1 (simultaneous-jobs status))
530 (match (find (matching-download item)
531 (build-status-downloading status))
532 (#f #f) ;shouldn't happen!
533 (download
534 ;; XXX: It would be nice to memoize the abbreviation.
535 (let ((uri (if (string-contains uri "/nar/")
536 (nar-uri-abbreviation uri)
537 (basename uri))))
538 (display-download-progress uri size
539 #:start-time
540 (download-start download)
541 #:transferred transferred))))))
542 (('substituter-succeeded item _ ...)
543 ;; If there are no jobs running, we already reported download completion
544 ;; so there's nothing left to do.
545 (unless (and (zero? (simultaneous-jobs status))
546 (extended-build-trace-supported?))
547 (format port (success (G_ "substitution of ~a complete")) item)
548 (newline port)))
549 (('substituter-failed item _ ...)
550 (format port (failure (G_ "substitution of ~a failed")) item)
551 (newline port))
552 (('hash-mismatch item algo expected actual _ ...)
553 ;; TRANSLATORS: The final string looks like "sha256 hash mismatch for
554 ;; /gnu/store/…-sth:", where "sha256" is the hash algorithm.
555 (format port (failure (G_ "~a hash mismatch for ~a:")) algo item)
556 (newline port)
557 (format port (info (G_ "\
558 expected hash: ~a
559 actual hash: ~a~%"))
560 expected actual))
561 (('build-remote drv host _ ...)
562 (format port (info (G_ "offloading build of ~a to '~a'")) drv host)
563 (newline port))
564 (('build-log pid line)
565 (if (multiplexed-output-supported?)
566 (if (not pid)
567 (begin
568 ;; LINE comes from the daemon, not from builders. Let it
569 ;; through.
570 (display line port)
571 (force-output port))
572 (print-log-line pid line))
573 (cond ((string-prefix? "substitute: " line)
574 ;; The daemon prefixes early messages coming with 'guix
575 ;; substitute' with "substitute:". These are useful ("updating
576 ;; substitutes from URL"), so let them through.
577 (display line port)
578 (force-output port))
579 ((string-prefix? "waiting for locks" line)
580 ;; This is when a derivation is already being built and we're just
581 ;; waiting for the build to complete.
582 (display (info (string-trim-right line)) port)
583 (newline))
584 (else
585 (print-log-line pid line)))))
586 (_
587 event)))
588
589 (define* (print-build-event/quiet event old-status status
590 #:optional
591 (port (current-error-port))
592 #:key
593 (colorize? (color-output? port)))
594 (print-build-event event old-status status port
595 #:colorize? colorize?
596 #:print-log? #f))
597
598 (define* (build-status-updater #:optional (on-change (const #t)))
599 "Return a procedure that can be passed to 'build-event-output-port'. That
600 procedure computes the new build status upon each event and calls ON-CHANGE:
601
602 (ON-CHANGE event status new-status)
603
604 ON-CHANGE can display the build status, build events, etc."
605 (lambda (event status)
606 (let ((new (compute-status event status)))
607 (on-change event status new)
608 new)))
609
610 \f
611 ;;;
612 ;;; Build port.
613 ;;;
614
615 (define (maybe-utf8->string bv)
616 "Attempt to decode BV as UTF-8 string and return it. Gracefully handle the
617 case where BV does not contain only valid UTF-8."
618 (catch 'decoding-error
619 (lambda ()
620 (utf8->string bv))
621 (lambda _
622 ;; This is the sledgehammer but it's the only safe way we have to
623 ;; properly handle this. It's expensive but it's rarely needed.
624 (let ((port (open-bytevector-input-port bv)))
625 (set-port-encoding! port "UTF-8")
626 (set-port-conversion-strategy! port 'substitute)
627 (let ((str (read-string port)))
628 (close-port port)
629 str)))))
630
631 (define (bytevector-index bv number offset count)
632 "Search for NUMBER in BV starting from OFFSET and reading up to COUNT bytes;
633 return the offset where NUMBER first occurs or #f if it could not be found."
634 (let loop ((offset offset)
635 (count count))
636 (cond ((zero? count) #f)
637 ((= (bytevector-u8-ref bv offset) number) offset)
638 (else (loop (+ 1 offset) (- count 1))))))
639
640 (define (split-lines str)
641 "Split STR into lines in a way that preserves newline characters."
642 (let loop ((str str)
643 (result '()))
644 (if (string-null? str)
645 (reverse result)
646 (match (string-index str #\newline)
647 (#f
648 (loop "" (cons str result)))
649 (index
650 (loop (string-drop str (+ index 1))
651 (cons (string-take str (+ index 1)) result)))))))
652
653 (define* (build-event-output-port proc #:optional (seed (build-status)))
654 "Return an output port for use as 'current-build-output-port' that calls
655 PROC with its current state value, initialized with SEED, on every build
656 event. Build events passed to PROC are tuples corresponding to the \"build
657 traces\" produced by the daemon:
658
659 (build-started \"/gnu/store/...-foo.drv\" ...)
660 (substituter-started \"/gnu/store/...-foo\" ...)
661
662 and so on.
663
664 The second return value is a thunk to retrieve the current state."
665 (define %fragments
666 ;; Line fragments received so far.
667 '())
668
669 (define %state
670 ;; Current state for PROC.
671 seed)
672
673 ;; When true, this represents the current state while reading a
674 ;; "@ build-log" trace: the current builder PID, the previously-read
675 ;; bytevectors, and the number of bytes that remain to be read.
676 (define %build-output-pid #f)
677 (define %build-output '())
678 (define %build-output-left #f)
679
680 (define (process-line line)
681 (cond ((string-prefix? "@ " line)
682 ;; Note: Drop the trailing \n, and use 'string-split' to preserve
683 ;; spaces (the log file part of 'build-started' events can be the
684 ;; empty string.)
685 (match (string-split (string-drop (string-drop-right line 1) 2)
686 #\space)
687 (("build-log" (= string->number pid) (= string->number len))
688 (set! %build-output-pid pid)
689 (set! %build-output '())
690 (set! %build-output-left len))
691 (((= string->symbol event-name) args ...)
692 (set! %state
693 (proc (cons event-name args)
694 %state)))))
695 (else
696 (set! %state (proc (list 'build-log #f line)
697 %state)))))
698
699 (define (process-build-output pid output)
700 ;; Transform OUTPUT in 'build-log' events or download events as generated
701 ;; by extended build traces.
702 (define (line->event line)
703 (match (and (string-prefix? "@ " line)
704 (string-tokenize (string-drop line 2)))
705 ((type . args)
706 (if (or (string-prefix? "download-" type)
707 (string=? "build-remote" type))
708 (cons (string->symbol type) args)
709 `(build-log ,pid ,line)))
710 (_
711 `(build-log ,pid ,line))))
712
713 (let* ((lines (split-lines output))
714 (events (map line->event lines)))
715 (set! %state (fold proc %state events))))
716
717 (define (bytevector-range bv offset count)
718 (let ((ptr (bytevector->pointer bv offset)))
719 (pointer->bytevector ptr count)))
720
721 (define (write! bv offset count)
722 (if %build-output-pid
723 (let ((keep (min count %build-output-left)))
724 (set! %build-output
725 (let ((bv* (make-bytevector keep)))
726 (bytevector-copy! bv offset bv* 0 keep)
727 (cons bv* %build-output)))
728 (set! %build-output-left
729 (- %build-output-left keep))
730
731 (when (zero? %build-output-left)
732 (process-build-output %build-output-pid
733 (string-concatenate-reverse
734 (map maybe-utf8->string %build-output))) ;XXX
735 (set! %build-output '())
736 (set! %build-output-pid #f))
737 keep)
738 (match (bytevector-index bv (char->integer #\newline)
739 offset count)
740 ((? integer? cr)
741 (let* ((tail (maybe-utf8->string
742 (bytevector-range bv offset (- cr -1 offset))))
743 (line (string-concatenate-reverse
744 (cons tail %fragments))))
745 (process-line line)
746 (set! %fragments '())
747 (- cr -1 offset)))
748 (#f
749 (unless (zero? count)
750 (let ((str (maybe-utf8->string
751 (bytevector-range bv offset count))))
752 (set! %fragments (cons str %fragments))))
753 count))))
754
755 (define port
756 (make-custom-binary-output-port "filtering-input-port"
757 write!
758 #f #f
759 #f))
760
761 ;; The build port actually receives Unicode strings.
762 (set-port-encoding! port "UTF-8")
763 (setvbuf port 'line)
764 (values port (lambda () %state)))
765
766 (define (call-with-status-report on-event thunk)
767 (parameterize ((current-terminal-columns (terminal-columns))
768 (current-build-output-port
769 (build-event-output-port (build-status-updater on-event))))
770 (thunk)))
771
772 (define-syntax-rule (with-status-report on-event exp ...)
773 "Set up build status reporting to the user using the ON-EVENT procedure;
774 evaluate EXP... in that context."
775 (call-with-status-report on-event (lambda () exp ...)))
776
777 (define (logger-for-level level)
778 "Return the logging procedure that corresponds to LEVEL."
779 (cond ((<= level 0) (const #t))
780 ((= level 1) print-build-event/quiet)
781 (else print-build-event)))
782
783 (define (call-with-status-verbosity level thunk)
784 (call-with-status-report (logger-for-level level) thunk))
785
786 (define-syntax-rule (with-status-verbosity level exp ...)
787 "Set up build status reporting to the user at the given LEVEL: 0 means
788 silent, 1 means quiet, 2 means verbose. Evaluate EXP... in that context."
789 (call-with-status-verbosity level (lambda () exp ...)))