profiles: Really disable deprecation warnings for 'profile-derivation'.
[guix.git] / guix / profiles.scm
blobcedf9faa82f89d974574e9a979dc0eac38ff68fc
1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2013, 2014, 2015, 2016, 2017 Ludovic Courtès <ludo@gnu.org>
3 ;;; Copyright © 2013 Nikita Karetnikov <nikita@karetnikov.org>
4 ;;; Copyright © 2014, 2016 Alex Kost <alezost@gmail.com>
5 ;;; Copyright © 2015 Mark H Weaver <mhw@netris.org>
6 ;;; Copyright © 2015 Sou Bunnbu <iyzsong@gmail.com>
7 ;;; Copyright © 2016 Ricardo Wurmus <rekado@elephly.net>
8 ;;; Copyright © 2016 Chris Marusich <cmmarusich@gmail.com>
9 ;;; Copyright © 2017 Huang Ying <huang.ying.caritas@gmail.com>
10 ;;; Copyright © 2017 Maxim Cournoyer <maxim.cournoyer@gmail.com>
11 ;;;
12 ;;; This file is part of GNU Guix.
13 ;;;
14 ;;; GNU Guix is free software; you can redistribute it and/or modify it
15 ;;; under the terms of the GNU General Public License as published by
16 ;;; the Free Software Foundation; either version 3 of the License, or (at
17 ;;; your option) any later version.
18 ;;;
19 ;;; GNU Guix is distributed in the hope that it will be useful, but
20 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 ;;; GNU General Public License for more details.
23 ;;;
24 ;;; You should have received a copy of the GNU General Public License
25 ;;; along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>.
27 (define-module (guix profiles)
28   #:use-module ((guix utils) #:hide (package-name->name+version))
29   #:use-module ((guix build utils)
30                 #:select (package-name->name+version))
31   #:use-module (guix records)
32   #:use-module (guix packages)
33   #:use-module (guix derivations)
34   #:use-module (guix search-paths)
35   #:use-module (guix gexp)
36   #:use-module (guix monads)
37   #:use-module (guix store)
38   #:use-module (guix sets)
39   #:use-module (ice-9 vlist)
40   #:use-module (ice-9 match)
41   #:use-module (ice-9 regex)
42   #:use-module (ice-9 ftw)
43   #:use-module (ice-9 format)
44   #:use-module (srfi srfi-1)
45   #:use-module (srfi srfi-9)
46   #:use-module (srfi srfi-11)
47   #:use-module (srfi srfi-19)
48   #:use-module (srfi srfi-26)
49   #:use-module (srfi srfi-34)
50   #:use-module (srfi srfi-35)
51   #:export (&profile-error
52             profile-error?
53             profile-error-profile
54             &profile-not-found-error
55             profile-not-found-error?
56             &profile-collistion-error
57             profile-collision-error?
58             profile-collision-error-entry
59             profile-collision-error-conflict
60             &missing-generation-error
61             missing-generation-error?
62             missing-generation-error-generation
64             manifest make-manifest
65             manifest?
66             manifest-entries
67             manifest-transitive-entries
69             <manifest-entry>              ; FIXME: eventually make it internal
70             manifest-entry
71             manifest-entry?
72             manifest-entry-name
73             manifest-entry-version
74             manifest-entry-output
75             manifest-entry-item
76             manifest-entry-dependencies
77             manifest-entry-search-paths
78             manifest-entry-parent
80             manifest-pattern
81             manifest-pattern?
82             manifest-pattern-name
83             manifest-pattern-version
84             manifest-pattern-output
86             manifest-remove
87             manifest-add
88             manifest-lookup
89             manifest-installed?
90             manifest-matching-entries
92             manifest-transaction
93             manifest-transaction?
94             manifest-transaction-install
95             manifest-transaction-remove
96             manifest-transaction-install-entry
97             manifest-transaction-remove-pattern
98             manifest-transaction-null?
99             manifest-transaction-removal-candidate?
100             manifest-perform-transaction
101             manifest-transaction-effects
103             profile-manifest
104             package->manifest-entry
105             packages->manifest
106             ca-certificate-bundle
107             %default-profile-hooks
108             profile-derivation
110             generation-number
111             generation-numbers
112             profile-generations
113             relative-generation-spec->number
114             relative-generation
115             previous-generation-number
116             generation-time
117             generation-file-name
118             switch-to-generation
119             roll-back
120             delete-generation))
122 ;;; Commentary:
124 ;;; Tools to create and manipulate profiles---i.e., the representation of a
125 ;;; set of installed packages.
127 ;;; Code:
131 ;;; Condition types.
134 (define-condition-type &profile-error &error
135   profile-error?
136   (profile profile-error-profile))
138 (define-condition-type &profile-not-found-error &profile-error
139   profile-not-found-error?)
141 (define-condition-type &profile-collision-error &error
142   profile-collision-error?
143   (entry    profile-collision-error-entry)        ;<manifest-entry>
144   (conflict profile-collision-error-conflict))    ;<manifest-entry>
146 (define-condition-type &missing-generation-error &profile-error
147   missing-generation-error?
148   (generation missing-generation-error-generation))
152 ;;; Manifests.
155 (define-record-type <manifest>
156   (manifest entries)
157   manifest?
158   (entries manifest-entries))                     ; list of <manifest-entry>
160 ;; Convenient alias, to avoid name clashes.
161 (define make-manifest manifest)
163 (define-record-type* <manifest-entry> manifest-entry
164   make-manifest-entry
165   manifest-entry?
166   (name         manifest-entry-name)              ; string
167   (version      manifest-entry-version)           ; string
168   (output       manifest-entry-output             ; string
169                 (default "out"))
170   (item         manifest-entry-item)              ; package | store path
171   (dependencies manifest-entry-dependencies       ; <manifest-entry>*
172                 (default '()))
173   (search-paths manifest-entry-search-paths       ; search-path-specification*
174                 (default '()))
175   (parent       manifest-entry-parent        ; promise (#f | <manifest-entry>)
176                 (default (delay #f))))
178 (define-record-type* <manifest-pattern> manifest-pattern
179   make-manifest-pattern
180   manifest-pattern?
181   (name         manifest-pattern-name)            ; string
182   (version      manifest-pattern-version          ; string | #f
183                 (default #f))
184   (output       manifest-pattern-output           ; string | #f
185                 (default "out")))
187 (define (manifest-transitive-entries manifest)
188   "Return the entries of MANIFEST along with their propagated inputs,
189 recursively."
190   (let loop ((entries (manifest-entries manifest))
191              (result  '())
192              (visited (set)))                     ;compare with 'equal?'
193     (match entries
194       (()
195        (reverse result))
196       ((head . tail)
197        (if (set-contains? visited head)
198            (loop tail result visited)
199            (loop (append (manifest-entry-dependencies head)
200                          tail)
201                  (cons head result)
202                  (set-insert head visited)))))))
204 (define (profile-manifest profile)
205   "Return the PROFILE's manifest."
206   (let ((file (string-append profile "/manifest")))
207     (if (file-exists? file)
208         (call-with-input-file file read-manifest)
209         (manifest '()))))
211 (define (manifest-entry-lookup manifest)
212   "Return a lookup procedure for the entries of MANIFEST.  The lookup
213 procedure takes two arguments: the entry name and output."
214   (define mapping
215     (let loop ((entries (manifest-entries manifest))
216                (mapping vlist-null))
217       (fold (lambda (entry result)
218               (vhash-cons (cons (manifest-entry-name entry)
219                                 (manifest-entry-output entry))
220                           entry
221                           (loop (manifest-entry-dependencies entry)
222                                 result)))
223             mapping
224             entries)))
226   (lambda (name output)
227     (match (vhash-assoc (cons name output) mapping)
228       ((_ . entry) entry)
229       (#f          #f))))
231 (define* (lower-manifest-entry entry system #:key target)
232   "Lower ENTRY for SYSTEM and TARGET such that its 'item' field is a store
233 file name."
234   (let ((item (manifest-entry-item entry)))
235     (if (string? item)
236         (with-monad %store-monad
237           (return entry))
238         (mlet %store-monad ((drv (lower-object item system
239                                                #:target target))
240                             (output -> (manifest-entry-output entry)))
241           (return (manifest-entry
242                     (inherit entry)
243                     (item (derivation->output-path drv output))))))))
245 (define* (check-for-collisions manifest system #:key target)
246   "Check whether the entries of MANIFEST conflict with one another; raise a
247 '&profile-collision-error' when a conflict is encountered."
248   (define lookup
249     (manifest-entry-lookup manifest))
251   (with-monad %store-monad
252     (foldm %store-monad
253            (lambda (entry result)
254              (match (lookup (manifest-entry-name entry)
255                             (manifest-entry-output entry))
256                ((? manifest-entry? second)        ;potential conflict
257                 (mlet %store-monad ((first (lower-manifest-entry entry system
258                                                                  #:target
259                                                                  target))
260                                     (second (lower-manifest-entry second system
261                                                                   #:target
262                                                                   target)))
263                   (if (string=? (manifest-entry-item first)
264                                 (manifest-entry-item second))
265                       (return result)
266                       (raise (condition
267                               (&profile-collision-error
268                                (entry first)
269                                (conflict second)))))))
270                (#f                                ;no conflict
271                 (return result))))
272            #t
273            (manifest-transitive-entries manifest))))
275 (define* (package->manifest-entry package #:optional (output "out")
276                                   #:key (parent (delay #f)))
277   "Return a manifest entry for the OUTPUT of package PACKAGE."
278   ;; For each dependency, keep a promise pointing to its "parent" entry.
279   (letrec* ((deps  (map (match-lambda
280                           ((label package)
281                            (package->manifest-entry package
282                                                     #:parent (delay entry)))
283                           ((label package output)
284                            (package->manifest-entry package output
285                                                     #:parent (delay entry))))
286                         (package-propagated-inputs package)))
287             (entry (manifest-entry
288                      (name (package-name package))
289                      (version (package-version package))
290                      (output output)
291                      (item package)
292                      (dependencies (delete-duplicates deps))
293                      (search-paths
294                       (package-transitive-native-search-paths package))
295                      (parent parent))))
296     entry))
298 (define (packages->manifest packages)
299   "Return a list of manifest entries, one for each item listed in PACKAGES.
300 Elements of PACKAGES can be either package objects or package/string tuples
301 denoting a specific output of a package."
302   (manifest
303    (map (match-lambda
304          ((package output)
305           (package->manifest-entry package output))
306          ((? package? package)
307           (package->manifest-entry package)))
308         packages)))
310 (define (manifest->gexp manifest)
311   "Return a representation of MANIFEST as a gexp."
312   (define (entry->gexp entry)
313     (match entry
314       (($ <manifest-entry> name version output (? string? path)
315                            (deps ...) (search-paths ...))
316        #~(#$name #$version #$output #$path
317                  (propagated-inputs #$(map entry->gexp deps))
318                  (search-paths #$(map search-path-specification->sexp
319                                       search-paths))))
320       (($ <manifest-entry> name version output (? package? package)
321                            (deps ...) (search-paths ...))
322        #~(#$name #$version #$output
323                  (ungexp package (or output "out"))
324                  (propagated-inputs #$(map entry->gexp deps))
325                  (search-paths #$(map search-path-specification->sexp
326                                       search-paths))))))
328   (match manifest
329     (($ <manifest> (entries ...))
330      #~(manifest (version 3)
331                  (packages #$(map entry->gexp entries))))))
333 (define (find-package name version)
334   "Return a package from the distro matching NAME and possibly VERSION.  This
335 procedure is here for backward-compatibility and will eventually vanish."
336   (define find-best-packages-by-name              ;break abstractions
337     (module-ref (resolve-interface '(gnu packages))
338                 'find-best-packages-by-name))
340    ;; Use 'find-best-packages-by-name' and not 'find-packages-by-name'; the
341    ;; former traverses the module tree only once and then allows for efficient
342    ;; access via a vhash.
343    (match (find-best-packages-by-name name version)
344      ((p _ ...) p)
345      (_
346       (match (find-best-packages-by-name name #f)
347         ((p _ ...) p)
348         (_ #f)))))
350 (define (sexp->manifest sexp)
351   "Parse SEXP as a manifest."
352   (define (infer-search-paths name version)
353     ;; Infer the search path specifications for NAME-VERSION by looking up a
354     ;; same-named package in the distro.  Useful for the old manifest formats
355     ;; that did not store search path info.
356     (let ((package (find-package name version)))
357       (if package
358           (package-native-search-paths package)
359           '())))
361   (define (infer-dependency item parent)
362     ;; Return a <manifest-entry> for ITEM.
363     (let-values (((name version)
364                   (package-name->name+version
365                    (store-path-package-name item))))
366       (manifest-entry
367         (name name)
368         (version version)
369         (item item)
370         (parent parent))))
372   (define* (sexp->manifest-entry sexp #:optional (parent (delay #f)))
373     (match sexp
374       ((name version output path
375              ('propagated-inputs deps)
376              ('search-paths search-paths)
377              extra-stuff ...)
378        ;; For each of DEPS, keep a promise pointing to ENTRY.
379        (letrec* ((deps* (map (cut sexp->manifest-entry <> (delay entry))
380                              deps))
381                  (entry (manifest-entry
382                           (name name)
383                           (version version)
384                           (output output)
385                           (item path)
386                           (dependencies deps*)
387                           (search-paths (map sexp->search-path-specification
388                                              search-paths))
389                           (parent parent))))
390          entry))))
392   (match sexp
393     (('manifest ('version 0)
394                 ('packages ((name version output path) ...)))
395      (manifest
396       (map (lambda (name version output path)
397              (manifest-entry
398                (name name)
399                (version version)
400                (output output)
401                (item path)
402                (search-paths (infer-search-paths name version))))
403            name version output path)))
405     ;; Version 1 adds a list of propagated inputs to the
406     ;; name/version/output/path tuples.
407     (('manifest ('version 1)
408                 ('packages ((name version output path deps) ...)))
409      (manifest
410       (map (lambda (name version output path deps)
411              ;; Up to Guix 0.7 included, dependencies were listed as ("gmp"
412              ;; "/gnu/store/...-gmp") for instance.  Discard the 'label' in
413              ;; such lists.
414              (let ((deps (match deps
415                            (((labels directories) ...)
416                             directories)
417                            ((directories ...)
418                             directories))))
419                (letrec* ((deps* (map (cute infer-dependency <> (delay entry))
420                                      deps))
421                          (entry (manifest-entry
422                                   (name name)
423                                   (version version)
424                                   (output output)
425                                   (item path)
426                                   (dependencies deps*)
427                                   (search-paths
428                                    (infer-search-paths name version)))))
429                  entry)))
430            name version output path deps)))
432     ;; Version 2 adds search paths and is slightly more verbose.
433     (('manifest ('version 2 minor-version ...)
434                 ('packages ((name version output path
435                                   ('propagated-inputs deps)
436                                   ('search-paths search-paths)
437                                   extra-stuff ...)
438                             ...)))
439      (manifest
440       (map (lambda (name version output path deps search-paths)
441              (letrec* ((deps* (map (cute infer-dependency <> (delay entry))
442                                    deps))
443                        (entry (manifest-entry
444                                 (name name)
445                                 (version version)
446                                 (output output)
447                                 (item path)
448                                 (dependencies deps*)
449                                 (search-paths
450                                  (map sexp->search-path-specification
451                                       search-paths)))))
452                entry))
453            name version output path deps search-paths)))
455     ;; Version 3 represents DEPS as full-blown manifest entries.
456     (('manifest ('version 3 minor-version ...)
457                 ('packages (entries ...)))
458      (manifest (map sexp->manifest-entry entries)))
459     (_
460      (raise (condition
461              (&message (message "unsupported manifest format")))))))
463 (define (read-manifest port)
464   "Return the packages listed in MANIFEST."
465   (sexp->manifest (read port)))
467 (define (entry-predicate pattern)
468   "Return a procedure that returns #t when passed a manifest entry that
469 matches NAME/OUTPUT/VERSION.  OUTPUT and VERSION may be #f, in which case they
470 are ignored."
471   (match pattern
472     (($ <manifest-pattern> name version output)
473      (match-lambda
474       (($ <manifest-entry> entry-name entry-version entry-output)
475        (and (string=? entry-name name)
476             (or (not entry-output) (not output)
477                 (string=? entry-output output))
478             (or (not version)
479                 (string=? entry-version version))))))))
481 (define (manifest-remove manifest patterns)
482   "Remove entries for each of PATTERNS from MANIFEST.  Each item in PATTERNS
483 must be a manifest-pattern."
484   (define (remove-entry pattern lst)
485     (remove (entry-predicate pattern) lst))
487   (make-manifest (fold remove-entry
488                        (manifest-entries manifest)
489                        patterns)))
491 (define (manifest-add manifest entries)
492   "Add a list of manifest ENTRIES to MANIFEST and return new manifest.
493 Remove MANIFEST entries that have the same name and output as ENTRIES."
494   (define (same-entry? entry name output)
495     (match entry
496       (($ <manifest-entry> entry-name _ entry-output _ ...)
497        (and (equal? name entry-name)
498             (equal? output entry-output)))))
500   (make-manifest
501    (append entries
502            (fold (lambda (entry result)
503                    (match entry
504                      (($ <manifest-entry> name _ out _ ...)
505                       (filter (negate (cut same-entry? <> name out))
506                               result))))
507                  (manifest-entries manifest)
508                  entries))))
510 (define (manifest-lookup manifest pattern)
511   "Return the first item of MANIFEST that matches PATTERN, or #f if there is
512 no match.."
513   (find (entry-predicate pattern)
514         (manifest-entries manifest)))
516 (define (manifest-installed? manifest pattern)
517   "Return #t if MANIFEST has an entry matching PATTERN (a manifest-pattern),
518 #f otherwise."
519   (->bool (manifest-lookup manifest pattern)))
521 (define (manifest-matching-entries manifest patterns)
522   "Return all the entries of MANIFEST that match one of the PATTERNS."
523   (define predicates
524     (map entry-predicate patterns))
526   (define (matches? entry)
527     (any (lambda (pred)
528            (pred entry))
529          predicates))
531   (filter matches? (manifest-entries manifest)))
535 ;;; Manifest transactions.
538 (define-record-type* <manifest-transaction> manifest-transaction
539   make-manifest-transaction
540   manifest-transaction?
541   (install manifest-transaction-install ; list of <manifest-entry>
542            (default '()))
543   (remove  manifest-transaction-remove  ; list of <manifest-pattern>
544            (default '())))
546 (define (manifest-transaction-install-entry entry transaction)
547   "Augment TRANSACTION's set of installed packages with ENTRY, a
548 <manifest-entry>."
549   (manifest-transaction
550    (inherit transaction)
551    (install
552     (cons entry (manifest-transaction-install transaction)))))
554 (define (manifest-transaction-remove-pattern pattern transaction)
555   "Add PATTERN to TRANSACTION's list of packages to remove."
556   (manifest-transaction
557    (inherit transaction)
558    (remove
559     (cons pattern (manifest-transaction-remove transaction)))))
561 (define (manifest-transaction-null? transaction)
562   "Return true if TRANSACTION has no effect---i.e., it neither installs nor
563 remove software."
564   (match transaction
565     (($ <manifest-transaction> () ()) #t)
566     (($ <manifest-transaction> _ _)   #f)))
568 (define (manifest-transaction-removal-candidate? entry transaction)
569   "Return true if ENTRY is a candidate for removal in TRANSACTION."
570   (any (lambda (pattern)
571          ((entry-predicate pattern) entry))
572        (manifest-transaction-remove transaction)))
574 (define (manifest-transaction-effects manifest transaction)
575   "Compute the effect of applying TRANSACTION to MANIFEST.  Return 4 values:
576 the list of packages that would be removed, installed, upgraded, or downgraded
577 when applying TRANSACTION to MANIFEST.  Upgrades are represented as pairs
578 where the head is the entry being upgraded and the tail is the entry that will
579 replace it."
580   (define (manifest-entry->pattern entry)
581     (manifest-pattern
582       (name   (manifest-entry-name entry))
583       (output (manifest-entry-output entry))))
585   (let loop ((input     (manifest-transaction-install transaction))
586              (install   '())
587              (upgrade   '())
588              (downgrade '()))
589     (match input
590       (()
591        (let ((remove (manifest-transaction-remove transaction)))
592          (values (manifest-matching-entries manifest remove)
593                  (reverse install) (reverse upgrade) (reverse downgrade))))
594       ((entry rest ...)
595        ;; Check whether installing ENTRY corresponds to the installation of a
596        ;; new package or to an upgrade.
598        ;; XXX: When the exact same output directory is installed, we're not
599        ;; really upgrading anything.  Add a check for that case.
600        (let* ((pattern  (manifest-entry->pattern entry))
601               (previous (manifest-lookup manifest pattern))
602               (newer?   (and previous
603                              (version>=? (manifest-entry-version entry)
604                                          (manifest-entry-version previous)))))
605          (loop rest
606                (if previous install (cons entry install))
607                (if (and previous newer?)
608                    (alist-cons previous entry upgrade)
609                    upgrade)
610                (if (and previous (not newer?))
611                    (alist-cons previous entry downgrade)
612                    downgrade)))))))
614 (define (manifest-perform-transaction manifest transaction)
615   "Perform TRANSACTION on MANIFEST and return the new manifest."
616   (let ((install (manifest-transaction-install transaction))
617         (remove  (manifest-transaction-remove transaction)))
618     (manifest-add (manifest-remove manifest remove)
619                   install)))
623 ;;; Profiles.
626 (define (manifest-inputs manifest)
627   "Return a list of <gexp-input> objects for MANIFEST."
628   (define entry->input
629     (match-lambda
630       (($ <manifest-entry> name version output thing deps)
631        ;; THING may be a package or a file name.  In the latter case, assume
632        ;; it's already valid.
633        (cons (gexp-input thing output)
634              (append-map entry->input deps)))))
636   (append-map entry->input (manifest-entries manifest)))
638 (define* (manifest-lookup-package manifest name #:optional version)
639   "Return as a monadic value the first package or store path referenced by
640 MANIFEST that is named NAME and optionally has the given VERSION prefix, or #f
641 if not found."
642   ;; Return as a monadic value the package or store path referenced by the
643   ;; manifest ENTRY, or #f if not referenced.
644   (define (entry-lookup-package entry)
645     (define (find-among-inputs inputs)
646       (find (lambda (input)
647               (and (package? input)
648                    (equal? name (package-name input))
649                    (if version
650                        (string-prefix? version (package-version input))
651                        #t)))
652             inputs))
653     (define (find-among-store-items items)
654       (find (lambda (item)
655               (let-values (((name* version*)
656                             (package-name->name+version
657                              (store-path-package-name item))))
658                 (and (string=? name name*)
659                      (if version
660                          (string-prefix? version version*)
661                          #t))))
662             items))
664     (with-monad %store-monad
665       (match (manifest-entry-item entry)
666         ((? package? package)
667          (match (cons (list (package-name package) package)
668                       (package-transitive-inputs package))
669            (((labels inputs . _) ...)
670             (return (find-among-inputs inputs)))))
671         ((? string? item)
672          (mlet %store-monad ((refs (references* item)))
673            (return (find-among-store-items refs)))))))
675   (anym %store-monad
676         entry-lookup-package (manifest-entries manifest)))
678 (define (info-dir-file manifest)
679   "Return a derivation that builds the 'dir' file for all the entries of
680 MANIFEST."
681   (define texinfo                                 ;lazy reference
682     (module-ref (resolve-interface '(gnu packages texinfo)) 'texinfo))
683   (define gzip                                    ;lazy reference
684     (module-ref (resolve-interface '(gnu packages compression)) 'gzip))
686   (define build
687     (with-imported-modules '((guix build utils))
688       #~(begin
689           (use-modules (guix build utils)
690                        (srfi srfi-1) (srfi srfi-26)
691                        (ice-9 ftw))
693           (define (info-file? file)
694             (or (string-suffix? ".info" file)
695                 (string-suffix? ".info.gz" file)))
697           (define (info-files top)
698             (let ((infodir (string-append top "/share/info")))
699               (map (cut string-append infodir "/" <>)
700                    (or (scandir infodir info-file?) '()))))
702           (define (install-info info)
703             (setenv "PATH" (string-append #+gzip "/bin")) ;for info.gz files
704             (zero?
705              (system* (string-append #+texinfo "/bin/install-info") "--silent"
706                       info (string-append #$output "/share/info/dir"))))
708           (mkdir-p (string-append #$output "/share/info"))
709           (exit (every install-info
710                        (append-map info-files
711                                    '#$(manifest-inputs manifest)))))))
713   (gexp->derivation "info-dir" build
714                     #:local-build? #t
715                     #:substitutable? #f))
717 (define (ghc-package-cache-file manifest)
718   "Return a derivation that builds the GHC 'package.cache' file for all the
719 entries of MANIFEST, or #f if MANIFEST does not have any GHC packages."
720   (define ghc                                     ;lazy reference
721     (module-ref (resolve-interface '(gnu packages haskell)) 'ghc))
723   (define build
724     (with-imported-modules '((guix build utils))
725       #~(begin
726           (use-modules (guix build utils)
727                        (srfi srfi-1) (srfi srfi-26)
728                        (ice-9 ftw))
730           (define ghc-name-version
731             (let* ((base (basename #+ghc)))
732               (string-drop base
733                            (+ 1 (string-index base #\-)))))
735           (define db-subdir
736             (string-append "lib/" ghc-name-version "/package.conf.d"))
738           (define db-dir
739             (string-append #$output "/" db-subdir))
741           (define (conf-files top)
742             (let ((db (string-append top "/" db-subdir)))
743               (if (file-exists? db)
744                   (find-files db "\\.conf$")
745                   '())))
747           (define (copy-conf-file conf)
748             (let ((base (basename conf)))
749               (copy-file conf (string-append db-dir "/" base))))
751           (system* (string-append #+ghc "/bin/ghc-pkg") "init" db-dir)
752           (for-each copy-conf-file
753                     (append-map conf-files
754                                 (delete-duplicates
755                                  '#$(manifest-inputs manifest))))
756           (let ((success
757                  (zero?
758                   (system* (string-append #+ghc "/bin/ghc-pkg") "recache"
759                            (string-append "--package-db=" db-dir)))))
760             (for-each delete-file (find-files db-dir "\\.conf$"))
761             (exit success)))))
763   (with-monad %store-monad
764     ;; Don't depend on GHC when there's nothing to do.
765     (if (any (cut string-prefix? "ghc" <>)
766              (map manifest-entry-name (manifest-entries manifest)))
767         (gexp->derivation "ghc-package-cache" build
768                           #:local-build? #t
769                           #:substitutable? #f)
770         (return #f))))
772 (define (ca-certificate-bundle manifest)
773   "Return a derivation that builds a single-file bundle containing the CA
774 certificates in the /etc/ssl/certs sub-directories of the packages in
775 MANIFEST.  Single-file bundles are required by programs such as Git and Lynx."
776   ;; See <http://lists.gnu.org/archive/html/guix-devel/2015-02/msg00429.html>
777   ;; for a discussion.
779   (define glibc-utf8-locales                      ;lazy reference
780     (module-ref (resolve-interface '(gnu packages base)) 'glibc-utf8-locales))
782   (define build
783     (with-imported-modules '((guix build utils))
784       #~(begin
785           (use-modules (guix build utils)
786                        (rnrs io ports)
787                        (srfi srfi-1)
788                        (srfi srfi-26)
789                        (ice-9 ftw)
790                        (ice-9 match))
792           (define (pem-file? file)
793             (string-suffix? ".pem" file))
795           (define (ca-files top)
796             (let ((cert-dir (string-append top "/etc/ssl/certs")))
797               (map (cut string-append cert-dir "/" <>)
798                    (or (scandir cert-dir pem-file?) '()))))
800           (define (concatenate-files files result)
801             "Make RESULT the concatenation of all of FILES."
802             (define (dump file port)
803               (display (call-with-input-file file get-string-all)
804                        port)
805               (newline port))  ;required, see <https://bugs.debian.org/635570>
807             (call-with-output-file result
808               (lambda (port)
809                 (for-each (cut dump <> port) files))))
811           ;; Some file names in the NSS certificates are UTF-8 encoded so
812           ;; install a UTF-8 locale.
813           (setenv "LOCPATH"
814                   (string-append #+glibc-utf8-locales "/lib/locale/"
815                                  #+(package-version glibc-utf8-locales)))
816           (setlocale LC_ALL "en_US.utf8")
818           (match (append-map ca-files '#$(manifest-inputs manifest))
819             (()
820              ;; Since there are no CA files, just create an empty directory.  Do
821              ;; not create the etc/ssl/certs sub-directory, since that would
822              ;; wrongfully lead to a message about 'SSL_CERT_DIR' needing to be
823              ;; defined.
824              (mkdir #$output)
825              #t)
826             ((ca-files ...)
827              (let ((result (string-append #$output "/etc/ssl/certs")))
828                (mkdir-p result)
829                (concatenate-files ca-files
830                                   (string-append result
831                                                  "/ca-certificates.crt"))
832                #t))))))
834   (gexp->derivation "ca-certificate-bundle" build
835                     #:local-build? #t
836                     #:substitutable? #f))
838 (define (gtk-icon-themes manifest)
839   "Return a derivation that unions all icon themes from manifest entries and
840 creates the GTK+ 'icon-theme.cache' file for each theme."
841   (define gtk+  ; lazy reference
842     (module-ref (resolve-interface '(gnu packages gtk)) 'gtk+))
844   (mlet %store-monad ((%gtk+ (manifest-lookup-package manifest "gtk+"))
845                       ;; XXX: Can't use gtk-update-icon-cache corresponding
846                       ;; to the gtk+ referenced by 'manifest'.  Because
847                       ;; '%gtk+' can be either a package or store path, and
848                       ;; there's no way to get the "bin" output for the later.
849                       (gtk-update-icon-cache
850                        -> #~(string-append #+gtk+:bin
851                                            "/bin/gtk-update-icon-cache")))
853     (define build
854       (with-imported-modules '((guix build utils)
855                                (guix build union)
856                                (guix build profiles)
857                                (guix search-paths)
858                                (guix records))
859         #~(begin
860             (use-modules (guix build utils)
861                          (guix build union)
862                          (guix build profiles)
863                          (srfi srfi-26)
864                          (ice-9 ftw))
866             (let* ((destdir  (string-append #$output "/share/icons"))
867                    (icondirs (filter file-exists?
868                                      (map (cut string-append <> "/share/icons")
869                                           '#$(manifest-inputs manifest)))))
871               ;; Union all the icons.
872               (mkdir-p (string-append #$output "/share"))
873               (union-build destdir icondirs
874                            #:log-port (%make-void-port "w"))
876               ;; Update the 'icon-theme.cache' file for each icon theme.
877               (for-each
878                (lambda (theme)
879                  (let ((dir (string-append destdir "/" theme)))
880                    ;; Occasionally DESTDIR contains plain files, such as
881                    ;; "abiword_48.png".  Ignore these.
882                    (when (file-is-directory? dir)
883                      (ensure-writable-directory dir)
884                      (system* #+gtk-update-icon-cache "-t" dir "--quiet"))))
885                (scandir destdir (negate (cut member <> '("." "..")))))))))
887     ;; Don't run the hook when there's nothing to do.
888     (if %gtk+
889         (gexp->derivation "gtk-icon-themes" build
890                           #:local-build? #t
891                           #:substitutable? #f)
892         (return #f))))
894 (define (gtk-im-modules manifest)
895   "Return a derivation that builds the cache files for input method modules
896 for both major versions of GTK+."
898   (mlet %store-monad ((gtk+   (manifest-lookup-package manifest "gtk+" "3"))
899                       (gtk+-2 (manifest-lookup-package manifest "gtk+" "2")))
901     (define (build gtk gtk-version query)
902       (let ((major (string-take gtk-version 1)))
903         (with-imported-modules '((guix build utils)
904                                  (guix build union)
905                                  (guix build profiles)
906                                  (guix search-paths)
907                                  (guix records))
908           #~(begin
909               (use-modules (guix build utils)
910                            (guix build union)
911                            (guix build profiles)
912                            (ice-9 popen)
913                            (srfi srfi-1)
914                            (srfi srfi-26))
916               (let* ((prefix  (string-append "/lib/gtk-" #$major ".0/"
917                                              #$gtk-version))
918                      (destdir (string-append #$output prefix))
919                      (moddirs (cons (string-append #$gtk prefix "/immodules")
920                                     (filter file-exists?
921                                             (map (cut string-append <> prefix "/immodules")
922                                                  '#$(manifest-inputs manifest)))))
923                      (modules (append-map (cut find-files <> "\\.so$")
924                                           moddirs)))
926                 ;; Generate a new immodules cache file.
927                 (mkdir-p (string-append #$output prefix))
928                 (let ((pipe    (apply open-pipe* OPEN_READ #$query modules))
929                       (outfile (string-append #$output prefix
930                                               "/immodules-gtk" #$major ".cache")))
931                   (dynamic-wind
932                     (const #t)
933                     (lambda ()
934                       (call-with-output-file outfile
935                         (lambda (out)
936                           (while (not (eof-object? (peek-char pipe)))
937                             (write-char (read-char pipe) out))))
938                       #t)
939                     (lambda ()
940                       (close-pipe pipe)))))))))
942     ;; Don't run the hook when there's nothing to do.
943     (let* ((pkg-gtk+ (module-ref        ; lazy reference
944                       (resolve-interface '(gnu packages gtk)) 'gtk+))
945            (gexp #~(begin
946                      #$(if gtk+
947                            (build
948                             gtk+ "3.0.0"
949                             ;; Use 'gtk-query-immodules-3.0' from the 'bin'
950                             ;; output of latest gtk+ package.
951                             #~(string-append
952                                #$pkg-gtk+:bin "/bin/gtk-query-immodules-3.0"))
953                            #t)
954                      #$(if gtk+-2
955                            (build
956                             gtk+-2 "2.10.0"
957                             #~(string-append
958                                #$gtk+-2 "/bin/gtk-query-immodules-2.0"))
959                            #t))))
960       (if (or gtk+ gtk+-2)
961           (gexp->derivation "gtk-im-modules" gexp
962                             #:local-build? #t
963                             #:substitutable? #f)
964           (return #f)))))
966 (define (xdg-desktop-database manifest)
967   "Return a derivation that builds the @file{mimeinfo.cache} database from
968 desktop files.  It's used to query what applications can handle a given
969 MIME type."
970   (define desktop-file-utils            ; lazy reference
971     (module-ref (resolve-interface '(gnu packages freedesktop))
972                 'desktop-file-utils))
974   (mlet %store-monad ((glib
975                        (manifest-lookup-package
976                         manifest "glib")))
977     (define build
978       (with-imported-modules '((guix build utils)
979                                (guix build union))
980         #~(begin
981             (use-modules (srfi srfi-26)
982                          (guix build utils)
983                          (guix build union))
984             (let* ((destdir (string-append #$output "/share/applications"))
985                    (appdirs (filter file-exists?
986                                     (map (cut string-append <>
987                                               "/share/applications")
988                                          '#$(manifest-inputs manifest))))
989                    (update-desktop-database (string-append
990                                              #+desktop-file-utils
991                                              "/bin/update-desktop-database")))
992               (mkdir-p (string-append #$output "/share"))
993               (union-build destdir appdirs
994                            #:log-port (%make-void-port "w"))
995               (exit (zero? (system* update-desktop-database destdir)))))))
997     ;; Don't run the hook when 'glib' is not referenced.
998     (if glib
999         (gexp->derivation "xdg-desktop-database" build
1000                           #:local-build? #t
1001                           #:substitutable? #f)
1002         (return #f))))
1004 (define (xdg-mime-database manifest)
1005   "Return a derivation that builds the @file{mime.cache} database from manifest
1006 entries.  It's used to query the MIME type of a given file."
1007   (define shared-mime-info  ; lazy reference
1008     (module-ref (resolve-interface '(gnu packages gnome)) 'shared-mime-info))
1010   (mlet %store-monad ((glib
1011                        (manifest-lookup-package
1012                         manifest "glib")))
1013     (define build
1014       (with-imported-modules  '((guix build utils)
1015                                 (guix build union))
1016         #~(begin
1017             (use-modules (srfi srfi-26)
1018                          (guix build utils)
1019                          (guix build union))
1020             (let* ((datadir (string-append #$output "/share"))
1021                    (destdir (string-append datadir "/mime"))
1022                    (pkgdirs (filter file-exists?
1023                                     (map (cut string-append <>
1024                                               "/share/mime/packages")
1025                                          (cons #+shared-mime-info
1026                                                '#$(manifest-inputs manifest)))))
1027                    (update-mime-database (string-append
1028                                           #+shared-mime-info
1029                                           "/bin/update-mime-database")))
1030               (mkdir-p destdir)
1031               (union-build (string-append destdir "/packages") pkgdirs
1032                            #:log-port (%make-void-port "w"))
1033               (setenv "XDG_DATA_HOME" datadir)
1034               (exit (zero? (system* update-mime-database destdir)))))))
1036     ;; Don't run the hook when there are no GLib based applications.
1037     (if glib
1038         (gexp->derivation "xdg-mime-database" build
1039                           #:local-build? #t
1040                           #:substitutable? #f)
1041         (return #f))))
1043 ;; Several font packages may install font files into same directory, so
1044 ;; fonts.dir and fonts.scale file should be generated here, instead of in
1045 ;; packages.
1046 (define (fonts-dir-file manifest)
1047   "Return a derivation that builds the @file{fonts.dir} and @file{fonts.scale}
1048 files for the fonts of the @var{manifest} entries."
1049   (define mkfontscale
1050     (module-ref (resolve-interface '(gnu packages xorg)) 'mkfontscale))
1052   (define mkfontdir
1053     (module-ref (resolve-interface '(gnu packages xorg)) 'mkfontdir))
1055   (define build
1056     #~(begin
1057         (use-modules (srfi srfi-26)
1058                      (guix build utils)
1059                      (guix build union))
1060         (let ((fonts-dirs (filter file-exists?
1061                                   (map (cut string-append <>
1062                                             "/share/fonts")
1063                                        '#$(manifest-inputs manifest)))))
1064           (mkdir #$output)
1065           (if (null? fonts-dirs)
1066               (exit #t)
1067               (let* ((share-dir   (string-append #$output "/share"))
1068                      (fonts-dir   (string-append share-dir "/fonts"))
1069                      (mkfontscale (string-append #+mkfontscale
1070                                                  "/bin/mkfontscale"))
1071                      (mkfontdir   (string-append #+mkfontdir
1072                                                  "/bin/mkfontdir"))
1073                      (empty-file? (lambda (filename)
1074                                     (call-with-ascii-input-file filename
1075                                       (lambda (p)
1076                                         (eqv? #\0 (read-char p))))))
1077                      (fonts-dir-file "fonts.dir")
1078                      (fonts-scale-file "fonts.scale"))
1079                 (mkdir-p share-dir)
1080                 ;; Create all sub-directories, because we may create fonts.dir
1081                 ;; and fonts.scale files in the sub-directories.
1082                 (union-build fonts-dir fonts-dirs
1083                              #:log-port (%make-void-port "w")
1084                              #:create-all-directories? #t)
1085                 (let ((directories (find-files fonts-dir
1086                                                (lambda (file stat)
1087                                                  (eq? 'directory (stat:type stat)))
1088                                                #:directories? #t)))
1089                   (for-each (lambda (dir)
1090                               (with-directory-excursion dir
1091                                 (when (file-exists? fonts-scale-file)
1092                                   (delete-file fonts-scale-file))
1093                                 (when (file-exists? fonts-dir-file)
1094                                   (delete-file fonts-dir-file))
1095                                 (unless (and (zero? (system* mkfontscale))
1096                                              (zero? (system* mkfontdir)))
1097                                   (exit #f))
1098                                 (when (and (file-exists? fonts-scale-file)
1099                                            (empty-file? fonts-scale-file))
1100                                   (delete-file fonts-scale-file))
1101                                 (when (and (file-exists? fonts-dir-file)
1102                                            (empty-file? fonts-dir-file))
1103                                   (delete-file fonts-dir-file))))
1104                             directories)))))))
1106   (gexp->derivation "fonts-dir" build
1107                     #:modules '((guix build utils)
1108                                 (guix build union)
1109                                 (srfi srfi-26))
1110                     #:local-build? #t
1111                     #:substitutable? #f))
1113 (define (manual-database manifest)
1114   "Return a derivation that builds the manual page database (\"mandb\") for
1115 the entries in MANIFEST."
1116   (define man-db                                  ;lazy reference
1117     (module-ref (resolve-interface '(gnu packages man)) 'man-db))
1119   (define build
1120     (with-imported-modules '((guix build utils))
1121       #~(begin
1122           (use-modules (guix build utils)
1123                        (srfi srfi-1)
1124                        (srfi srfi-19)
1125                        (srfi srfi-26))
1127           (define entries
1128             (filter-map (lambda (directory)
1129                           (let ((man (string-append directory "/share/man")))
1130                             (and (directory-exists? man)
1131                                  man)))
1132                         '#$(manifest-inputs manifest)))
1134           (define manpages-collection-dir
1135             (string-append (getenv "PWD") "/manpages-collection"))
1137           (define man-directory
1138             (string-append #$output "/share/man"))
1140           (define (get-manpage-tail-path manpage-path)
1141             (let ((index (string-contains manpage-path "/share/man/")))
1142               (unless index
1143                 (error "Manual path doesn't contain \"/share/man/\":"
1144                        manpage-path))
1145               (string-drop manpage-path (+ index (string-length "/share/man/")))))
1147           (define (populate-manpages-collection-dir entries)
1148             (let ((manpages (append-map (cut find-files <> #:stat stat) entries)))
1149               (for-each (lambda (manpage)
1150                           (let* ((dest-file (string-append
1151                                              manpages-collection-dir "/"
1152                                              (get-manpage-tail-path manpage))))
1153                             (mkdir-p (dirname dest-file))
1154                             (catch 'system-error
1155                               (lambda ()
1156                                 (symlink manpage dest-file))
1157                               (lambda args
1158                                 ;; Different packages may contain the same
1159                                 ;; manpage.  Simply ignore the symlink error.
1160                                 #t))))
1161                         manpages)))
1163           (mkdir-p manpages-collection-dir)
1164           (populate-manpages-collection-dir entries)
1166           ;; Create a mandb config file which contains a custom made
1167           ;; manpath. The associated catpath is the location where the database
1168           ;; gets generated.
1169           (copy-file #+(file-append man-db "/etc/man_db.conf")
1170                      "man_db.conf")
1171           (substitute* "man_db.conf"
1172             (("MANDB_MAP        /usr/man                /var/cache/man/fsstnd")
1173              (string-append "MANDB_MAP " manpages-collection-dir " "
1174                             man-directory)))
1176           (mkdir-p man-directory)
1177           (setenv "MANPATH" (string-join entries ":"))
1179           (format #t "Creating manual page database for ~a packages... "
1180                   (length entries))
1181           (force-output)
1182           (let* ((start-time (current-time))
1183                  (exit-status (system* #+(file-append man-db "/bin/mandb")
1184                                        "--quiet" "--create"
1185                                        "-C" "man_db.conf"))
1186                  (duration (time-difference (current-time) start-time)))
1187             (format #t "done in ~,3f s~%"
1188                     (+ (time-second duration)
1189                        (* (time-nanosecond duration) (expt 10 -9))))
1190             (force-output)
1191             (zero? exit-status)))))
1193   (gexp->derivation "manual-database" build
1194                     #:local-build? #t))
1196 (define %default-profile-hooks
1197   ;; This is the list of derivation-returning procedures that are called by
1198   ;; default when making a non-empty profile.
1199   (list info-dir-file
1200         manual-database
1201         fonts-dir-file
1202         ghc-package-cache-file
1203         ca-certificate-bundle
1204         gtk-icon-themes
1205         gtk-im-modules
1206         xdg-desktop-database
1207         xdg-mime-database))
1209 (define* (profile-derivation manifest
1210                              #:key
1211                              (hooks %default-profile-hooks)
1212                              (locales? #t)
1213                              (allow-collisions? #f)
1214                              system target)
1215   "Return a derivation that builds a profile (aka. 'user environment') with
1216 the given MANIFEST.  The profile includes additional derivations returned by
1217 the monadic procedures listed in HOOKS--such as an Info 'dir' file, etc.
1218 Unless ALLOW-COLLISIONS? is true, a '&profile-collision-error' is raised if
1219 entries in MANIFEST collide (for instance if there are two same-name packages
1220 with a different version number.)
1222 When LOCALES? is true, the build is performed under a UTF-8 locale; this adds
1223 a dependency on the 'glibc-utf8-locales' package.
1225 When TARGET is true, it must be a GNU triplet, and the packages in MANIFEST
1226 are cross-built for TARGET."
1227   (mlet* %store-monad ((system (if system
1228                                    (return system)
1229                                    (current-system)))
1230                        (ok?    (if allow-collisions?
1231                                    (return #t)
1232                                    (check-for-collisions manifest system
1233                                                          #:target target)))
1234                        (extras (if (null? (manifest-entries manifest))
1235                                    (return '())
1236                                    (sequence %store-monad
1237                                              (map (lambda (hook)
1238                                                     (hook manifest))
1239                                                   hooks)))))
1240     (define inputs
1241       (append (filter-map (lambda (drv)
1242                             (and (derivation? drv)
1243                                  (gexp-input drv)))
1244                           extras)
1245               (manifest-inputs manifest)))
1247     (define glibc-utf8-locales                    ;lazy reference
1248       (module-ref (resolve-interface '(gnu packages base))
1249                   'glibc-utf8-locales))
1251     (define set-utf8-locale
1252       ;; Some file names (e.g., in 'nss-certs') are UTF-8 encoded so
1253       ;; install a UTF-8 locale.
1254       #~(begin
1255           (setenv "LOCPATH"
1256                   #$(file-append glibc-utf8-locales "/lib/locale/"
1257                                  (package-version glibc-utf8-locales)))
1258           (setlocale LC_ALL "en_US.utf8")))
1260     (define builder
1261       (with-imported-modules '((guix build profiles)
1262                                (guix build union)
1263                                (guix build utils)
1264                                (guix search-paths)
1265                                (guix records))
1266         #~(begin
1267             (use-modules (guix build profiles)
1268                          (guix search-paths)
1269                          (srfi srfi-1))
1271             (setvbuf (current-output-port) _IOLBF)
1272             (setvbuf (current-error-port) _IOLBF)
1274             #+(if locales? set-utf8-locale #t)
1276             (define search-paths
1277               ;; Search paths of MANIFEST's packages, converted back to their
1278               ;; record form.
1279               (map sexp->search-path-specification
1280                    (delete-duplicates
1281                     '#$(map search-path-specification->sexp
1282                             (append-map manifest-entry-search-paths
1283                                         (manifest-entries manifest))))))
1285             (build-profile #$output '#$inputs
1286                            #:manifest '#$(manifest->gexp manifest)
1287                            #:search-paths search-paths))))
1289     (gexp->derivation "profile" builder
1290                       #:system system
1291                       #:target target
1293                       ;; Don't complain about _IO* on Guile 2.2.
1294                       #:env-vars '(("GUILE_WARN_DEPRECATED" . "no"))
1296                       ;; Not worth offloading.
1297                       #:local-build? #t
1299                       ;; Disable substitution because it would trigger a
1300                       ;; connection to the substitute server, which is likely
1301                       ;; to have no substitute to offer.
1302                       #:substitutable? #f)))
1304 (define (profile-regexp profile)
1305   "Return a regular expression that matches PROFILE's name and number."
1306   (make-regexp (string-append "^" (regexp-quote (basename profile))
1307                               "-([0-9]+)")))
1309 (define (generation-number profile)
1310   "Return PROFILE's number or 0.  An absolute file name must be used."
1311   (or (and=> (false-if-exception (regexp-exec (profile-regexp profile)
1312                                               (basename (readlink profile))))
1313              (compose string->number (cut match:substring <> 1)))
1314       0))
1316 (define (generation-numbers profile)
1317   "Return the sorted list of generation numbers of PROFILE, or '(0) if no
1318 former profiles were found."
1319   (match (scandir (dirname profile)
1320                   (cute regexp-exec (profile-regexp profile) <>))
1321     (#f                                         ; no profile directory
1322      '(0))
1323     (()                                         ; no profiles
1324      '(0))
1325     ((profiles ...)                             ; former profiles around
1326      (sort (map (compose string->number
1327                          (cut match:substring <> 1)
1328                          (cute regexp-exec (profile-regexp profile) <>))
1329                 profiles)
1330            <))))
1332 (define (profile-generations profile)
1333   "Return a list of PROFILE's generations."
1334   (let ((generations (generation-numbers profile)))
1335     (if (equal? generations '(0))
1336         '()
1337         generations)))
1339 (define (relative-generation-spec->number profile spec)
1340   "Return PROFILE's generation specified by SPEC, which is a string.  The SPEC
1341 may be a N, -N, or +N, where N is a number.  If the spec is N, then the number
1342 returned is N.  If it is -N, then the number returned is the profile's current
1343 generation number minus N.  If it is +N, then the number returned is the
1344 profile's current generation number plus N.  Return #f if there is no such
1345 generation."
1346   (let ((number (string->number spec)))
1347     (and number
1348          (case (string-ref spec 0)
1349            ((#\+ #\-)
1350             (relative-generation profile number))
1351            (else (if (memv number (profile-generations profile))
1352                      number
1353                      #f))))))
1356 (define* (relative-generation profile shift #:optional
1357                               (current (generation-number profile)))
1358   "Return PROFILE's generation shifted from the CURRENT generation by SHIFT.
1359 SHIFT is a positive or negative number.
1360 Return #f if there is no such generation."
1361   (let* ((abs-shift (abs shift))
1362          (numbers (profile-generations profile))
1363          (from-current (memq current
1364                              (if (negative? shift)
1365                                  (reverse numbers)
1366                                  numbers))))
1367     (and from-current
1368          (< abs-shift (length from-current))
1369          (list-ref from-current abs-shift))))
1371 (define* (previous-generation-number profile #:optional
1372                                      (number (generation-number profile)))
1373   "Return the number of the generation before generation NUMBER of
1374 PROFILE, or 0 if none exists.  It could be NUMBER - 1, but it's not the
1375 case when generations have been deleted (there are \"holes\")."
1376   (or (relative-generation profile -1 number)
1377       0))
1379 (define (generation-file-name profile generation)
1380   "Return the file name for PROFILE's GENERATION."
1381   (format #f "~a-~a-link" profile generation))
1383 (define (generation-time profile number)
1384   "Return the creation time of a generation in the UTC format."
1385   (make-time time-utc 0
1386              (stat:ctime (stat (generation-file-name profile number)))))
1388 (define (link-to-empty-profile store generation)
1389   "Link GENERATION, a string, to the empty profile.  An error is raised if
1390 that fails."
1391   (let* ((drv  (run-with-store store
1392                  (profile-derivation (manifest '())
1393                                      #:locales? #f)))
1394          (prof (derivation->output-path drv "out")))
1395     (build-derivations store (list drv))
1396     (switch-symlinks generation prof)))
1398 (define (switch-to-generation profile number)
1399   "Atomically switch PROFILE to the generation NUMBER.  Return the number of
1400 the generation that was current before switching."
1401   (let ((current    (generation-number profile))
1402         (generation (generation-file-name profile number)))
1403     (cond ((not (file-exists? profile))
1404            (raise (condition (&profile-not-found-error
1405                               (profile profile)))))
1406           ((not (file-exists? generation))
1407            (raise (condition (&missing-generation-error
1408                               (profile profile)
1409                               (generation number)))))
1410           (else
1411            (switch-symlinks profile generation)
1412            current))))
1414 (define (switch-to-previous-generation profile)
1415   "Atomically switch PROFILE to the previous generation.  Return the former
1416 generation number and the current one."
1417   (let ((previous (previous-generation-number profile)))
1418     (values (switch-to-generation profile previous)
1419             previous)))
1421 (define (roll-back store profile)
1422   "Roll back to the previous generation of PROFILE.  Return the number of the
1423 generation that was current before switching and the new generation number."
1424   (let* ((number              (generation-number profile))
1425          (previous-number     (previous-generation-number profile number))
1426          (previous-generation (generation-file-name profile previous-number)))
1427     (cond ((not (file-exists? profile))           ;invalid profile
1428            (raise (condition (&profile-not-found-error
1429                               (profile profile)))))
1430           ((zero? number)                         ;empty profile
1431            (values number number))
1432           ((or (zero? previous-number)            ;going to emptiness
1433                (not (file-exists? previous-generation)))
1434            (link-to-empty-profile store previous-generation)
1435            (switch-to-previous-generation profile))
1436           (else                                   ;anything else
1437            (switch-to-previous-generation profile)))))
1439 (define (delete-generation store profile number)
1440   "Delete generation with NUMBER from PROFILE.  Return the file name of the
1441 generation that has been deleted, or #f if nothing was done (for instance
1442 because the NUMBER is zero.)"
1443   (define (delete-and-return)
1444     (let ((generation (generation-file-name profile number)))
1445       (delete-file generation)
1446       generation))
1448   (let* ((current-number      (generation-number profile))
1449          (previous-number     (previous-generation-number profile number))
1450          (previous-generation (generation-file-name profile previous-number)))
1451     (cond ((zero? number) #f)                     ;do not delete generation 0
1452           ((and (= number current-number)
1453                 (not (file-exists? previous-generation)))
1454            (link-to-empty-profile store previous-generation)
1455            (switch-to-previous-generation profile)
1456            (delete-and-return))
1457           ((= number current-number)
1458            (roll-back store profile)
1459            (delete-and-return))
1460           (else
1461            (delete-and-return)))))
1463 ;;; profiles.scm ends here