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