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