aboutsummaryrefslogtreecommitdiff
path: root/guix/profiles.scm
blob: d19b49f6d2dc3059d67c445d79d872493e412a0e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2013, 2014, 2015 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2013 Nikita Karetnikov <nikita@karetnikov.org>
;;; Copyright © 2014 Alex Kost <alezost@gmail.com>
;;; Copyright © 2015 Mark H Weaver <mhw@netris.org>
;;; Copyright © 2015 Sou Bunnbu <iyzsong@gmail.com>
;;;
;;; This file is part of GNU Guix.
;;;
;;; GNU Guix is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or (at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>.

(define-module (guix profiles)
  #:use-module (guix utils)
  #:use-module (guix records)
  #:use-module (guix packages)
  #:use-module (guix derivations)
  #:use-module (guix search-paths)
  #:use-module (guix gexp)
  #:use-module (guix monads)
  #:use-module (guix store)
  #:use-module (ice-9 match)
  #:use-module (ice-9 regex)
  #:use-module (ice-9 ftw)
  #:use-module (ice-9 format)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-9)
  #:use-module (srfi srfi-11)
  #:use-module (srfi srfi-19)
  #:use-module (srfi srfi-26)
  #:use-module (srfi srfi-34)
  #:use-module (srfi srfi-35)
  #:export (&profile-error
            profile-error?
            profile-error-profile
            &profile-not-found-error
            profile-not-found-error?
            &missing-generation-error
            missing-generation-error?
            missing-generation-error-generation

            manifest make-manifest
            manifest?
            manifest-entries

            <manifest-entry>              ; FIXME: eventually make it internal
            manifest-entry
            manifest-entry?
            manifest-entry-name
            manifest-entry-version
            manifest-entry-output
            manifest-entry-item
            manifest-entry-dependencies
            manifest-entry-search-paths

            manifest-pattern
            manifest-pattern?

            manifest-remove
            manifest-add
            manifest-lookup
            manifest-installed?
            manifest-matching-entries

            manifest-transaction
            manifest-transaction?
            manifest-transaction-install
            manifest-transaction-remove
            manifest-perform-transaction
            manifest-transaction-effects

            profile-manifest
            package->manifest-entry
            packages->manifest
            %default-profile-hooks
            profile-derivation
            generation-number
            generation-numbers
            profile-generations
            relative-generation
            previous-generation-number
            generation-time
            generation-file-name))

;;; Commentary:
;;;
;;; Tools to create and manipulate profiles---i.e., the representation of a
;;; set of installed packages.
;;;
;;; Code:


;;;
;;; Condition types.
;;;

(define-condition-type &profile-error &error
  profile-error?
  (profile profile-error-profile))

(define-condition-type &profile-not-found-error &profile-error
  profile-not-found-error?)

(define-condition-type &missing-generation-error &profile-error
  missing-generation-error?
  (generation missing-generation-error-generation))


;;;
;;; Manifests.
;;;

(define-record-type <manifest>
  (manifest entries)
  manifest?
  (entries manifest-entries))                     ; list of <manifest-entry>

;; Convenient alias, to avoid name clashes.
(define make-manifest manifest)

(define-record-type* <manifest-entry> manifest-entry
  make-manifest-entry
  manifest-entry?
  (name         manifest-entry-name)              ; string
  (version      manifest-entry-version)           ; string
  (output       manifest-entry-output             ; string
                (default "out"))
  (item         manifest-entry-item)              ; package | store path
  (dependencies manifest-entry-dependencies       ; (store path | package)*
                (default '()))
  (search-paths manifest-entry-search-paths       ; search-path-specification*
                (default '())))

(define-record-type* <manifest-pattern> manifest-pattern
  make-manifest-pattern
  manifest-pattern?
  (name         manifest-pattern-name)            ; string
  (version      manifest-pattern-version          ; string | #f
                (default #f))
  (output       manifest-pattern-output           ; string | #f
                (default "out")))

(define (profile-manifest profile)
  "Return the PROFILE's manifest."
  (let ((file (string-append profile "/manifest")))
    (if (file-exists? file)
        (call-with-input-file file read-manifest)
        (manifest '()))))

(define* (package->manifest-entry package #:optional output)
  "Return a manifest entry for the OUTPUT of package PACKAGE.  When OUTPUT is
omitted or #f, use the first output of PACKAGE."
  (let ((deps (map (match-lambda
                    ((label package)
                     (gexp-input package))
                    ((label package output)
                     (gexp-input package output)))
                   (package-transitive-propagated-inputs package))))
    (manifest-entry
     (name (package-name package))
     (version (package-version package))
     (output (or output (car (package-outputs package))))
     (item package)
     (dependencies (delete-duplicates deps))
     (search-paths (package-native-search-paths package)))))

(define (packages->manifest packages)
  "Return a list of manifest entries, one for each item listed in PACKAGES.
Elements of PACKAGES can be either package objects or package/string tuples
denoting a specific output of a package."
  (manifest
   (map (match-lambda
         ((package output)
          (package->manifest-entry package output))
         (package
           (package->manifest-entry package)))
        packages)))

(define (manifest->gexp manifest)
  "Return a representation of MANIFEST as a gexp."
  (define (entry->gexp entry)
    (match entry
      (($ <manifest-entry> name version output (? string? path)
                           (deps ...) (search-paths ...))
       #~(#$name #$version #$output #$path
                 (propagated-inputs #$deps)
                 (search-paths #$(map search-path-specification->sexp
                                      search-paths))))
      (($ <manifest-entry> name version output (? package? package)
                           (deps ...) (search-paths ...))
       #~(#$name #$version #$output
                 (ungexp package (or output "out"))
                 (propagated-inputs #$deps)
                 (search-paths #$(map search-path-specification->sexp
                                      search-paths))))))

  (match manifest
    (($ <manifest> (entries ...))
     #~(manifest (version 2)
                 (packages #$(map entry->gexp entries))))))

(define (find-package name version)
  "Return a package from the distro matching NAME and possibly VERSION.  This
procedure is here for backward-compatibility and will eventually vanish."
  (define find-best-packages-by-name              ;break abstractions
    (module-ref (resolve-interface '(gnu packages))
                'find-best-packages-by-name))

   ;; Use 'find-best-packages-by-name' and not 'find-packages-by-name'; the
   ;; former traverses the module tree only once and then allows for efficient
   ;; access via a vhash.
   (match (find-best-packages-by-name name version)
     ((p _ ...) p)
     (_
      (match (find-best-packages-by-name name #f)
        ((p _ ...) p)
        (_ #f)))))

(define (sexp->manifest sexp)
  "Parse SEXP as a manifest."
  (define (infer-search-paths name version)
    ;; Infer the search path specifications for NAME-VERSION by looking up a
    ;; same-named package in the distro.  Useful for the old manifest formats
    ;; that did not store search path info.
    (let ((package (find-package name version)))
      (if package
          (package-native-search-paths package)
          '())))

  (match sexp
    (('manifest ('version 0)
                ('packages ((name version output path) ...)))
     (manifest
      (map (lambda (name version output path)
             (manifest-entry
              (name name)
              (version version)
              (output output)
              (item path)
              (search-paths (infer-search-paths name version))))
           name version output path)))

    ;; Version 1 adds a list of propagated inputs to the
    ;; name/version/output/path tuples.
    (('manifest ('version 1)
                ('packages ((name version output path deps) ...)))
     (manifest
      (map (lambda (name version output path deps)
             ;; Up to Guix 0.7 included, dependencies were listed as ("gmp"
             ;; "/gnu/store/...-gmp") for instance.  Discard the 'label' in
             ;; such lists.
             (let ((deps (match deps
                           (((labels directories) ...)
                            directories)
                           ((directories ...)
                            directories))))
               (manifest-entry
                 (name name)
                 (version version)
                 (output output)
                 (item path)
                 (dependencies deps)
                 (search-paths (infer-search-paths name version)))))
           name version output path deps)))

    ;; Version 2 adds search paths and is slightly more verbose.
    (('manifest ('version 2 minor-version ...)
                ('packages ((name version output path
                                  ('propagated-inputs deps)
                                  ('search-paths search-paths)
                                  extra-stuff ...)
                            ...)))
     (manifest
      (map (lambda (name version output path deps search-paths)
             (manifest-entry
               (name name)
               (version version)
               (output output)
               (item path)
               (dependencies deps)
               (search-paths (map sexp->search-path-specification
                                  search-paths))))
           name version output path deps search-paths)))
    (_
     (raise (condition
             (&message (message "unsupported manifest format")))))))

(define (read-manifest port)
  "Return the packages listed in MANIFEST."
  (sexp->manifest (read port)))

(define (entry-predicate pattern)
  "Return a procedure that returns #t when passed a manifest entry that
matches NAME/OUTPUT/VERSION.  OUTPUT and VERSION may be #f, in which case they
are ignored."
  (match pattern
    (($ <manifest-pattern> name version output)
     (match-lambda
      (($ <manifest-entry> entry-name entry-version entry-output)
       (and (string=? entry-name name)
            (or (not entry-output) (not output)
                (string=? entry-output output))
            (or (not version)
                (string=? entry-version version))))))))

(define (manifest-remove manifest patterns)
  "Remove entries for each of PATTERNS from MANIFEST.  Each item in PATTERNS
must be a manifest-pattern."
  (define (remove-entry pattern lst)
    (remove (entry-predicate pattern) lst))

  (make-manifest (fold remove-entry
                       (manifest-entries manifest)
                       patterns)))

(define (manifest-add manifest entries)
  "Add a list of manifest ENTRIES to MANIFEST and return new manifest.
Remove MANIFEST entries that have the same name and output as ENTRIES."
  (define (same-entry? entry name output)
    (match entry
      (($ <manifest-entry> entry-name _ entry-output _ ...)
       (and (equal? name entry-name)
            (equal? output entry-output)))))

  (make-manifest
   (append entries
           (fold (lambda (entry result)
                   (match entry
                     (($ <manifest-entry> name _ out _ ...)
                      (filter (negate (cut same-entry? <> name out))
                              result))))
                 (manifest-entries manifest)
                 entries))))

(define (manifest-lookup manifest pattern)
  "Return the first item of MANIFEST that matches PATTERN, or #f if there is
no match.."
  (find (entry-predicate pattern)
        (manifest-entries manifest)))

(define (manifest-installed? manifest pattern)
  "Return #t if MANIFEST has an entry matching PATTERN (a manifest-pattern),
#f otherwise."
  (->bool (manifest-lookup manifest pattern)))

(define (manifest-matching-entries manifest patterns)
  "Return all the entries of MANIFEST that match one of the PATTERNS."
  (define predicates
    (map entry-predicate patterns))

  (define (matches? entry)
    (any (lambda (pred)
           (pred entry))
         predicates))

  (filter matches? (manifest-entries manifest)))


;;;
;;; Manifest transactions.
;;;

(define-record-type* <manifest-transaction> manifest-transaction
  make-manifest-transaction
  manifest-transaction?
  (install manifest-transaction-install ; list of <manifest-entry>
           (default '()))
  (remove  manifest-transaction-remove  ; list of <manifest-pattern>
           (default '())))

(define (manifest-transaction-effects manifest transaction)
  "Compute the effect of applying TRANSACTION to MANIFEST.  Return 4 values:
the list of packages that would be removed, installed, upgraded, or downgraded
when applying TRANSACTION to MANIFEST.  Upgrades are represented as pairs
where the head is the entry being upgraded and the tail is the entry that will
replace it."
  (define (manifest-entry->pattern entry)
    (manifest-pattern
      (name   (manifest-entry-name entry))
      (output (manifest-entry-output entry))))

  (let loop ((input     (manifest-transaction-install transaction))
             (install   '())
             (upgrade   '())
             (downgrade '()))
    (match input
      (()
       (let ((remove (manifest-transaction-remove transaction)))
         (values (manifest-matching-entries manifest remove)
                 (reverse install) (reverse upgrade) (reverse downgrade))))
      ((entry rest ...)
       ;; Check whether installing ENTRY corresponds to the installation of a
       ;; new package or to an upgrade.

       ;; XXX: When the exact same output directory is installed, we're not
       ;; really upgrading anything.  Add a check for that case.
       (let* ((pattern  (manifest-entry->pattern entry))
              (previous (manifest-lookup manifest pattern))
              (newer?   (and previous
                             (version>=? (manifest-entry-version entry)
                                         (manifest-entry-version previous)))))
         (loop rest
               (if previous install (cons entry install))
               (if (and previous newer?)
                   (alist-cons previous entry upgrade)
                   upgrade)
               (if (and previous (not newer?))
                   (alist-cons previous entry downgrade)
                   downgrade)))))))

(define (manifest-perform-transaction manifest transaction)
  "Perform TRANSACTION on MANIFEST and return new manifest."
  (let ((install (manifest-transaction-install transaction))
        (remove  (manifest-transaction-remove transaction)))
    (manifest-add (manifest-remove manifest remove)
                  install)))


;;;
;;; Profiles.
;;;

(define (manifest-inputs manifest)
  "Return a list of <gexp-input> objects for MANIFEST."
  (append-map (match-lambda
               (($ <manifest-entry> name version output thing deps)
                ;; THING may be a package or a file name.  In the latter case,
                ;; assume it's already valid.  Ditto for DEPS.
                (cons (gexp-input thing output) deps)))
              (manifest-entries manifest)))

(define (info-dir-file manifest)
  "Return a derivation that builds the 'dir' file for all the entries of
MANIFEST."
  (define texinfo                                 ;lazy reference
    (module-ref (resolve-interface '(gnu packages texinfo)) 'texinfo))
  (define gzip                                    ;lazy reference
    (module-ref (resolve-interface '(gnu packages compression)) 'gzip))

  (define build
    #~(begin
        (use-modules (guix build utils)
                     (srfi srfi-1) (srfi srfi-26)
                     (ice-9 ftw))

        (define (info-file? file)
          (or (string-suffix? ".info" file)
              (string-suffix? ".info.gz" file)))

        (define (info-files top)
          (let ((infodir (string-append top "/share/info")))
            (map (cut string-append infodir "/" <>)
                 (or (scandir infodir info-file?) '()))))

        (define (install-info info)
          (setenv "PATH" (string-append #+gzip "/bin")) ;for info.gz files
          (zero?
           (system* (string-append #+texinfo "/bin/install-info")
                    info (string-append #$output "/share/info/dir"))))

        (mkdir-p (string-append #$output "/share/info"))
        (every install-info
               (append-map info-files
                           '#$(manifest-inputs manifest)))))

  (gexp->derivation "info-dir" build
                    #:modules '((guix build utils))))

(define (ghc-package-cache-file manifest)
  "Return a derivation that builds the GHC 'package.cache' file for all the
entries of MANIFEST, or #f if MANIFEST does not have any GHC packages."
  (define ghc                                 ;lazy reference
    (module-ref (resolve-interface '(gnu packages haskell)) 'ghc))

  (define build
    #~(begin
        (use-modules (guix build utils)
                     (srfi srfi-1) (srfi srfi-26)
                     (ice-9 ftw))

        (define ghc-name-version
          (let* ((base (basename #+ghc)))
            (string-drop base
                         (+ 1 (string-index base #\-)))))

        (define db-subdir
          (string-append "lib/" ghc-name-version "/package.conf.d"))

        (define db-dir
          (string-append #$output "/" db-subdir))

        (define (conf-files top)
          (let ((db (string-append top "/" db-subdir)))
            (if (file-exists? db)
                (find-files db "\\.conf$")
                '())))

        (define (copy-conf-file conf)
          (let ((base (basename conf)))
            (copy-file conf (string-append db-dir "/" base))))

        (system* (string-append #+ghc "/bin/ghc-pkg") "init" db-dir)
        (for-each copy-conf-file
                  (append-map conf-files
                              (delete-duplicates
                               '#$(manifest-inputs manifest))))
        (let ((success
               (zero?
                (system* (string-append #+ghc "/bin/ghc-pkg") "recache"
                         (string-append "--package-db=" db-dir)))))
          (for-each delete-file (find-files db-dir "\\.conf$"))
          success)))

  (with-monad %store-monad
    ;; Don't depend on GHC when there's nothing to do.
    (if (any (cut string-prefix? "ghc" <>)
             (map manifest-entry-name (manifest-entries manifest)))
        (gexp->derivation "ghc-package-cache" build
                          #:modules '((guix build utils))
                          #:local-build? #t)
        (return #f))))

(define (ca-certificate-bundle manifest)
  "Return a derivation that builds a single-file bundle containing the CA
certificates in the /etc/ssl/certs sub-directories of the packages in
MANIFEST.  Single-file bundles are required by programs such as Git and Lynx."
  ;; See <http://lists.gnu.org/archive/html/guix-devel/2015-02/msg00429.html>
  ;; for a discussion.

  (define glibc-utf8-locales                      ;lazy reference
    (module-ref (resolve-interface '(gnu packages base)) 'glibc-utf8-locales))

  (define build
    #~(begin
        (use-modules (guix build utils)
                     (rnrs io ports)
                     (srfi srfi-1)
                     (srfi srfi-26)
                     (ice-9 ftw)
                     (ice-9 match))

        (define (pem-file? file)
          (string-suffix? ".pem" file))

        (define (ca-files top)
          (let ((cert-dir (string-append top "/etc/ssl/certs")))
            (map (cut string-append cert-dir "/" <>)
                 (or (scandir cert-dir pem-file?) '()))))

        (define (concatenate-files files result)
          "Make RESULT the concatenation of all of FILES."
          (define (dump file port)
            (display (call-with-input-file file get-string-all)
                     port)
            (newline port))    ;required, see <https://bugs.debian.org/635570>

          (call-with-output-file result
            (lambda (port)
              (for-each (cut dump <> port) files))))

        ;; Some file names in the NSS certificates are UTF-8 encoded so
        ;; install a UTF-8 locale.
        (setenv "LOCPATH" (string-append #+glibc-utf8-locales "/lib/locale"))
        (setlocale LC_ALL "en_US.UTF-8")

        (match (append-map ca-files '#$(manifest-inputs manifest))
          (()
           ;; Since there are no CA files, just create an empty directory.  Do
           ;; not create the etc/ssl/certs sub-directory, since that would
           ;; wrongfully lead to a message about 'SSL_CERT_DIR' needing to be
           ;; defined.
           (mkdir #$output)
           #t)
          ((ca-files ...)
           (let ((result (string-append #$output "/etc/ssl/certs")))
             (mkdir-p result)
             (concatenate-files ca-files
                                (string-append result
                                               "/ca-certificates.crt"))
             #t)))))

  (gexp->derivation "ca-certificate-bundle" build
                    #:modules '((guix build utils))
                    #:local-build? #t))

(define (gtk-icon-themes manifest)
  "Return a derivation that unions all icon themes from manifest entries and
creates the GTK+ 'icon-theme.cache' file for each theme."
  ;; Return as a monadic value the GTK+ package or store path referenced by the
  ;; manifest ENTRY, or #f if not referenced.
  (define (entry-lookup-gtk+ entry)
    (define (find-among-inputs inputs)
      (find (lambda (input)
              (and (package? input)
                   (string=? "gtk+" (package-name input))))
            inputs))

    (define (find-among-store-items items)
      (find (lambda (item)
              (equal? "gtk+"
                      (package-name->name+version
                       (store-path-package-name item))))
            items))

    ;; TODO: Factorize.
    (define references*
      (store-lift references))

    (with-monad %store-monad
      (match (manifest-entry-item entry)
        ((? package? package)
         (match (package-transitive-inputs package)
           (((labels inputs . _) ...)
            (return (find-among-inputs inputs)))))
        ((? string? item)
         (mlet %store-monad ((refs (references* item)))
           (return (find-among-store-items refs)))))))

  (define (manifest-lookup-gtk+ manifest)
    (anym %store-monad
          entry-lookup-gtk+ (manifest-entries manifest)))

  (mlet %store-monad ((gtk+ (manifest-lookup-gtk+ manifest)))
    (define build
      #~(begin
          (use-modules (guix build utils)
                       (guix build union)
                       (guix build profiles)
                       (srfi srfi-26)
                       (ice-9 ftw))

          (let* ((destdir  (string-append #$output "/share/icons"))
                 (icondirs (filter file-exists?
                                   (map (cut string-append <> "/share/icons")
                                        '#$(manifest-inputs manifest))))
                 (update-icon-cache (string-append
                                     #+gtk+ "/bin/gtk-update-icon-cache")))

            ;; Union all the icons.
            (mkdir-p (string-append #$output "/share"))
            (union-build destdir icondirs)

            ;; Update the 'icon-theme.cache' file for each icon theme.
            (for-each
             (lambda (theme)
               (let ((dir (string-append destdir "/" theme)))
                 ;; Occasionally DESTDIR contains plain files, such as
                 ;; "abiword_48.png".  Ignore these.
                 (when (file-is-directory? dir)
                   (ensure-writable-directory dir)
                   (system* update-icon-cache "-t" dir))))
             (scandir destdir (negate (cut member <> '("." ".."))))))))

    ;; Don't run the hook when there's nothing to do.
    (if gtk+
        (gexp->derivation "gtk-icon-themes" build
                          #:modules '((guix build utils)
                                      (guix build union)
                                      (guix build profiles)
                                      (guix search-paths)
                                      (guix records))
                          #:local-build? #t)
        (return #f))))

(define %default-profile-hooks
  ;; This is the list of derivation-returning procedures that are called by
  ;; default when making a non-empty profile.
  (list info-dir-file
        ghc-package-cache-file
        ca-certificate-bundle
        gtk-icon-themes))

(define* (profile-derivation manifest
                             #:key
                             (hooks %default-profile-hooks))
  "Return a derivation that builds a profile (aka. 'user environment') with
the given MANIFEST.  The profile includes additional derivations returned by
the monadic procedures listed in HOOKS--such as an Info 'dir' file, etc."
  (mlet %store-monad ((extras (if (null? (manifest-entries manifest))
                                  (return '())
                                  (sequence %store-monad
                                            (map (lambda (hook)
                                                   (hook manifest))
                                                 hooks)))))
    (define inputs
      (append (filter-map (lambda (drv)
                            (and (derivation? drv)
                                 (gexp-input drv)))
                          extras)
              (manifest-inputs manifest)))

    (define builder
      #~(begin
          (use-modules (guix build profiles)
                       (guix search-paths)
                       (srfi srfi-1))

          (setvbuf (current-output-port) _IOLBF)
          (setvbuf (current-error-port) _IOLBF)

          (define search-paths
            ;; Search paths of MANIFEST's packages, converted back to their
            ;; record form.
            (map sexp->search-path-specification
                 (delete-duplicates
                  '#$(map search-path-specification->sexp
                          (append-map manifest-entry-search-paths
                                      (manifest-entries manifest))))))

          (build-profile #$output '#$inputs
                         #:manifest '#$(manifest->gexp manifest)
                         #:search-paths search-paths)))

    (gexp->derivation "profile" builder
                      #:modules '((guix build profiles)
                                  (guix build union)
                                  (guix build utils)
                                  (guix search-paths)
                                  (guix records))
                      #:local-build? #t)))

(define (profile-regexp profile)
  "Return a regular expression that matches PROFILE's name and number."
  (make-regexp (string-append "^" (regexp-quote (basename profile))
                              "-([0-9]+)")))

(define (generation-number profile)
  "Return PROFILE's number or 0.  An absolute file name must be used."
  (or (and=> (false-if-exception (regexp-exec (profile-regexp profile)
                                              (basename (readlink profile))))
             (compose string->number (cut match:substring <> 1)))
      0))

(define (generation-numbers profile)
  "Return the sorted list of generation numbers of PROFILE, or '(0) if no
former profiles were found."
  (define* (scandir name #:optional (select? (const #t))
                    (entry<? (@ (ice-9 i18n) string-locale<?)))
    ;; XXX: Bug-fix version introduced in Guile v2.0.6-62-g139ce19.
    (define (enter? dir stat result)
      (and stat (string=? dir name)))

    (define (visit basename result)
      (if (select? basename)
          (cons basename result)
          result))

    (define (leaf name stat result)
      (and result
           (visit (basename name) result)))

    (define (down name stat result)
      (visit "." '()))

    (define (up name stat result)
      (visit ".." result))

    (define (skip name stat result)
      ;; All the sub-directories are skipped.
      (visit (basename name) result))

    (define (error name* stat errno result)
      (if (string=? name name*)             ; top-level NAME is unreadable
          result
          (visit (basename name*) result)))

    (and=> (file-system-fold enter? leaf down up skip error #f name lstat)
           (lambda (files)
             (sort files entry<?))))

  (match (scandir (dirname profile)
                  (cute regexp-exec (profile-regexp profile) <>))
    (#f                                         ; no profile directory
     '(0))
    (()                                         ; no profiles
     '(0))
    ((profiles ...)                             ; former profiles around
     (sort (map (compose string->number
                         (cut match:substring <> 1)
                         (cute regexp-exec (profile-regexp profile) <>))
                profiles)
           <))))

(define (profile-generations profile)
  "Return a list of PROFILE's generations."
  (let ((generations (generation-numbers profile)))
    (if (equal? generations '(0))
        '()
        generations)))

(define* (relative-generation profile shift #:optional
                              (current (generation-number profile)))
  "Return PROFILE's generation shifted from the CURRENT generation by SHIFT.
SHIFT is a positive or negative number.
Return #f if there is no such generation."
  (let* ((abs-shift (abs shift))
         (numbers (profile-generations profile))
         (from-current (memq current
                             (if (negative? shift)
                                 (reverse numbers)
                                 numbers))))
    (and from-current
         (< abs-shift (length from-current))
         (list-ref from-current abs-shift))))

(define* (previous-generation-number profile #:optional
                                     (number (generation-number profile)))
  "Return the number of the generation before generation NUMBER of
PROFILE, or 0 if none exists.  It could be NUMBER - 1, but it's not the
case when generations have been deleted (there are \"holes\")."
  (or (relative-generation profile -1 number)
      0))

(define (generation-file-name profile generation)
  "Return the file name for PROFILE's GENERATION."
  (format #f "~a-~a-link" profile generation))

(define (generation-time profile number)
  "Return the creation time of a generation in the UTC format."
  (make-time time-utc 0
             (stat:ctime (stat (generation-file-name profile number)))))

;;; profiles.scm ends here