Merge branch 'master' into core-updates-frozen
[jackhill/guix/guix.git] / doc / guix-cookbook.texi
1 \input texinfo
2 @c -*-texinfo-*-
3
4 @c %**start of header
5 @setfilename guix-cookbook.info
6 @documentencoding UTF-8
7 @settitle GNU Guix Cookbook
8 @c %**end of header
9
10 @copying
11 Copyright @copyright{} 2019 Ricardo Wurmus@*
12 Copyright @copyright{} 2019 Efraim Flashner@*
13 Copyright @copyright{} 2019 Pierre Neidhardt@*
14 Copyright @copyright{} 2020 Oleg Pykhalov@*
15 Copyright @copyright{} 2020 Matthew Brooks@*
16 Copyright @copyright{} 2020 Marcin Karpezo@*
17 Copyright @copyright{} 2020 Brice Waegeneire@*
18 Copyright @copyright{} 2020 André Batista@*
19 Copyright @copyright{} 2020 Christine Lemmer-Webber@*
20 Copyright @copyright{} 2021 Joshua Branson@*
21
22 Permission is granted to copy, distribute and/or modify this document
23 under the terms of the GNU Free Documentation License, Version 1.3 or
24 any later version published by the Free Software Foundation; with no
25 Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A
26 copy of the license is included in the section entitled ``GNU Free
27 Documentation License''.
28 @end copying
29
30 @dircategory System administration
31 @direntry
32 * Guix cookbook: (guix-cookbook). Tutorials and examples for GNU Guix.
33 @end direntry
34
35 @titlepage
36 @title GNU Guix Cookbook
37 @subtitle Tutorials and examples for using the GNU Guix Functional Package Manager
38 @author The GNU Guix Developers
39
40 @page
41 @vskip 0pt plus 1filll
42
43 @insertcopying
44 @end titlepage
45
46 @contents
47
48 @c *********************************************************************
49 @node Top
50 @top GNU Guix Cookbook
51
52 This document presents tutorials and detailed examples for GNU@tie{}Guix, a
53 functional package management tool written for the GNU system. Please
54 @pxref{Top,,, guix, GNU Guix reference manual} for details about the system,
55 its API, and related concepts.
56
57 @c TRANSLATORS: You can replace the following paragraph with information on
58 @c how to join your own translation team and how to report issues with the
59 @c translation.
60 This manual is also available in French (@pxref{Top,,, guix-cookbook.fr,
61 Livre de recettes de GNU Guix}) and German (@pxref{Top,,,
62 guix-cookbook.de, GNU-Guix-Kochbuch}). If you would like to translate
63 this document in your native language, consider joining
64 @uref{https://translate.fedoraproject.org/projects/guix/documentation-cookbook,
65 Weblate} (@pxref{Translating Guix,,, guix, GNU Guix reference manual}).
66
67 @menu
68 * Scheme tutorials:: Meet your new favorite language!
69 * Packaging:: Packaging tutorials
70 * System Configuration:: Customizing the GNU System
71 * Advanced package management:: Power to the users!
72 * Environment management:: Control environment
73
74 * Acknowledgments:: Thanks!
75 * GNU Free Documentation License:: The license of this document.
76 * Concept Index:: Concepts.
77
78 @detailmenu
79 --- The Detailed Node Listing ---
80
81 Scheme tutorials
82
83 * A Scheme Crash Course:: Learn the basics of Scheme
84
85 Packaging
86
87 * Packaging Tutorial:: Let's add a package to Guix!
88
89 System Configuration
90
91 * Auto-Login to a Specific TTY:: Automatically Login a User to a Specific TTY
92 * Customizing the Kernel:: Creating and using a custom Linux kernel on Guix System.
93
94 @end detailmenu
95 @end menu
96
97 @c *********************************************************************
98 @node Scheme tutorials
99 @chapter Scheme tutorials
100
101 GNU@tie{}Guix is written in the general purpose programming language Scheme,
102 and many of its features can be accessed and manipulated programmatically.
103 You can use Scheme to generate package definitions, to modify them, to build
104 them, to deploy whole operating systems, etc.
105
106 Knowing the basics of how to program in Scheme will unlock many of the
107 advanced features Guix provides --- and you don't even need to be an
108 experienced programmer to use them!
109
110 Let's get started!
111
112 @node A Scheme Crash Course
113 @section A Scheme Crash Course
114
115 @cindex Scheme, crash course
116
117 Guix uses the Guile implementation of Scheme. To start playing with the
118 language, install it with @code{guix install guile} and start a
119 @dfn{REPL}---short for @uref{https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop,
120 @dfn{read-eval-print loop}}---by running @code{guile} from the command line.
121
122 Alternatively you can also run @code{guix environment --ad-hoc guile -- guile}
123 if you'd rather not have Guile installed in your user profile.
124
125 In the following examples, lines show what you would type at the REPL;
126 lines starting with ``@result{}'' show evaluation results, while lines
127 starting with ``@print{}'' show things that get printed. @xref{Using Guile
128 Interactively,,, guile, GNU Guile Reference Manual}, for more details on the
129 REPL.
130
131 @itemize
132 @item
133 Scheme syntax boils down to a tree of expressions (or @emph{s-expression} in
134 Lisp lingo). An expression can be a literal such as numbers and strings, or a
135 compound which is a parenthesized list of compounds and literals. @code{#true}
136 and @code{#false} (abbreviated @code{#t} and @code{#f}) stand for the
137 Booleans ``true'' and ``false'', respectively.
138
139 Examples of valid expressions:
140
141 @lisp
142 "Hello World!"
143 @result{} "Hello World!"
144
145 17
146 @result{} 17
147
148 (display (string-append "Hello " "Guix" "\n"))
149 @print{} Hello Guix!
150 @result{} #<unspecified>
151 @end lisp
152
153 @item
154 This last example is a function call nested in another function call. When a
155 parenthesized expression is evaluated, the first term is the function and the
156 rest are the arguments passed to the function. Every function returns the
157 last evaluated expression as its return value.
158
159 @item
160 Anonymous functions are declared with the @code{lambda} term:
161
162 @lisp
163 (lambda (x) (* x x))
164 @result{} #<procedure 120e348 at <unknown port>:24:0 (x)>
165 @end lisp
166
167 The above procedure returns the square of its argument. Since everything is
168 an expression, the @code{lambda} expression returns an anonymous procedure,
169 which can in turn be applied to an argument:
170
171 @lisp
172 ((lambda (x) (* x x)) 3)
173 @result{} 9
174 @end lisp
175
176 @item
177 Anything can be assigned a global name with @code{define}:
178
179 @lisp
180 (define a 3)
181 (define square (lambda (x) (* x x)))
182 (square a)
183 @result{} 9
184 @end lisp
185
186 @item
187 Procedures can be defined more concisely with the following syntax:
188
189 @lisp
190 (define (square x) (* x x))
191 @end lisp
192
193 @item
194 A list structure can be created with the @code{list} procedure:
195
196 @lisp
197 (list 2 a 5 7)
198 @result{} (2 3 5 7)
199 @end lisp
200
201 @item
202 The @dfn{quote} disables evaluation of a parenthesized expression: the
203 first term is not called over the other terms (@pxref{Expression Syntax,
204 quote,, guile, GNU Guile Reference Manual}). Thus it effectively
205 returns a list of terms.
206
207 @lisp
208 '(display (string-append "Hello " "Guix" "\n"))
209 @result{} (display (string-append "Hello " "Guix" "\n"))
210
211 '(2 a 5 7)
212 @result{} (2 a 5 7)
213 @end lisp
214
215 @item
216 The @dfn{quasiquote} disables evaluation of a parenthesized expression
217 until @dfn{unquote} (a comma) re-enables it. Thus it provides us with
218 fine-grained control over what is evaluated and what is not.
219
220 @lisp
221 `(2 a 5 7 (2 ,a 5 ,(+ a 4)))
222 @result{} (2 a 5 7 (2 3 5 7))
223 @end lisp
224
225 Note that the above result is a list of mixed elements: numbers, symbols (here
226 @code{a}) and the last element is a list itself.
227
228 @item
229 Multiple variables can be named locally with @code{let} (@pxref{Local
230 Bindings,,, guile, GNU Guile Reference Manual}):
231
232 @lisp
233 (define x 10)
234 (let ((x 2)
235 (y 3))
236 (list x y))
237 @result{} (2 3)
238
239 x
240 @result{} 10
241
242 y
243 @error{} In procedure module-lookup: Unbound variable: y
244 @end lisp
245
246 Use @code{let*} to allow later variable declarations to refer to earlier
247 definitions.
248
249 @lisp
250 (let* ((x 2)
251 (y (* x 3)))
252 (list x y))
253 @result{} (2 6)
254 @end lisp
255
256 @item
257 @dfn{Keywords} are typically used to identify the named parameters of a
258 procedure. They are prefixed by @code{#:} (hash, colon) followed by
259 alphanumeric characters: @code{#:like-this}.
260 @xref{Keywords,,, guile, GNU Guile Reference Manual}.
261
262 @item
263 The percentage @code{%} is typically used for read-only global variables in
264 the build stage. Note that it is merely a convention, like @code{_} in C.
265 Scheme treats @code{%} exactly the same as any other letter.
266
267 @item
268 Modules are created with @code{define-module} (@pxref{Creating Guile
269 Modules,,, guile, GNU Guile Reference Manual}). For instance
270
271 @lisp
272 (define-module (guix build-system ruby)
273 #:use-module (guix store)
274 #:export (ruby-build
275 ruby-build-system))
276 @end lisp
277
278 defines the module @code{guix build-system ruby} which must be located in
279 @file{guix/build-system/ruby.scm} somewhere in the Guile load path. It
280 depends on the @code{(guix store)} module and it exports two variables,
281 @code{ruby-build} and @code{ruby-build-system}.
282 @end itemize
283
284 For a more detailed introduction, check out
285 @uref{http://www.troubleshooters.com/codecorn/scheme_guile/hello.htm, Scheme
286 at a Glance}, by Steve Litt.
287
288 One of the reference Scheme books is the seminal ``Structure and
289 Interpretation of Computer Programs'', by Harold Abelson and Gerald Jay
290 Sussman, with Julie Sussman. You'll find a
291 @uref{https://mitpress.mit.edu/sites/default/files/sicp/index.html, free copy
292 online}, together with
293 @uref{https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-001-structure-and-interpretation-of-computer-programs-spring-2005/video-lectures/,
294 videos of the lectures by the authors}. The book is available in Texinfo
295 format as the @code{sicp} Guix package. Go ahead, run @code{guix install
296 sicp} and start reading with @code{info sicp} (@pxref{,,, sicp, Structure and Interpretation of Computer Programs}).
297 An @uref{https://sarabander.github.io/sicp/, unofficial ebook is also
298 available}.
299
300 You'll find more books, tutorials and other resources at
301 @url{https://schemers.org/}.
302
303
304 @c *********************************************************************
305 @node Packaging
306 @chapter Packaging
307
308 @cindex packaging
309
310 This chapter is dedicated to teaching you how to add packages to the
311 collection of packages that come with GNU Guix. This involves writing package
312 definitions in Guile Scheme, organizing them in package modules, and building
313 them.
314
315 @menu
316 * Packaging Tutorial:: A tutorial on how to add packages to Guix.
317 @end menu
318
319 @node Packaging Tutorial
320 @section Packaging Tutorial
321
322 GNU Guix stands out as the @emph{hackable} package manager, mostly because it
323 uses @uref{https://www.gnu.org/software/guile/, GNU Guile}, a powerful
324 high-level programming language, one of the
325 @uref{https://en.wikipedia.org/wiki/Scheme_%28programming_language%29, Scheme}
326 dialects from the
327 @uref{https://en.wikipedia.org/wiki/Lisp_%28programming_language%29, Lisp family}.
328
329 Package definitions are also written in Scheme, which empowers Guix in some
330 very unique ways, unlike most other package managers that use shell scripts or
331 simple languages.
332
333 @itemize
334 @item
335 Use functions, structures, macros and all of Scheme expressiveness for your
336 package definitions.
337
338 @item
339 Inheritance makes it easy to customize a package by inheriting from it and
340 modifying only what is needed.
341
342 @item
343 Batch processing: the whole package collection can be parsed, filtered and
344 processed. Building a headless server with all graphical interfaces stripped
345 out? It's possible. Want to rebuild everything from source using specific
346 compiler optimization flags? Pass the @code{#:make-flags "..."} argument to
347 the list of packages. It wouldn't be a stretch to think
348 @uref{https://wiki.gentoo.org/wiki/USE_flag, Gentoo USE flags} here, but this
349 goes even further: the changes don't have to be thought out beforehand by the
350 packager, they can be @emph{programmed} by the user!
351 @end itemize
352
353 The following tutorial covers all the basics around package creation with Guix.
354 It does not assume much knowledge of the Guix system nor of the Lisp language.
355 The reader is only expected to be familiar with the command line and to have some
356 basic programming knowledge.
357
358 @node A ``Hello World'' package
359 @subsection A ``Hello World'' package
360
361 The ``Defining Packages'' section of the manual introduces the basics of Guix
362 packaging (@pxref{Defining Packages,,, guix, GNU Guix Reference Manual}). In
363 the following section, we will partly go over those basics again.
364
365 GNU@tie{}Hello is a dummy project that serves as an idiomatic example for
366 packaging. It uses the GNU build system (@code{./configure && make && make
367 install}). Guix already provides a package definition which is a perfect
368 example to start with. You can look up its declaration with @code{guix edit
369 hello} from the command line. Let's see how it looks:
370
371 @lisp
372 (define-public hello
373 (package
374 (name "hello")
375 (version "2.10")
376 (source (origin
377 (method url-fetch)
378 (uri (string-append "mirror://gnu/hello/hello-" version
379 ".tar.gz"))
380 (sha256
381 (base32
382 "0ssi1wpaf7plaswqqjwigppsg5fyh99vdlb9kzl7c9lng89ndq1i"))))
383 (build-system gnu-build-system)
384 (synopsis "Hello, GNU world: An example GNU package")
385 (description
386 "GNU Hello prints the message \"Hello, world!\" and then exits. It
387 serves as an example of standard GNU coding practices. As such, it supports
388 command-line arguments, multiple languages, and so on.")
389 (home-page "https://www.gnu.org/software/hello/")
390 (license gpl3+)))
391 @end lisp
392
393 As you can see, most of it is rather straightforward. But let's review the
394 fields together:
395
396 @table @samp
397 @item name
398 The project name. Using Scheme conventions, we prefer to keep it
399 lower case, without underscore and using dash-separated words.
400
401 @item source
402 This field contains a description of the source code origin. The
403 @code{origin} record contains these fields:
404
405 @enumerate
406 @item The method, here @code{url-fetch} to download via HTTP/FTP, but other methods
407 exist, such as @code{git-fetch} for Git repositories.
408 @item The URI, which is typically some @code{https://} location for @code{url-fetch}. Here
409 the special `mirror://gnu` refers to a set of well known locations, all of
410 which can be used by Guix to fetch the source, should some of them fail.
411 @item The @code{sha256} checksum of the requested file. This is essential to ensure
412 the source is not corrupted. Note that Guix works with base32 strings,
413 hence the call to the @code{base32} function.
414 @end enumerate
415
416 @item build-system
417
418 This is where the power of abstraction provided by the Scheme language really
419 shines: in this case, the @code{gnu-build-system} abstracts away the famous
420 @code{./configure && make && make install} shell invocations. Other build
421 systems include the @code{trivial-build-system} which does not do anything and
422 requires from the packager to program all the build steps, the
423 @code{python-build-system}, the @code{emacs-build-system}, and many more
424 (@pxref{Build Systems,,, guix, GNU Guix Reference Manual}).
425
426 @item synopsis
427 It should be a concise summary of what the package does. For many packages a
428 tagline from the project's home page can be used as the synopsis.
429
430 @item description
431 Same as for the synopsis, it's fine to re-use the project description from the
432 homepage. Note that Guix uses Texinfo syntax.
433
434 @item home-page
435 Use HTTPS if available.
436
437 @item license
438 See @code{guix/licenses.scm} in the project source for a full list of
439 available licenses.
440 @end table
441
442 Time to build our first package! Nothing fancy here for now: we will stick to a
443 dummy @code{my-hello}, a copy of the above declaration.
444
445 As with the ritualistic ``Hello World'' taught with most programming languages,
446 this will possibly be the most ``manual'' approach. We will work out an ideal
447 setup later; for now we will go the simplest route.
448
449 Save the following to a file @file{my-hello.scm}.
450
451 @lisp
452 (use-modules (guix packages)
453 (guix download)
454 (guix build-system gnu)
455 (guix licenses))
456
457 (package
458 (name "my-hello")
459 (version "2.10")
460 (source (origin
461 (method url-fetch)
462 (uri (string-append "mirror://gnu/hello/hello-" version
463 ".tar.gz"))
464 (sha256
465 (base32
466 "0ssi1wpaf7plaswqqjwigppsg5fyh99vdlb9kzl7c9lng89ndq1i"))))
467 (build-system gnu-build-system)
468 (synopsis "Hello, Guix world: An example custom Guix package")
469 (description
470 "GNU Hello prints the message \"Hello, world!\" and then exits. It
471 serves as an example of standard GNU coding practices. As such, it supports
472 command-line arguments, multiple languages, and so on.")
473 (home-page "https://www.gnu.org/software/hello/")
474 (license gpl3+))
475 @end lisp
476
477 We will explain the extra code in a moment.
478
479 Feel free to play with the different values of the various fields. If you
480 change the source, you'll need to update the checksum. Indeed, Guix refuses to
481 build anything if the given checksum does not match the computed checksum of the
482 source code. To obtain the correct checksum of the package declaration, we
483 need to download the source, compute the sha256 checksum and convert it to
484 base32.
485
486 Thankfully, Guix can automate this task for us; all we need is to provide the
487 URI:
488
489 @c TRANSLATORS: This is example shell output.
490 @example sh
491 $ guix download mirror://gnu/hello/hello-2.10.tar.gz
492
493 Starting download of /tmp/guix-file.JLYgL7
494 From https://ftpmirror.gnu.org/gnu/hello/hello-2.10.tar.gz...
495 following redirection to `https://mirror.ibcp.fr/pub/gnu/hello/hello-2.10.tar.gz'...
496 …10.tar.gz 709KiB 2.5MiB/s 00:00 [##################] 100.0%
497 /gnu/store/hbdalsf5lpf01x4dcknwx6xbn6n5km6k-hello-2.10.tar.gz
498 0ssi1wpaf7plaswqqjwigppsg5fyh99vdlb9kzl7c9lng89ndq1i
499 @end example
500
501 In this specific case the output tells us which mirror was chosen.
502 If the result of the above command is not the same as in the above snippet,
503 update your @code{my-hello} declaration accordingly.
504
505 Note that GNU package tarballs come with an OpenPGP signature, so you
506 should definitely check the signature of this tarball with `gpg` to
507 authenticate it before going further:
508
509 @c TRANSLATORS: This is example shell output.
510 @example sh
511 $ guix download mirror://gnu/hello/hello-2.10.tar.gz.sig
512
513 Starting download of /tmp/guix-file.03tFfb
514 From https://ftpmirror.gnu.org/gnu/hello/hello-2.10.tar.gz.sig...
515 following redirection to `https://ftp.igh.cnrs.fr/pub/gnu/hello/hello-2.10.tar.gz.sig'...
516 ….tar.gz.sig 819B 1.2MiB/s 00:00 [##################] 100.0%
517 /gnu/store/rzs8wba9ka7grrmgcpfyxvs58mly0sx6-hello-2.10.tar.gz.sig
518 0q0v86n3y38z17rl146gdakw9xc4mcscpk8dscs412j22glrv9jf
519 $ gpg --verify /gnu/store/rzs8wba9ka7grrmgcpfyxvs58mly0sx6-hello-2.10.tar.gz.sig /gnu/store/hbdalsf5lpf01x4dcknwx6xbn6n5km6k-hello-2.10.tar.gz
520 gpg: Signature made Sun 16 Nov 2014 01:08:37 PM CET
521 gpg: using RSA key A9553245FDE9B739
522 gpg: Good signature from "Sami Kerola <kerolasa@@iki.fi>" [unknown]
523 gpg: aka "Sami Kerola (http://www.iki.fi/kerolasa/) <kerolasa@@iki.fi>" [unknown]
524 gpg: WARNING: This key is not certified with a trusted signature!
525 gpg: There is no indication that the signature belongs to the owner.
526 Primary key fingerprint: 8ED3 96E3 7E38 D471 A005 30D3 A955 3245 FDE9 B739
527 @end example
528
529 You can then happily run
530
531 @c TRANSLATORS: Do not translate this command
532 @example sh
533 $ guix package --install-from-file=my-hello.scm
534 @end example
535
536 You should now have @code{my-hello} in your profile!
537
538 @c TRANSLATORS: Do not translate this command
539 @example sh
540 $ guix package --list-installed=my-hello
541 my-hello 2.10 out
542 /gnu/store/f1db2mfm8syb8qvc357c53slbvf1g9m9-my-hello-2.10
543 @end example
544
545 We've gone as far as we could without any knowledge of Scheme. Before moving
546 on to more complex packages, now is the right time to brush up on your Scheme
547 knowledge. @pxref{A Scheme Crash Course} to get up to speed.
548
549 @node Setup
550 @subsection Setup
551
552 In the rest of this chapter we will rely on some basic Scheme
553 programming knowledge. Now let's detail the different possible setups
554 for working on Guix packages.
555
556 There are several ways to set up a Guix packaging environment.
557
558 We recommend you work directly on the Guix source checkout since it makes it
559 easier for everyone to contribute to the project.
560
561 But first, let's look at other possibilities.
562
563 @node Local file
564 @subsubsection Local file
565
566 This is what we previously did with @samp{my-hello}. With the Scheme basics we've
567 covered, we are now able to explain the leading chunks. As stated in @code{guix
568 package --help}:
569
570 @example
571 -f, --install-from-file=FILE
572 install the package that the code within FILE
573 evaluates to
574 @end example
575
576 Thus the last expression @emph{must} return a package, which is the case in our
577 earlier example.
578
579 The @code{use-modules} expression tells which of the modules we need in the file.
580 Modules are a collection of values and procedures. They are commonly called
581 ``libraries'' or ``packages'' in other programming languages.
582
583 @node @samp{GUIX_PACKAGE_PATH}
584 @subsubsection @samp{GUIX_PACKAGE_PATH}
585
586 @emph{Note: Starting from Guix 0.16, the more flexible Guix @dfn{channels} are the
587 preferred way and supersede @samp{GUIX_PACKAGE_PATH}. See next section.}
588
589 It can be tedious to specify the file from the command line instead of simply
590 calling @code{guix package --install my-hello} as you would do with the official
591 packages.
592
593 Guix makes it possible to streamline the process by adding as many ``package
594 declaration directories'' as you want.
595
596 Create a directory, say @file{~/guix-packages} and add it to the @samp{GUIX_PACKAGE_PATH}
597 environment variable:
598
599 @example
600 $ mkdir ~/guix-packages
601 $ export GUIX_PACKAGE_PATH=~/guix-packages
602 @end example
603
604 To add several directories, separate them with a colon (@code{:}).
605
606 Our previous @samp{my-hello} needs some adjustments though:
607
608 @lisp
609 (define-module (my-hello)
610 #:use-module (guix licenses)
611 #:use-module (guix packages)
612 #:use-module (guix build-system gnu)
613 #:use-module (guix download))
614
615 (define-public my-hello
616 (package
617 (name "my-hello")
618 (version "2.10")
619 (source (origin
620 (method url-fetch)
621 (uri (string-append "mirror://gnu/hello/hello-" version
622 ".tar.gz"))
623 (sha256
624 (base32
625 "0ssi1wpaf7plaswqqjwigppsg5fyh99vdlb9kzl7c9lng89ndq1i"))))
626 (build-system gnu-build-system)
627 (synopsis "Hello, Guix world: An example custom Guix package")
628 (description
629 "GNU Hello prints the message \"Hello, world!\" and then exits. It
630 serves as an example of standard GNU coding practices. As such, it supports
631 command-line arguments, multiple languages, and so on.")
632 (home-page "https://www.gnu.org/software/hello/")
633 (license gpl3+)))
634 @end lisp
635
636 Note that we have assigned the package value to an exported variable name with
637 @code{define-public}. This is effectively assigning the package to the @code{my-hello}
638 variable so that it can be referenced, among other as dependency of other
639 packages.
640
641 If you use @code{guix package --install-from-file=my-hello.scm} on the above file, it
642 will fail because the last expression, @code{define-public}, does not return a
643 package. If you want to use @code{define-public} in this use-case nonetheless, make
644 sure the file ends with an evaluation of @code{my-hello}:
645
646 @lisp
647 ; ...
648 (define-public my-hello
649 ; ...
650 )
651
652 my-hello
653 @end lisp
654
655 This last example is not very typical.
656
657 Now @samp{my-hello} should be part of the package collection like all other official
658 packages. You can verify this with:
659
660 @example
661 $ guix package --show=my-hello
662 @end example
663
664 @node Guix channels
665 @subsubsection Guix channels
666
667 Guix 0.16 features channels, which is very similar to @samp{GUIX_PACKAGE_PATH} but
668 provides better integration and provenance tracking. Channels are not
669 necessarily local, they can be maintained as a public Git repository for
670 instance. Of course, several channels can be used at the same time.
671
672 @xref{Channels,,, guix, GNU Guix Reference Manual} for setup details.
673
674 @node Direct checkout hacking
675 @subsubsection Direct checkout hacking
676
677 Working directly on the Guix project is recommended: it reduces the friction
678 when the time comes to submit your changes upstream to let the community benefit
679 from your hard work!
680
681 Unlike most software distributions, the Guix repository holds in one place both
682 the tooling (including the package manager) and the package definitions. This
683 choice was made so that it would give developers the flexibility to modify the
684 API without breakage by updating all packages at the same time. This reduces
685 development inertia.
686
687 Check out the official @uref{https://git-scm.com/, Git} repository:
688
689 @example
690 $ git clone https://git.savannah.gnu.org/git/guix.git
691 @end example
692
693 In the rest of this article, we use @samp{$GUIX_CHECKOUT} to refer to the location of
694 the checkout.
695
696
697 Follow the instructions in the manual (@pxref{Contributing,,, guix, GNU Guix
698 Reference Manual}) to set up the repository environment.
699
700 Once ready, you should be able to use the package definitions from the
701 repository environment.
702
703 Feel free to edit package definitions found in @samp{$GUIX_CHECKOUT/gnu/packages}.
704
705 The @samp{$GUIX_CHECKOUT/pre-inst-env} script lets you use @samp{guix} over the package
706 collection of the repository (@pxref{Running Guix Before It Is
707 Installed,,, guix, GNU Guix Reference Manual}).
708
709 @itemize
710 @item
711 Search packages, such as Ruby:
712
713 @example
714 $ cd $GUIX_CHECKOUT
715 $ ./pre-inst-env guix package --list-available=ruby
716 ruby 1.8.7-p374 out gnu/packages/ruby.scm:119:2
717 ruby 2.1.6 out gnu/packages/ruby.scm:91:2
718 ruby 2.2.2 out gnu/packages/ruby.scm:39:2
719 @end example
720
721 @item
722 Build a package, here Ruby version 2.1:
723
724 @example
725 $ ./pre-inst-env guix build --keep-failed ruby@@2.1
726 /gnu/store/c13v73jxmj2nir2xjqaz5259zywsa9zi-ruby-2.1.6
727 @end example
728
729 @item
730 Install it to your user profile:
731
732 @example
733 $ ./pre-inst-env guix package --install ruby@@2.1
734 @end example
735
736 @item
737 Check for common mistakes:
738
739 @example
740 $ ./pre-inst-env guix lint ruby@@2.1
741 @end example
742 @end itemize
743
744 Guix strives at maintaining a high packaging standard; when contributing to the
745 Guix project, remember to
746
747 @itemize
748 @item
749 follow the coding style (@pxref{Coding Style,,, guix, GNU Guix Reference Manual}),
750 @item
751 and review the check list from the manual (@pxref{Submitting Patches,,, guix, GNU Guix Reference Manual}).
752 @end itemize
753
754 Once you are happy with the result, you are welcome to send your contribution to
755 make it part of Guix. This process is also detailed in the manual. (@pxref{Contributing,,, guix, GNU Guix Reference Manual})
756
757
758 It's a community effort so the more join in, the better Guix becomes!
759
760 @node Extended example
761 @subsection Extended example
762
763 The above ``Hello World'' example is as simple as it goes. Packages can be more
764 complex than that and Guix can handle more advanced scenarios. Let's look at
765 another, more sophisticated package (slightly modified from the source):
766
767 @lisp
768 (define-module (gnu packages version-control)
769 #:use-module ((guix licenses) #:prefix license:)
770 #:use-module (guix utils)
771 #:use-module (guix packages)
772 #:use-module (guix git-download)
773 #:use-module (guix build-system cmake)
774 #:use-module (gnu packages ssh)
775 #:use-module (gnu packages web)
776 #:use-module (gnu packages pkg-config)
777 #:use-module (gnu packages python)
778 #:use-module (gnu packages compression)
779 #:use-module (gnu packages tls))
780
781 (define-public my-libgit2
782 (let ((commit "e98d0a37c93574d2c6107bf7f31140b548c6a7bf")
783 (revision "1"))
784 (package
785 (name "my-libgit2")
786 (version (git-version "0.26.6" revision commit))
787 (source (origin
788 (method git-fetch)
789 (uri (git-reference
790 (url "https://github.com/libgit2/libgit2/")
791 (commit commit)))
792 (file-name (git-file-name name version))
793 (sha256
794 (base32
795 "17pjvprmdrx4h6bb1hhc98w9qi6ki7yl57f090n9kbhswxqfs7s3"))
796 (patches (search-patches "libgit2-mtime-0.patch"))
797 (modules '((guix build utils)))
798 ;; Remove bundled software.
799 (snippet '(delete-file-recursively "deps"))))
800 (build-system cmake-build-system)
801 (outputs '("out" "debug"))
802 (arguments
803 `(#:tests? #true ; Run the test suite (this is the default)
804 #:configure-flags '("-DUSE_SHA1DC=ON") ; SHA-1 collision detection
805 #:phases
806 (modify-phases %standard-phases
807 (add-after 'unpack 'fix-hardcoded-paths
808 (lambda _
809 (substitute* "tests/repo/init.c"
810 (("#!/bin/sh") (string-append "#!" (which "sh"))))
811 (substitute* "tests/clar/fs.h"
812 (("/bin/cp") (which "cp"))
813 (("/bin/rm") (which "rm")))))
814 ;; Run checks more verbosely.
815 (replace 'check
816 (lambda _ (invoke "./libgit2_clar" "-v" "-Q")))
817 (add-after 'unpack 'make-files-writable-for-tests
818 (lambda _ (for-each make-file-writable (find-files "." ".*")))))))
819 (inputs
820 (list libssh2 http-parser python-wrapper))
821 (native-inputs
822 (list pkg-config))
823 (propagated-inputs
824 ;; These two libraries are in 'Requires.private' in libgit2.pc.
825 (list openssl zlib))
826 (home-page "https://libgit2.github.com/")
827 (synopsis "Library providing Git core methods")
828 (description
829 "Libgit2 is a portable, pure C implementation of the Git core methods
830 provided as a re-entrant linkable library with a solid API, allowing you to
831 write native speed custom Git applications in any language with bindings.")
832 ;; GPLv2 with linking exception
833 (license license:gpl2))))
834 @end lisp
835
836 (In those cases were you only want to tweak a few fields from a package
837 definition, you should rely on inheritance instead of copy-pasting everything.
838 See below.)
839
840 Let's discuss those fields in depth.
841
842 @subsubsection @code{git-fetch} method
843
844 Unlike the @code{url-fetch} method, @code{git-fetch} expects a @code{git-reference} which takes
845 a Git repository and a commit. The commit can be any Git reference such as
846 tags, so if the @code{version} is tagged, then it can be used directly. Sometimes
847 the tag is prefixed with a @code{v}, in which case you'd use @code{(commit (string-append
848 "v" version))}.
849
850 To ensure that the source code from the Git repository is stored in a
851 directory with a descriptive name, we use @code{(file-name (git-file-name name
852 version))}.
853
854 The @code{git-version} procedure can be used to derive the
855 version when packaging programs for a specific commit, following the
856 Guix contributor guidelines (@pxref{Version Numbers,,, guix, GNU Guix
857 Reference Manual}).
858
859 How does one obtain the @code{sha256} hash that's in there, you ask? By
860 invoking @command{guix hash} on a checkout of the desired commit, along
861 these lines:
862
863 @example
864 git clone https://github.com/libgit2/libgit2/
865 cd libgit2
866 git checkout v0.26.6
867 guix hash -rx .
868 @end example
869
870 @command{guix hash -rx} computes a SHA256 hash over the whole directory,
871 excluding the @file{.git} sub-directory (@pxref{Invoking guix hash,,,
872 guix, GNU Guix Reference Manual}).
873
874 In the future, @command{guix download} will hopefully be able to do
875 these steps for you, just like it does for regular downloads.
876
877 @subsubsection Snippets
878
879 Snippets are quoted (i.e. non-evaluated) Scheme code that are a means of patching
880 the source. They are a Guix-y alternative to the traditional @file{.patch} files.
881 Because of the quote, the code in only evaluated when passed to the Guix daemon
882 for building. There can be as many snippets as needed.
883
884 Snippets might need additional Guile modules which can be imported from the
885 @code{modules} field.
886
887 @subsubsection Inputs
888
889 There are 3 different input types. In short:
890
891 @table @asis
892 @item native-inputs
893 Required for building but not runtime -- installing a package
894 through a substitute won't install these inputs.
895 @item inputs
896 Installed in the store but not in the profile, as well as being
897 present at build time.
898 @item propagated-inputs
899 Installed in the store and in the profile, as well as
900 being present at build time.
901 @end table
902
903 @xref{Package Reference,,, guix, GNU Guix Reference Manual} for more details.
904
905 The distinction between the various inputs is important: if a dependency can be
906 handled as an @emph{input} instead of a @emph{propagated input}, it should be done so, or
907 else it ``pollutes'' the user profile for no good reason.
908
909 For instance, a user installing a graphical program that depends on a
910 command line tool might only be interested in the graphical part, so there is no
911 need to force the command line tool into the user profile. The dependency is a
912 concern to the package, not to the user. @emph{Inputs} make it possible to handle
913 dependencies without bugging the user by adding undesired executable files (or
914 libraries) to their profile.
915
916 Same goes for @emph{native-inputs}: once the program is installed, build-time
917 dependencies can be safely garbage-collected.
918 It also matters when a substitute is available, in which case only the @emph{inputs}
919 and @emph{propagated inputs} will be fetched: the @emph{native inputs} are not required to
920 install a package from a substitute.
921
922 @quotation Note
923 You may see here and there snippets where package inputs are written
924 quite differently, like so:
925
926 @lisp
927 ;; The "old style" for inputs.
928 (inputs
929 `(("libssh2" ,libssh2)
930 ("http-parser" ,http-parser)
931 ("python" ,python-wrapper)))
932 @end lisp
933
934 This is the ``old style'', where each input in the list is explicitly
935 given a label (a string). It is still supported but we recommend using
936 the style above instead. @xref{package Reference,,, guix, GNU Guix
937 Reference Manual}, for more info.
938 @end quotation
939
940 @subsubsection Outputs
941
942 Just like how a package can have multiple inputs, it can also produce multiple
943 outputs.
944
945 Each output corresponds to a separate directory in the store.
946
947 The user can choose which output to install; this is useful to save space or
948 to avoid polluting the user profile with unwanted executables or libraries.
949
950 Output separation is optional. When the @code{outputs} field is left out, the
951 default and only output (the complete package) is referred to as @code{"out"}.
952
953 Typical separate output names include @code{debug} and @code{doc}.
954
955 It's advised to separate outputs only when you've shown it's worth it: if the
956 output size is significant (compare with @code{guix size}) or in case the package is
957 modular.
958
959 @subsubsection Build system arguments
960
961 The @code{arguments} is a keyword-value list used to configure the build process.
962
963 The simplest argument @code{#:tests?} can be used to disable the test suite when
964 building the package. This is mostly useful when the package does not feature
965 any test suite. It's strongly recommended to keep the test suite on if there is
966 one.
967
968 Another common argument is @code{:make-flags}, which specifies a list of flags to
969 append when running make, as you would from the command line. For instance, the
970 following flags
971
972 @lisp
973 #:make-flags (list (string-append "prefix=" (assoc-ref %outputs "out"))
974 "CC=gcc")
975 @end lisp
976
977 translate into
978
979 @example
980 $ make CC=gcc prefix=/gnu/store/...-<out>
981 @end example
982
983 This sets the C compiler to @code{gcc} and the @code{prefix} variable (the installation
984 directory in Make parlance) to @code{(assoc-ref %outputs "out")}, which is a build-stage
985 global variable pointing to the destination directory in the store (something like
986 @file{/gnu/store/...-my-libgit2-20180408}).
987
988 Similarly, it's possible to set the configure flags:
989
990 @lisp
991 #:configure-flags '("-DUSE_SHA1DC=ON")
992 @end lisp
993
994 The @code{%build-inputs} variable is also generated in scope. It's an association
995 table that maps the input names to their store directories.
996
997 The @code{phases} keyword lists the sequential steps of the build system. Typically
998 phases include @code{unpack}, @code{configure}, @code{build}, @code{install} and @code{check}. To know
999 more about those phases, you need to work out the appropriate build system
1000 definition in @samp{$GUIX_CHECKOUT/guix/build/gnu-build-system.scm}:
1001
1002 @lisp
1003 (define %standard-phases
1004 ;; Standard build phases, as a list of symbol/procedure pairs.
1005 (let-syntax ((phases (syntax-rules ()
1006 ((_ p ...) `((p . ,p) ...)))))
1007 (phases set-SOURCE-DATE-EPOCH set-paths install-locale unpack
1008 bootstrap
1009 patch-usr-bin-file
1010 patch-source-shebangs configure patch-generated-file-shebangs
1011 build check install
1012 patch-shebangs strip
1013 validate-runpath
1014 validate-documentation-location
1015 delete-info-dir-file
1016 patch-dot-desktop-files
1017 install-license-files
1018 reset-gzip-timestamps
1019 compress-documentation)))
1020 @end lisp
1021
1022 Or from the REPL:
1023
1024 @lisp
1025 (add-to-load-path "/path/to/guix/checkout")
1026 ,use (guix build gnu-build-system)
1027 (map first %standard-phases)
1028 @result{} (set-SOURCE-DATE-EPOCH set-paths install-locale unpack bootstrap patch-usr-bin-file patch-source-shebangs configure patch-generated-file-shebangs build check install patch-shebangs strip validate-runpath validate-documentation-location delete-info-dir-file patch-dot-desktop-files install-license-files reset-gzip-timestamps compress-documentation)
1029 @end lisp
1030
1031 If you want to know more about what happens during those phases, consult the
1032 associated procedures.
1033
1034 For instance, as of this writing the definition of @code{unpack} for the GNU build
1035 system is:
1036
1037 @lisp
1038 (define* (unpack #:key source #:allow-other-keys)
1039 "Unpack SOURCE in the working directory, and change directory within the
1040 source. When SOURCE is a directory, copy it in a sub-directory of the current
1041 working directory."
1042 (if (file-is-directory? source)
1043 (begin
1044 (mkdir "source")
1045 (chdir "source")
1046
1047 ;; Preserve timestamps (set to the Epoch) on the copied tree so that
1048 ;; things work deterministically.
1049 (copy-recursively source "."
1050 #:keep-mtime? #true))
1051 (begin
1052 (if (string-suffix? ".zip" source)
1053 (invoke "unzip" source)
1054 (invoke "tar" "xvf" source))
1055 (chdir (first-subdirectory "."))))
1056 #true)
1057 @end lisp
1058
1059 Note the @code{chdir} call: it changes the working directory to where the source was
1060 unpacked.
1061 Thus every phase following the @code{unpack} will use the source as a working
1062 directory, which is why we can directly work on the source files.
1063 That is to say, unless a later phase changes the working directory to something
1064 else.
1065
1066 We modify the list of @code{%standard-phases} of the build system with the
1067 @code{modify-phases} macro as per the list of specified modifications, which may have
1068 the following forms:
1069
1070 @itemize
1071 @item
1072 @code{(add-before @var{phase} @var{new-phase} @var{procedure})}: Run @var{procedure} named @var{new-phase} before @var{phase}.
1073 @item
1074 @code{(add-after @var{phase} @var{new-phase} @var{procedure})}: Same, but afterwards.
1075 @item
1076 @code{(replace @var{phase} @var{procedure})}.
1077 @item
1078 @code{(delete @var{phase})}.
1079 @end itemize
1080
1081 The @var{procedure} supports the keyword arguments @code{inputs} and @code{outputs}. Each
1082 input (whether @emph{native}, @emph{propagated} or not) and output directory is referenced
1083 by their name in those variables. Thus @code{(assoc-ref outputs "out")} is the store
1084 directory of the main output of the package. A phase procedure may look like
1085 this:
1086
1087 @lisp
1088 (lambda* (#:key inputs outputs #:allow-other-keys)
1089 (let ((bash-directory (assoc-ref inputs "bash"))
1090 (output-directory (assoc-ref outputs "out"))
1091 (doc-directory (assoc-ref outputs "doc")))
1092 ;; ...
1093 #true))
1094 @end lisp
1095
1096 The procedure must return @code{#true} on success. It's brittle to rely on the return
1097 value of the last expression used to tweak the phase because there is no
1098 guarantee it would be a @code{#true}. Hence the trailing @code{#true} to ensure the right value
1099 is returned on success.
1100
1101 @subsubsection Code staging
1102
1103 The astute reader may have noticed the quasi-quote and comma syntax in the
1104 argument field. Indeed, the build code in the package declaration should not be
1105 evaluated on the client side, but only when passed to the Guix daemon. This
1106 mechanism of passing code around two running processes is called @uref{https://arxiv.org/abs/1709.00833, code staging}.
1107
1108 @subsubsection Utility functions
1109
1110 When customizing @code{phases}, we often need to write code that mimics the
1111 equivalent system invocations (@code{make}, @code{mkdir}, @code{cp}, etc.)@: commonly used during
1112 regular ``Unix-style'' installations.
1113
1114 Some like @code{chmod} are native to Guile.
1115 @xref{,,, guile, Guile reference manual} for a complete list.
1116
1117 Guix provides additional helper functions which prove especially handy in the
1118 context of package management.
1119
1120 Some of those functions can be found in
1121 @samp{$GUIX_CHECKOUT/guix/guix/build/utils.scm}. Most of them mirror the behaviour
1122 of the traditional Unix system commands:
1123
1124 @table @code
1125 @item which
1126 Like the @samp{which} system command.
1127 @item find-files
1128 Akin to the @samp{find} system command.
1129 @item mkdir-p
1130 Like @samp{mkdir -p}, which creates all parents as needed.
1131 @item install-file
1132 Similar to @samp{install} when installing a file to a (possibly
1133 non-existing) directory. Guile has @code{copy-file} which works
1134 like @samp{cp}.
1135 @item copy-recursively
1136 Like @samp{cp -r}.
1137 @item delete-file-recursively
1138 Like @samp{rm -rf}.
1139 @item invoke
1140 Run an executable. This should be used instead of @code{system*}.
1141 @item with-directory-excursion
1142 Run the body in a different working directory,
1143 then restore the previous working directory.
1144 @item substitute*
1145 A ``@command{sed}-like'' function.
1146 @end table
1147
1148 @xref{Build Utilities,,, guix, GNU Guix Reference Manual}, for more
1149 information on these utilities.
1150
1151 @subsubsection Module prefix
1152
1153 The license in our last example needs a prefix: this is because of how the
1154 @code{license} module was imported in the package, as @code{#:use-module ((guix licenses)
1155 #:prefix license:)}. The Guile module import mechanism
1156 (@pxref{Using Guile Modules,,, guile, Guile reference manual})
1157 gives the user full control over namespacing: this is needed to avoid
1158 clashes between, say, the
1159 @samp{zlib} variable from @samp{licenses.scm} (a @emph{license} value) and the @samp{zlib} variable
1160 from @samp{compression.scm} (a @emph{package} value).
1161
1162 @node Other build systems
1163 @subsection Other build systems
1164
1165 What we've seen so far covers the majority of packages using a build system
1166 other than the @code{trivial-build-system}. The latter does not automate anything
1167 and leaves you to build everything manually. This can be more demanding and we
1168 won't cover it here for now, but thankfully it is rarely necessary to fall back
1169 on this system.
1170
1171 For the other build systems, such as ASDF, Emacs, Perl, Ruby and many more, the
1172 process is very similar to the GNU build system except for a few specialized
1173 arguments.
1174
1175 @xref{Build Systems,,, guix, GNU Guix Reference Manual}, for more
1176 information on build systems, or check the source code in the
1177 @samp{$GUIX_CHECKOUT/guix/build} and
1178 @samp{$GUIX_CHECKOUT/guix/build-system} directories.
1179
1180 @node Programmable and automated package definition
1181 @subsection Programmable and automated package definition
1182
1183 We can't repeat it enough: having a full-fledged programming language at hand
1184 empowers us in ways that reach far beyond traditional package management.
1185
1186 Let's illustrate this with some awesome features of Guix!
1187
1188 @node Recursive importers
1189 @subsubsection Recursive importers
1190
1191 You might find some build systems good enough that there is little to do at all
1192 to write a package, to the point that it becomes repetitive and tedious after a
1193 while. A @emph{raison d'être} of computers is to replace human beings at those
1194 boring tasks. So let's tell Guix to do this for us and create the package
1195 definition of an R package from CRAN (the output is trimmed for conciseness):
1196
1197 @example
1198 $ guix import cran --recursive walrus
1199
1200 (define-public r-mc2d
1201 ; ...
1202 (license gpl2+)))
1203
1204 (define-public r-jmvcore
1205 ; ...
1206 (license gpl2+)))
1207
1208 (define-public r-wrs2
1209 ; ...
1210 (license gpl3)))
1211
1212 (define-public r-walrus
1213 (package
1214 (name "r-walrus")
1215 (version "1.0.3")
1216 (source
1217 (origin
1218 (method url-fetch)
1219 (uri (cran-uri "walrus" version))
1220 (sha256
1221 (base32
1222 "1nk2glcvy4hyksl5ipq2mz8jy4fss90hx6cq98m3w96kzjni6jjj"))))
1223 (build-system r-build-system)
1224 (propagated-inputs
1225 `(("r-ggplot2" ,r-ggplot2)
1226 ("r-jmvcore" ,r-jmvcore)
1227 ("r-r6" ,r-r6)
1228 ("r-wrs2" ,r-wrs2)))
1229 (home-page "https://github.com/jamovi/walrus")
1230 (synopsis "Robust Statistical Methods")
1231 (description
1232 "This package provides a toolbox of common robust statistical
1233 tests, including robust descriptives, robust t-tests, and robust ANOVA.
1234 It is also available as a module for 'jamovi' (see
1235 <https://www.jamovi.org> for more information). Walrus is based on the
1236 WRS2 package by Patrick Mair, which is in turn based on the scripts and
1237 work of Rand Wilcox. These analyses are described in depth in the book
1238 'Introduction to Robust Estimation & Hypothesis Testing'.")
1239 (license gpl3)))
1240 @end example
1241
1242 The recursive importer won't import packages for which Guix already has package
1243 definitions, except for the very first.
1244
1245 Not all applications can be packaged this way, only those relying on a select
1246 number of supported systems. Read about the full list of importers in
1247 the guix import section of the manual
1248 (@pxref{Invoking guix import,,, guix, GNU Guix Reference Manual}).
1249
1250 @node Automatic update
1251 @subsubsection Automatic update
1252
1253 Guix can be smart enough to check for updates on systems it knows. It can
1254 report outdated package definitions with
1255
1256 @example
1257 $ guix refresh hello
1258 @end example
1259
1260 In most cases, updating a package to a newer version requires little more than
1261 changing the version number and the checksum. Guix can do that automatically as
1262 well:
1263
1264 @example
1265 $ guix refresh hello --update
1266 @end example
1267
1268 @node Inheritance
1269 @subsubsection Inheritance
1270
1271 If you've started browsing the existing package definitions, you might have
1272 noticed that a significant number of them have a @code{inherit} field:
1273
1274 @lisp
1275 (define-public adwaita-icon-theme
1276 (package (inherit gnome-icon-theme)
1277 (name "adwaita-icon-theme")
1278 (version "3.26.1")
1279 (source (origin
1280 (method url-fetch)
1281 (uri (string-append "mirror://gnome/sources/" name "/"
1282 (version-major+minor version) "/"
1283 name "-" version ".tar.xz"))
1284 (sha256
1285 (base32
1286 "17fpahgh5dyckgz7rwqvzgnhx53cx9kr2xw0szprc6bnqy977fi8"))))
1287 (native-inputs
1288 `(("gtk-encode-symbolic-svg" ,gtk+ "bin")))))
1289 @end lisp
1290
1291 All unspecified fields are inherited from the parent package. This is very
1292 convenient to create alternative packages, for instance with different source,
1293 version or compilation options.
1294
1295 @node Getting help
1296 @subsection Getting help
1297
1298 Sadly, some applications can be tough to package. Sometimes they need a patch to
1299 work with the non-standard file system hierarchy enforced by the store.
1300 Sometimes the tests won't run properly. (They can be skipped but this is not
1301 recommended.) Other times the resulting package won't be reproducible.
1302
1303 Should you be stuck, unable to figure out how to fix any sort of packaging
1304 issue, don't hesitate to ask the community for help.
1305
1306 See the @uref{https://www.gnu.org/software/guix/contact/, Guix homepage} for information on the mailing lists, IRC, etc.
1307
1308 @node Conclusion
1309 @subsection Conclusion
1310
1311 This tutorial was a showcase of the sophisticated package management that Guix
1312 boasts. At this point we have mostly restricted this introduction to the
1313 @code{gnu-build-system} which is a core abstraction layer on which more advanced
1314 abstractions are based.
1315
1316 Where do we go from here? Next we ought to dissect the innards of the build
1317 system by removing all abstractions, using the @code{trivial-build-system}: this
1318 should give us a thorough understanding of the process before investigating some
1319 more advanced packaging techniques and edge cases.
1320
1321 Other features worth exploring are the interactive editing and debugging
1322 capabilities of Guix provided by the Guile REPL@.
1323
1324 Those fancy features are completely optional and can wait; now is a good time
1325 to take a well-deserved break. With what we've introduced here you should be
1326 well armed to package lots of programs. You can get started right away and
1327 hopefully we will see your contributions soon!
1328
1329 @node References
1330 @subsection References
1331
1332 @itemize
1333 @item
1334 The @uref{https://www.gnu.org/software/guix/manual/en/html_node/Defining-Packages.html, package reference in the manual}
1335
1336 @item
1337 @uref{https://gitlab.com/pjotrp/guix-notes/blob/master/HACKING.org, Pjotr’s hacking guide to GNU Guix}
1338
1339 @item
1340 @uref{https://www.gnu.org/software/guix/guix-ghm-andreas-20130823.pdf, ``GNU Guix: Package without a scheme!''}, by Andreas Enge
1341 @end itemize
1342
1343 @c *********************************************************************
1344 @node System Configuration
1345 @chapter System Configuration
1346
1347 Guix offers a flexible language for declaratively configuring your Guix
1348 System. This flexibility can at times be overwhelming. The purpose of this
1349 chapter is to demonstrate some advanced configuration concepts.
1350
1351 @pxref{System Configuration,,, guix, GNU Guix Reference Manual} for a complete
1352 reference.
1353
1354 @menu
1355 * Auto-Login to a Specific TTY:: Automatically Login a User to a Specific TTY
1356 * Customizing the Kernel:: Creating and using a custom Linux kernel on Guix System.
1357 * Guix System Image API:: Customizing images to target specific platforms.
1358 * Connecting to Wireguard VPN:: Connecting to a Wireguard VPN.
1359 * Customizing a Window Manager:: Handle customization of a Window manager on Guix System.
1360 * Running Guix on a Linode Server:: Running Guix on a Linode Server
1361 * Setting up a bind mount:: Setting up a bind mount in the file-systems definition.
1362 * Getting substitutes from Tor:: Configuring Guix daemon to get substitutes through Tor.
1363 * Setting up NGINX with Lua:: Configuring NGINX web-server to load Lua modules.
1364 @end menu
1365
1366 @node Auto-Login to a Specific TTY
1367 @section Auto-Login to a Specific TTY
1368
1369 While the Guix manual explains auto-login one user to @emph{all} TTYs (
1370 @pxref{auto-login to TTY,,, guix, GNU Guix Reference Manual}), some
1371 might prefer a situation, in which one user is logged into one TTY with
1372 the other TTYs either configured to login different users or no one at
1373 all. Note that one can auto-login one user to any TTY, but it is
1374 usually advisable to avoid @code{tty1}, which, by default, is used to
1375 log warnings and errors.
1376
1377 Here is how one might set up auto login for one user to one tty:
1378
1379 @lisp
1380 (define (auto-login-to-tty config tty user)
1381 (if (string=? tty (mingetty-configuration-tty config))
1382 (mingetty-configuration
1383 (inherit config)
1384 (auto-login user))
1385 config))
1386
1387 (define %my-services
1388 (modify-services %base-services
1389 ;; @dots{}
1390 (mingetty-service-type config =>
1391 (auto-login-to-tty
1392 config "tty3" "alice"))))
1393
1394 (operating-system
1395 ;; @dots{}
1396 (services %my-services))
1397 @end lisp
1398
1399 One could also @code{compose} (@pxref{Higher-Order Functions,,, guile,
1400 The Guile Reference Manual}) @code{auto-login-to-tty} to login multiple
1401 users to multiple ttys.
1402
1403 Finally, here is a note of caution. Setting up auto login to a TTY,
1404 means that anyone can turn on your computer and run commands as your
1405 regular user.
1406 However, if you have an encrypted root partition, and thus already need
1407 to enter a passphrase when the system boots, auto-login might be a
1408 convenient option.
1409
1410
1411 @node Customizing the Kernel
1412 @section Customizing the Kernel
1413
1414 Guix is, at its core, a source based distribution with substitutes
1415 (@pxref{Substitutes,,, guix, GNU Guix Reference Manual}), and as such building
1416 packages from their source code is an expected part of regular package
1417 installations and upgrades. Given this starting point, it makes sense that
1418 efforts are made to reduce the amount of time spent compiling packages, and
1419 recent changes and upgrades to the building and distribution of substitutes
1420 continues to be a topic of discussion within Guix.
1421
1422 The kernel, while not requiring an overabundance of RAM to build, does take a
1423 rather long time on an average machine. The official kernel configuration, as
1424 is the case with many GNU/Linux distributions, errs on the side of
1425 inclusiveness, and this is really what causes the build to take such a long
1426 time when the kernel is built from source.
1427
1428 The Linux kernel, however, can also just be described as a regular old
1429 package, and as such can be customized just like any other package. The
1430 procedure is a little bit different, although this is primarily due to the
1431 nature of how the package definition is written.
1432
1433 The @code{linux-libre} kernel package definition is actually a procedure which
1434 creates a package.
1435
1436 @lisp
1437 (define* (make-linux-libre version hash supported-systems
1438 #:key
1439 ;; A function that takes an arch and a variant.
1440 ;; See kernel-config for an example.
1441 (extra-version #false)
1442 (configuration-file #false)
1443 (defconfig "defconfig")
1444 (extra-options %default-extra-linux-options)
1445 (patches (list %boot-logo-patch)))
1446 ...)
1447 @end lisp
1448
1449 The current @code{linux-libre} package is for the 5.1.x series, and is
1450 declared like this:
1451
1452 @lisp
1453 (define-public linux-libre
1454 (make-linux-libre %linux-libre-version
1455 %linux-libre-hash
1456 '("x86_64-linux" "i686-linux" "armhf-linux" "aarch64-linux")
1457 #:patches %linux-libre-5.1-patches
1458 #:configuration-file kernel-config))
1459 @end lisp
1460
1461 Any keys which are not assigned values inherit their default value from the
1462 @code{make-linux-libre} definition. When comparing the two snippets above,
1463 you may notice that the code comment in the first doesn't actually refer to
1464 the @code{#:extra-version} keyword; it is actually for
1465 @code{#:configuration-file}. Because of this, it is not actually easy to
1466 include a custom kernel configuration from the definition, but don't worry,
1467 there are other ways to work with what we do have.
1468
1469 There are two ways to create a kernel with a custom kernel configuration. The
1470 first is to provide a standard @file{.config} file during the build process by
1471 including an actual @file{.config} file as a native input to our custom
1472 kernel. The following is a snippet from the custom @code{'configure} phase of
1473 the @code{make-linux-libre} package definition:
1474
1475 @lisp
1476 (let ((build (assoc-ref %standard-phases 'build))
1477 (config (assoc-ref (or native-inputs inputs) "kconfig")))
1478
1479 ;; Use a custom kernel configuration file or a default
1480 ;; configuration file.
1481 (if config
1482 (begin
1483 (copy-file config ".config")
1484 (chmod ".config" #o666))
1485 (invoke "make" ,defconfig)))
1486 @end lisp
1487
1488 Below is a sample kernel package. The @code{linux-libre} package is nothing
1489 special and can be inherited from and have its fields overridden like any
1490 other package:
1491
1492 @lisp
1493 (define-public linux-libre/E2140
1494 (package
1495 (inherit linux-libre)
1496 (native-inputs
1497 `(("kconfig" ,(local-file "E2140.config"))
1498 ,@@(alist-delete "kconfig"
1499 (package-native-inputs linux-libre))))))
1500 @end lisp
1501
1502 In the same directory as the file defining @code{linux-libre-E2140} is a file
1503 named @file{E2140.config}, which is an actual kernel configuration file. The
1504 @code{defconfig} keyword of @code{make-linux-libre} is left blank here, so the
1505 only kernel configuration in the package is the one which was included in the
1506 @code{native-inputs} field.
1507
1508 The second way to create a custom kernel is to pass a new value to the
1509 @code{extra-options} keyword of the @code{make-linux-libre} procedure. The
1510 @code{extra-options} keyword works with another function defined right below
1511 it:
1512
1513 @lisp
1514 (define %default-extra-linux-options
1515 `(;; https://lists.gnu.org/archive/html/guix-devel/2014-04/msg00039.html
1516 ("CONFIG_DEVPTS_MULTIPLE_INSTANCES" . #true)
1517 ;; Modules required for initrd:
1518 ("CONFIG_NET_9P" . m)
1519 ("CONFIG_NET_9P_VIRTIO" . m)
1520 ("CONFIG_VIRTIO_BLK" . m)
1521 ("CONFIG_VIRTIO_NET" . m)
1522 ("CONFIG_VIRTIO_PCI" . m)
1523 ("CONFIG_VIRTIO_BALLOON" . m)
1524 ("CONFIG_VIRTIO_MMIO" . m)
1525 ("CONFIG_FUSE_FS" . m)
1526 ("CONFIG_CIFS" . m)
1527 ("CONFIG_9P_FS" . m)))
1528
1529 (define (config->string options)
1530 (string-join (map (match-lambda
1531 ((option . 'm)
1532 (string-append option "=m"))
1533 ((option . #true)
1534 (string-append option "=y"))
1535 ((option . #false)
1536 (string-append option "=n")))
1537 options)
1538 "\n"))
1539 @end lisp
1540
1541 And in the custom configure script from the `make-linux-libre` package:
1542
1543 @lisp
1544 ;; Appending works even when the option wasn't in the
1545 ;; file. The last one prevails if duplicated.
1546 (let ((port (open-file ".config" "a"))
1547 (extra-configuration ,(config->string extra-options)))
1548 (display extra-configuration port)
1549 (close-port port))
1550
1551 (invoke "make" "oldconfig")
1552 @end lisp
1553
1554 So by not providing a configuration-file the @file{.config} starts blank, and
1555 then we write into it the collection of flags that we want. Here's another
1556 custom kernel:
1557
1558 @lisp
1559 (define %macbook41-full-config
1560 (append %macbook41-config-options
1561 %file-systems
1562 %efi-support
1563 %emulation
1564 (@@@@ (gnu packages linux) %default-extra-linux-options)))
1565
1566 (define-public linux-libre-macbook41
1567 ;; XXX: Access the internal 'make-linux-libre' procedure, which is
1568 ;; private and unexported, and is liable to change in the future.
1569 ((@@@@ (gnu packages linux) make-linux-libre) (@@@@ (gnu packages linux) %linux-libre-version)
1570 (@@@@ (gnu packages linux) %linux-libre-hash)
1571 '("x86_64-linux")
1572 #:extra-version "macbook41"
1573 #:patches (@@@@ (gnu packages linux) %linux-libre-5.1-patches)
1574 #:extra-options %macbook41-config-options))
1575 @end lisp
1576
1577 In the above example @code{%file-systems} is a collection of flags enabling
1578 different file system support, @code{%efi-support} enables EFI support and
1579 @code{%emulation} enables a x86_64-linux machine to act in 32-bit mode also.
1580 @code{%default-extra-linux-options} are the ones quoted above, which had to be
1581 added in since they were replaced in the @code{extra-options} keyword.
1582
1583 This all sounds like it should be doable, but how does one even know which
1584 modules are required for a particular system? Two places that can be helpful
1585 in trying to answer this question is the
1586 @uref{https://wiki.gentoo.org/wiki/Handbook:AMD64/Installation/Kernel, Gentoo
1587 Handbook} and the
1588 @uref{https://www.kernel.org/doc/html/latest/admin-guide/README.html?highlight=localmodconfig,
1589 documentation from the kernel itself}. From the kernel documentation, it
1590 seems that @code{make localmodconfig} is the command we want.
1591
1592 In order to actually run @code{make localmodconfig} we first need to get and
1593 unpack the kernel source code:
1594
1595 @example shell
1596 tar xf $(guix build linux-libre --source)
1597 @end example
1598
1599 Once inside the directory containing the source code run @code{touch .config}
1600 to create an initial, empty @file{.config} to start with. @code{make
1601 localmodconfig} works by seeing what you already have in @file{.config} and
1602 letting you know what you're missing. If the file is blank then you're
1603 missing everything. The next step is to run:
1604
1605 @example shell
1606 guix environment linux-libre -- make localmodconfig
1607 @end example
1608
1609 and note the output. Do note that the @file{.config} file is still empty.
1610 The output generally contains two types of warnings. The first start with
1611 "WARNING" and can actually be ignored in our case. The second read:
1612
1613 @example shell
1614 module pcspkr did not have configs CONFIG_INPUT_PCSPKR
1615 @end example
1616
1617 For each of these lines, copy the @code{CONFIG_XXXX_XXXX} portion into the
1618 @file{.config} in the directory, and append @code{=m}, so in the end it looks
1619 like this:
1620
1621 @example shell
1622 CONFIG_INPUT_PCSPKR=m
1623 CONFIG_VIRTIO=m
1624 @end example
1625
1626 After copying all the configuration options, run @code{make localmodconfig}
1627 again to make sure that you don't have any output starting with ``module''.
1628 After all of these machine specific modules there are a couple more left that
1629 are also needed. @code{CONFIG_MODULES} is necessary so that you can build and
1630 load modules separately and not have everything built into the kernel.
1631 @code{CONFIG_BLK_DEV_SD} is required for reading from hard drives. It is
1632 possible that there are other modules which you will need.
1633
1634 This post does not aim to be a guide to configuring your own kernel however,
1635 so if you do decide to build a custom kernel you'll have to seek out other
1636 guides to create a kernel which is just right for your needs.
1637
1638 The second way to setup the kernel configuration makes more use of Guix's
1639 features and allows you to share configuration segments between different
1640 kernels. For example, all machines using EFI to boot have a number of EFI
1641 configuration flags that they need. It is likely that all the kernels will
1642 share a list of file systems to support. By using variables it is easier to
1643 see at a glance what features are enabled and to make sure you don't have
1644 features in one kernel but missing in another.
1645
1646 Left undiscussed however, is Guix's initrd and its customization. It is
1647 likely that you'll need to modify the initrd on a machine using a custom
1648 kernel, since certain modules which are expected to be built may not be
1649 available for inclusion into the initrd.
1650
1651 @node Guix System Image API
1652 @section Guix System Image API
1653
1654 Historically, Guix System is centered around an @code{operating-system}
1655 structure. This structure contains various fields ranging from the
1656 bootloader and kernel declaration to the services to install.
1657
1658 Depending on the target machine, that can go from a standard
1659 @code{x86_64} machine to a small ARM single board computer such as the
1660 Pine64, the image constraints can vary a lot. The hardware
1661 manufacturers will impose different image formats with various partition
1662 sizes and offsets.
1663
1664 To create images suitable for all those machines, a new abstraction is
1665 necessary: that's the goal of the @code{image} record. This record
1666 contains all the required information to be transformed into a
1667 standalone image, that can be directly booted on any target machine.
1668
1669 @lisp
1670 (define-record-type* <image>
1671 image make-image
1672 image?
1673 (name image-name ;symbol
1674 (default #f))
1675 (format image-format) ;symbol
1676 (target image-target
1677 (default #f))
1678 (size image-size ;size in bytes as integer
1679 (default 'guess))
1680 (operating-system image-operating-system ;<operating-system>
1681 (default #f))
1682 (partitions image-partitions ;list of <partition>
1683 (default '()))
1684 (compression? image-compression? ;boolean
1685 (default #t))
1686 (volatile-root? image-volatile-root? ;boolean
1687 (default #t))
1688 (substitutable? image-substitutable? ;boolean
1689 (default #t)))
1690 @end lisp
1691
1692 This record contains the operating-system to instantiate. The
1693 @code{format} field defines the image type and can be @code{efi-raw},
1694 @code{qcow2} or @code{iso9660} for instance. In the future, it could be
1695 extended to @code{docker} or other image types.
1696
1697 A new directory in the Guix sources is dedicated to images definition. For now
1698 there are four files:
1699
1700 @itemize @bullet
1701 @item @file{gnu/system/images/hurd.scm}
1702 @item @file{gnu/system/images/pine64.scm}
1703 @item @file{gnu/system/images/novena.scm}
1704 @item @file{gnu/system/images/pinebook-pro.scm}
1705 @end itemize
1706
1707 Let's have a look to @file{pine64.scm}. It contains the
1708 @code{pine64-barebones-os} variable which is a minimal definition of an
1709 operating-system dedicated to the @b{Pine A64 LTS} board.
1710
1711 @lisp
1712 (define pine64-barebones-os
1713 (operating-system
1714 (host-name "vignemale")
1715 (timezone "Europe/Paris")
1716 (locale "en_US.utf8")
1717 (bootloader (bootloader-configuration
1718 (bootloader u-boot-pine64-lts-bootloader)
1719 (targets '("/dev/vda"))))
1720 (initrd-modules '())
1721 (kernel linux-libre-arm64-generic)
1722 (file-systems (cons (file-system
1723 (device (file-system-label "my-root"))
1724 (mount-point "/")
1725 (type "ext4"))
1726 %base-file-systems))
1727 (services (cons (service agetty-service-type
1728 (agetty-configuration
1729 (extra-options '("-L")) ; no carrier detect
1730 (baud-rate "115200")
1731 (term "vt100")
1732 (tty "ttyS0")))
1733 %base-services))))
1734 @end lisp
1735
1736 The @code{kernel} and @code{bootloader} fields are pointing to packages
1737 dedicated to this board.
1738
1739 Right below, the @code{pine64-image-type} variable is also defined.
1740
1741 @lisp
1742 (define pine64-image-type
1743 (image-type
1744 (name 'pine64-raw)
1745 (constructor (cut image-with-os arm64-disk-image <>))))
1746 @end lisp
1747
1748 It's using a record we haven't talked about yet, the @code{image-type} record,
1749 defined this way:
1750
1751 @lisp
1752 (define-record-type* <image-type>
1753 image-type make-image-type
1754 image-type?
1755 (name image-type-name) ;symbol
1756 (constructor image-type-constructor)) ;<operating-system> -> <image>
1757 @end lisp
1758
1759 The main purpose of this record is to associate a name to a procedure
1760 transforming an @code{operating-system} to an image. To understand why
1761 it is necessary, let's have a look to the command producing an image
1762 from an @code{operating-system} configuration file:
1763
1764 @example
1765 guix system image my-os.scm
1766 @end example
1767
1768 This command expects an @code{operating-system} configuration but how
1769 should we indicate that we want an image targeting a Pine64 board? We
1770 need to provide an extra information, the @code{image-type}, by passing
1771 the @code{--image-type} or @code{-t} flag, this way:
1772
1773 @example
1774 guix system image --image-type=pine64-raw my-os.scm
1775 @end example
1776
1777 This @code{image-type} parameter points to the @code{pine64-image-type}
1778 defined above. Hence, the @code{operating-system} declared in
1779 @code{my-os.scm} will be applied the @code{(cut image-with-os
1780 arm64-disk-image <>)} procedure to turn it into an image.
1781
1782 The resulting image looks like:
1783
1784 @lisp
1785 (image
1786 (format 'disk-image)
1787 (target "aarch64-linux-gnu")
1788 (operating-system my-os)
1789 (partitions
1790 (list (partition
1791 (inherit root-partition)
1792 (offset root-offset)))))
1793 @end lisp
1794
1795 which is the aggregation of the @code{operating-system} defined in
1796 @code{my-os.scm} to the @code{arm64-disk-image} record.
1797
1798 But enough Scheme madness. What does this image API bring to the Guix user?
1799
1800 One can run:
1801
1802 @example
1803 mathieu@@cervin:~$ guix system --list-image-types
1804 The available image types are:
1805
1806 - pinebook-pro-raw
1807 - pine64-raw
1808 - novena-raw
1809 - hurd-raw
1810 - hurd-qcow2
1811 - qcow2
1812 - uncompressed-iso9660
1813 - efi-raw
1814 - arm64-raw
1815 - arm32-raw
1816 - iso9660
1817 @end example
1818
1819 and by writing an @code{operating-system} file based on
1820 @code{pine64-barebones-os}, you can customize your image to your
1821 preferences in a file (@file{my-pine-os.scm}) like this:
1822
1823 @lisp
1824 (use-modules (gnu services linux)
1825 (gnu system images pine64))
1826
1827 (let ((base-os pine64-barebones-os))
1828 (operating-system
1829 (inherit base-os)
1830 (timezone "America/Indiana/Indianapolis")
1831 (services
1832 (cons
1833 (service earlyoom-service-type
1834 (earlyoom-configuration
1835 (prefer-regexp "icecat|chromium")))
1836 (operating-system-user-services base-os)))))
1837 @end lisp
1838
1839 run:
1840
1841 @example
1842 guix system image --image-type=pine64-raw my-pine-os.scm
1843 @end example
1844
1845 or,
1846
1847 @example
1848 guix system image --image-type=hurd-raw my-hurd-os.scm
1849 @end example
1850
1851 to get an image that can be written directly to a hard drive and booted
1852 from.
1853
1854 Without changing anything to @code{my-hurd-os.scm}, calling:
1855
1856 @example
1857 guix system image --image-type=hurd-qcow2 my-hurd-os.scm
1858 @end example
1859
1860 will instead produce a Hurd QEMU image.
1861
1862 @node Connecting to Wireguard VPN
1863 @section Connecting to Wireguard VPN
1864
1865 To connect to a Wireguard VPN server you need the kernel module to be
1866 loaded in memory and a package providing networking tools that support
1867 it (e.g. @code{wireguard-tools} or @code{network-manager}).
1868
1869 Here is a configuration example for Linux-Libre < 5.6, where the module
1870 is out of tree and need to be loaded manually---following revisions of
1871 the kernel have it built-in and so don't need such configuration:
1872
1873 @lisp
1874 (use-modules (gnu))
1875 (use-service-modules desktop)
1876 (use-package-modules vpn)
1877
1878 (operating-system
1879 ;; …
1880 (services (cons (simple-service 'wireguard-module
1881 kernel-module-loader-service-type
1882 '("wireguard"))
1883 %desktop-services))
1884 (packages (cons wireguard-tools %base-packages))
1885 (kernel-loadable-modules (list wireguard-linux-compat)))
1886 @end lisp
1887
1888 After reconfiguring and restarting your system you can either use
1889 Wireguard tools or NetworkManager to connect to a VPN server.
1890
1891 @subsection Using Wireguard tools
1892
1893 To test your Wireguard setup it is convenient to use @command{wg-quick}.
1894 Just give it a configuration file @command{wg-quick up ./wg0.conf}; or
1895 put that file in @file{/etc/wireguard} and run @command{wg-quick up wg0}
1896 instead.
1897
1898 @quotation Note
1899 Be warned that the author described this command as a: “[…] very quick
1900 and dirty bash script […]”.
1901 @end quotation
1902
1903 @subsection Using NetworkManager
1904
1905 Thanks to NetworkManager support for Wireguard we can connect to our VPN
1906 using @command{nmcli} command. Up to this point this guide assumes that
1907 you're using Network Manager service provided by
1908 @code{%desktop-services}. Ortherwise you need to adjust your services
1909 list to load @code{network-manager-service-type} and reconfigure your
1910 Guix system.
1911
1912 To import your VPN configuration execute nmcli import command:
1913
1914 @example shell
1915 # nmcli connection import type wireguard file wg0.conf
1916 Connection 'wg0' (edbee261-aa5a-42db-b032-6c7757c60fde) successfully added
1917 @end example
1918
1919 This will create a configuration file in
1920 @file{/etc/NetworkManager/wg0.nmconnection}. Next connect to the
1921 Wireguard server:
1922
1923 @example shell
1924 $ nmcli connection up wg0
1925 Connection successfully activated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/6)
1926 @end example
1927
1928 By default NetworkManager will connect automatically on system boot. To
1929 change that behaviour you need to edit your config:
1930
1931 @example shell
1932 # nmcli connection modify wg0 connection.autoconnect no
1933 @end example
1934
1935 For more specific information about NetworkManager and wireguard
1936 @uref{https://blogs.gnome.org/thaller/2019/03/15/wireguard-in-networkmanager/,see
1937 this post by thaller}.
1938
1939 @node Customizing a Window Manager
1940 @section Customizing a Window Manager
1941 @cindex wm
1942
1943 @node StumpWM
1944 @subsection StumpWM
1945 @cindex stumpwm
1946
1947 You could install StumpWM with a Guix system by adding
1948 @code{stumpwm} and optionally @code{`(,stumpwm "lib")}
1949 packages to a system configuration file, e.g.@: @file{/etc/config.scm}.
1950
1951 An example configuration can look like this:
1952
1953 @lisp
1954 (use-modules (gnu))
1955 (use-package-modules wm)
1956
1957 (operating-system
1958 ;; …
1959 (packages (append (list sbcl stumpwm `(,stumpwm "lib"))
1960 %base-packages)))
1961 @end lisp
1962
1963 @cindex stumpwm fonts
1964 By default StumpWM uses X11 fonts, which could be small or pixelated on
1965 your system. You could fix this by installing StumpWM contrib Lisp
1966 module @code{sbcl-ttf-fonts}, adding it to Guix system packages:
1967
1968 @lisp
1969 (use-modules (gnu))
1970 (use-package-modules fonts wm)
1971
1972 (operating-system
1973 ;; …
1974 (packages (append (list sbcl stumpwm `(,stumpwm "lib"))
1975 sbcl-ttf-fonts font-dejavu %base-packages)))
1976 @end lisp
1977
1978 Then you need to add the following code to a StumpWM configuration file
1979 @file{~/.stumpwm.d/init.lisp}:
1980
1981 @lisp
1982 (require :ttf-fonts)
1983 (setf xft:*font-dirs* '("/run/current-system/profile/share/fonts/"))
1984 (setf clx-truetype:+font-cache-filename+ (concat (getenv "HOME") "/.fonts/font-cache.sexp"))
1985 (xft:cache-fonts)
1986 (set-font (make-instance 'xft:font :family "DejaVu Sans Mono" :subfamily "Book" :size 11))
1987 @end lisp
1988
1989 @node Session lock
1990 @subsection Session lock
1991 @cindex sessionlock
1992
1993 Depending on your environment, locking the screen of your session might come built in
1994 or it might be something you have to set up yourself. If you use a desktop environment
1995 like GNOME or KDE, it's usually built in. If you use a plain window manager like
1996 StumpWM or EXWM, you might have to set it up yourself.
1997
1998 @node Xorg
1999 @subsubsection Xorg
2000
2001 If you use Xorg, you can use the utility
2002 @uref{https://www.mankier.com/1/xss-lock, xss-lock} to lock the screen of your session.
2003 xss-lock is triggered by DPMS which since Xorg 1.8 is auto-detected and enabled if
2004 ACPI is also enabled at kernel runtime.
2005
2006 To use xss-lock, you can simple execute it and put it into the background before
2007 you start your window manager from e.g. your @file{~/.xsession}:
2008
2009 @example
2010 xss-lock -- slock &
2011 exec stumpwm
2012 @end example
2013
2014 In this example, xss-lock uses @code{slock} to do the actual locking of the screen when
2015 it determines it's appropriate, like when you suspend your device.
2016
2017 For slock to be allowed to be a screen locker for the graphical session, it needs to
2018 be made setuid-root so it can authenticate users, and it needs a PAM service. This
2019 can be achieved by adding the following service to your @file{config.scm}:
2020
2021 @lisp
2022 (screen-locker-service slock)
2023 @end lisp
2024
2025 If you manually lock your screen, e.g. by directly calling slock when you want to lock
2026 your screen but not suspend it, it's a good idea to notify xss-lock about this so no
2027 confusion occurs. This can be done by executing @code{xset s activate} immediately
2028 before you execute slock.
2029
2030 @node Running Guix on a Linode Server
2031 @section Running Guix on a Linode Server
2032 @cindex linode, Linode
2033
2034 To run Guix on a server hosted by @uref{https://www.linode.com, Linode},
2035 start with a recommended Debian server. We recommend using the default
2036 distro as a way to bootstrap Guix. Create your SSH keys.
2037
2038 @example
2039 ssh-keygen
2040 @end example
2041
2042 Be sure to add your SSH key for easy login to the remote server.
2043 This is trivially done via Linode's graphical interface for adding
2044 SSH keys. Go to your profile and click add SSH Key.
2045 Copy into it the output of:
2046
2047 @example
2048 cat ~/.ssh/<username>_rsa.pub
2049 @end example
2050
2051 Power the Linode down.
2052
2053 In the Linode's Storage tab, resize the Debian disk to be smaller.
2054 30 GB free space is recommended. Then click "Add a disk", and fill
2055 out the form with the following:
2056
2057 @itemize @bullet
2058 @item
2059 Label: "Guix"
2060
2061 @item
2062 Filesystem: ext4
2063
2064 @item
2065 Set it to the remaining size
2066 @end itemize
2067
2068 In the Configurations tab, press "Edit" on the default Debian profile.
2069 Under "Block Device Assignment" click "Add a Device". It should be
2070 @file{/dev/sdc} and you can select the "Guix" disk. Save Changes.
2071
2072 Now "Add a Configuration", with the following:
2073 @itemize @bullet
2074 @item
2075 Label: Guix
2076
2077 @item
2078 Kernel:GRUB 2 (it's at the bottom! This step is @b{IMPORTANT!})
2079
2080 @item
2081 Block device assignment:
2082
2083 @item
2084 @file{/dev/sda}: Guix
2085
2086 @item
2087 @file{/dev/sdb}: swap
2088
2089 @item
2090 Root device: @file{/dev/sda}
2091
2092 @item
2093 Turn off all the filesystem/boot helpers
2094 @end itemize
2095
2096 Now power it back up, booting with the Debian configuration. Once it's
2097 running, ssh to your server via @code{ssh
2098 root@@@var{<your-server-IP-here>}}. (You can find your server IP address in
2099 your Linode Summary section.) Now you can run the "install guix from
2100 @pxref{Binary Installation,,, guix, GNU Guix}" steps:
2101
2102 @example
2103 sudo apt-get install gpg
2104 wget https://sv.gnu.org/people/viewgpg.php?user_id=15145 -qO - | gpg --import -
2105 wget https://git.savannah.gnu.org/cgit/guix.git/plain/etc/guix-install.sh
2106 chmod +x guix-install.sh
2107 ./guix-install.sh
2108 guix pull
2109 @end example
2110
2111 Now it's time to write out a config for the server. The key information
2112 is below. Save the resulting file as @file{guix-config.scm}.
2113
2114 @lisp
2115 (use-modules (gnu)
2116 (guix modules))
2117 (use-service-modules networking
2118 ssh)
2119 (use-package-modules admin
2120 certs
2121 package-management
2122 ssh
2123 tls)
2124
2125 (operating-system
2126 (host-name "my-server")
2127 (timezone "America/New_York")
2128 (locale "en_US.UTF-8")
2129 ;; This goofy code will generate the grub.cfg
2130 ;; without installing the grub bootloader on disk.
2131 (bootloader (bootloader-configuration
2132 (bootloader
2133 (bootloader
2134 (inherit grub-bootloader)
2135 (installer #~(const #true))))))
2136 (file-systems (cons (file-system
2137 (device "/dev/sda")
2138 (mount-point "/")
2139 (type "ext4"))
2140 %base-file-systems))
2141
2142
2143 (swap-devices (list "/dev/sdb"))
2144
2145
2146 (initrd-modules (cons "virtio_scsi" ; Needed to find the disk
2147 %base-initrd-modules))
2148
2149 (users (cons (user-account
2150 (name "janedoe")
2151 (group "users")
2152 ;; Adding the account to the "wheel" group
2153 ;; makes it a sudoer.
2154 (supplementary-groups '("wheel"))
2155 (home-directory "/home/janedoe"))
2156 %base-user-accounts))
2157
2158 (packages (cons* nss-certs ;for HTTPS access
2159 openssh-sans-x
2160 %base-packages))
2161
2162 (services (cons*
2163 (service dhcp-client-service-type)
2164 (service openssh-service-type
2165 (openssh-configuration
2166 (openssh openssh-sans-x)
2167 (password-authentication? #false)
2168 (authorized-keys
2169 `(("janedoe" ,(local-file "janedoe_rsa.pub"))
2170 ("root" ,(local-file "janedoe_rsa.pub"))))))
2171 %base-services)))
2172 @end lisp
2173
2174 Replace the following fields in the above configuration:
2175 @lisp
2176 (host-name "my-server") ; replace with your server name
2177 ; if you chose a linode server outside the U.S., then
2178 ; use tzselect to find a correct timezone string
2179 (timezone "America/New_York") ; if needed replace timezone
2180 (name "janedoe") ; replace with your username
2181 ("janedoe" ,(local-file "janedoe_rsa.pub")) ; replace with your ssh key
2182 ("root" ,(local-file "janedoe_rsa.pub")) ; replace with your ssh key
2183 @end lisp
2184
2185 The last line in the above example lets you log into the server as root
2186 and set the initial root password (see the note at the end of this
2187 recipe about root login). After you have done this, you may
2188 delete that line from your configuration and reconfigure to prevent root
2189 login.
2190
2191 Copy your ssh public key (eg: @file{~/.ssh/id_rsa.pub}) as
2192 @file{@var{<your-username-here>}_rsa.pub} and put
2193 @file{guix-config.scm} in the same directory. In a new terminal run
2194 these commands.
2195
2196 @example
2197 sftp root@@<remote server ip address>
2198 put /path/to/files/<username>_rsa.pub .
2199 put /path/to/files/guix-config.scm .
2200 @end example
2201
2202 In your first terminal, mount the guix drive:
2203
2204 @example
2205 mkdir /mnt/guix
2206 mount /dev/sdc /mnt/guix
2207 @end example
2208
2209 Due to the way we set up the bootloader section of the guix-config.scm,
2210 only the grub configuration file will be installed. So, we need to copy
2211 over some of the other GRUB stuff already installed on the Debian system:
2212
2213 @example
2214 mkdir -p /mnt/guix/boot/grub
2215 cp -r /boot/grub/* /mnt/guix/boot/grub/
2216 @end example
2217
2218 Now initialize the Guix installation:
2219
2220 @example
2221 guix system init guix-config.scm /mnt/guix
2222 @end example
2223
2224 Ok, power it down!
2225 Now from the Linode console, select boot and select "Guix".
2226
2227 Once it boots, you should be able to log in via SSH! (The server config
2228 will have changed though.) You may encounter an error like:
2229
2230 @example
2231 $ ssh root@@<server ip address>
2232 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
2233 @ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @
2234 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
2235 IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
2236 Someone could be eavesdropping on you right now (man-in-the-middle attack)!
2237 It is also possible that a host key has just been changed.
2238 The fingerprint for the ECDSA key sent by the remote host is
2239 SHA256:0B+wp33w57AnKQuHCvQP0+ZdKaqYrI/kyU7CfVbS7R4.
2240 Please contact your system administrator.
2241 Add correct host key in /home/joshua/.ssh/known_hosts to get rid of this message.
2242 Offending ECDSA key in /home/joshua/.ssh/known_hosts:3
2243 ECDSA host key for 198.58.98.76 has changed and you have requested strict checking.
2244 Host key verification failed.
2245 @end example
2246
2247 Either delete @file{~/.ssh/known_hosts} file, or delete the offending line
2248 starting with your server IP address.
2249
2250 Be sure to set your password and root's password.
2251
2252 @example
2253 ssh root@@<remote ip address>
2254 passwd ; for the root password
2255 passwd <username> ; for the user password
2256 @end example
2257
2258 You may not be able to run the above commands at this point. If you
2259 have issues remotely logging into your linode box via SSH, then you may
2260 still need to set your root and user password initially by clicking on
2261 the ``Launch Console'' option in your linode. Choose the ``Glish''
2262 instead of ``Weblish''. Now you should be able to ssh into the machine.
2263
2264 Hooray! At this point you can shut down the server, delete the
2265 Debian disk, and resize the Guix to the rest of the size.
2266 Congratulations!
2267
2268 By the way, if you save it as a disk image right at this point, you'll
2269 have an easy time spinning up new Guix images! You may need to
2270 down-size the Guix image to 6144MB, to save it as an image. Then you
2271 can resize it again to the max size.
2272
2273 @node Setting up a bind mount
2274 @section Setting up a bind mount
2275
2276 To bind mount a file system, one must first set up some definitions
2277 before the @code{operating-system} section of the system definition. In
2278 this example we will bind mount a folder from a spinning disk drive to
2279 @file{/tmp}, to save wear and tear on the primary SSD, without
2280 dedicating an entire partition to be mounted as @file{/tmp}.
2281
2282 First, the source drive that hosts the folder we wish to bind mount
2283 should be defined, so that the bind mount can depend on it.
2284
2285 @lisp
2286 (define source-drive ;; "source-drive" can be named anything you want.
2287 (file-system
2288 (device (uuid "UUID goes here"))
2289 (mount-point "/path-to-spinning-disk-goes-here")
2290 (type "ext4"))) ;; Make sure to set this to the appropriate type for your drive.
2291 @end lisp
2292
2293 The source folder must also be defined, so that guix will know it's not
2294 a regular block device, but a folder.
2295 @lisp
2296 (define (%source-directory) "/path-to-spinning-disk-goes-here/tmp") ;; "source-directory" can be named any valid variable name.
2297 @end lisp
2298
2299 Finally, inside the @code{file-systems} definition, we must add the
2300 mount itself.
2301
2302 @lisp
2303 (file-systems (cons*
2304
2305 ...<other drives omitted for clarity>...
2306
2307 source-drive ;; Must match the name you gave the source drive in the earlier definition.
2308
2309 (file-system
2310 (device (%source-directory)) ;; Make sure "source-directory" matches your earlier definition.
2311 (mount-point "/tmp")
2312 (type "none") ;; We are mounting a folder, not a partition, so this type needs to be "none"
2313 (flags '(bind-mount))
2314 (dependencies (list source-drive)) ;; Ensure "source-drive" matches what you've named the variable for the drive.
2315 )
2316
2317 ...<other drives omitted for clarity>...
2318
2319 ))
2320 @end lisp
2321
2322 @node Getting substitutes from Tor
2323 @section Getting substitutes from Tor
2324
2325 Guix daemon can use a HTTP proxy to get substitutes, here we are
2326 configuring it to get them via Tor.
2327
2328 @quotation Warning
2329 @emph{Not all} Guix daemon's traffic will go through Tor! Only
2330 HTTP/HTTPS will get proxied; FTP, Git protocol, SSH, etc connections
2331 will still go through the clearnet. Again, this configuration isn't
2332 foolproof some of your traffic won't get routed by Tor at all. Use it
2333 at your own risk.
2334
2335 Also note that the procedure described here applies only to package
2336 substitution. When you update your guix distribution with
2337 @command{guix pull}, you still need to use @command{torsocks} if
2338 you want to route the connection to guix's git repository servers
2339 through Tor.
2340 @end quotation
2341
2342 Guix's substitute server is available as a Onion service, if you want
2343 to use it to get your substitutes through Tor configure your system as
2344 follow:
2345
2346 @lisp
2347 (use-modules (gnu))
2348 (use-service-module base networking)
2349
2350 (operating-system
2351
2352 (services
2353 (cons
2354 (service tor-service-type
2355 (tor-configuration
2356 (config-file (plain-file "tor-config"
2357 "HTTPTunnelPort 127.0.0.1:9250"))))
2358 (modify-services %base-services
2359 (guix-service-type
2360 config => (guix-configuration
2361 (inherit config)
2362 ;; ci.guix.gnu.org's Onion service
2363 (substitute-urls "https://bp7o7ckwlewr4slm.onion")
2364 (http-proxy "http://localhost:9250")))))))
2365 @end lisp
2366
2367 This will keep a tor process running that provides a HTTP CONNECT tunnel
2368 which will be used by @command{guix-daemon}. The daemon can use other
2369 protocols than HTTP(S) to get remote resources, request using those
2370 protocols won't go through Tor since we are only setting a HTTP tunnel
2371 here. Note that @code{substitutes-urls} is using HTTPS and not HTTP or
2372 it won't work, that's a limitation of Tor's tunnel; you may want to use
2373 @command{privoxy} instead to avoid such limitations.
2374
2375 If you don't want to always get substitutes through Tor but using it just
2376 some of the times, then skip the @code{guix-configuration}. When you
2377 want to get a substitute from the Tor tunnel run:
2378
2379 @example
2380 sudo herd set-http-proxy guix-daemon http://localhost:9250
2381 guix build --substitute-urls=https://bp7o7ckwlewr4slm.onion …
2382 @end example
2383
2384 @node Setting up NGINX with Lua
2385 @section Setting up NGINX with Lua
2386 @cindex nginx, lua, openresty, resty
2387
2388 NGINX could be extended with Lua scripts.
2389
2390 Guix provides NGINX service with ability to load Lua module and specific
2391 Lua packages, and reply to requests by evaluating Lua scripts.
2392
2393 The following example demonstrates system definition with configuration
2394 to evaluate @file{index.lua} Lua script on HTTP request to
2395 @uref{http://localhost/hello} endpoint:
2396
2397 @example
2398 local shell = require "resty.shell"
2399
2400 local stdin = ""
2401 local timeout = 1000 -- ms
2402 local max_size = 4096 -- byte
2403
2404 local ok, stdout, stderr, reason, status =
2405 shell.run([[/run/current-system/profile/bin/ls /tmp]], stdin, timeout, max_size)
2406
2407 ngx.say(stdout)
2408 @end example
2409
2410 @lisp
2411 (use-modules (gnu))
2412 (use-service-modules #;… web)
2413 (use-package-modules #;… lua)
2414 (operating-system
2415 ;; …
2416 (services
2417 ;; …
2418 (service nginx-service-type
2419 (nginx-configuration
2420 (modules
2421 (list
2422 (file-append nginx-lua-module "/etc/nginx/modules/ngx_http_lua_module.so")))
2423 (lua-package-path (list lua-resty-core
2424 lua-resty-lrucache
2425 lua-resty-signal
2426 lua-tablepool
2427 lua-resty-shell))
2428 (lua-package-cpath (list lua-resty-signal))
2429 (server-blocks
2430 (list (nginx-server-configuration
2431 (server-name '("localhost"))
2432 (listen '("80"))
2433 (root "/etc")
2434 (locations (list
2435 (nginx-location-configuration
2436 (uri "/hello")
2437 (body (list #~(format #f "content_by_lua_file ~s;"
2438 #$(local-file "index.lua"))))))))))))))
2439 @end lisp
2440
2441 @c *********************************************************************
2442 @node Advanced package management
2443 @chapter Advanced package management
2444
2445 Guix is a functional package manager that offers many features beyond
2446 what more traditional package managers can do. To the uninitiated,
2447 those features might not have obvious use cases at first. The purpose
2448 of this chapter is to demonstrate some advanced package management
2449 concepts.
2450
2451 @pxref{Package Management,,, guix, GNU Guix Reference Manual} for a complete
2452 reference.
2453
2454 @menu
2455 * Guix Profiles in Practice:: Strategies for multiple profiles and manifests.
2456 @end menu
2457
2458 @node Guix Profiles in Practice
2459 @section Guix Profiles in Practice
2460
2461 Guix provides a very useful feature that may be quite foreign to newcomers:
2462 @emph{profiles}. They are a way to group package installations together and all users
2463 on the same system are free to use as many profiles as they want.
2464
2465 Whether you're a developer or not, you may find that multiple profiles bring you
2466 great power and flexibility. While they shift the paradigm somewhat compared to
2467 @emph{traditional package managers}, they are very convenient to use once you've
2468 understood how to set them up.
2469
2470 If you are familiar with Python's @samp{virtualenv}, you can think of a profile as a
2471 kind of universal @samp{virtualenv} that can hold any kind of software whatsoever, not
2472 just Python software. Furthermore, profiles are self-sufficient: they capture
2473 all the runtime dependencies which guarantees that all programs within a profile
2474 will always work at any point in time.
2475
2476 Multiple profiles have many benefits:
2477
2478 @itemize
2479 @item
2480 Clean semantic separation of the various packages a user needs for different contexts.
2481
2482 @item
2483 Multiple profiles can be made available into the environment either on login
2484 or within a dedicated shell.
2485
2486 @item
2487 Profiles can be loaded on demand. For instance, the user can use multiple
2488 shells, each of them running different profiles.
2489
2490 @item
2491 Isolation: Programs from one profile will not use programs from the other, and
2492 the user can even install different versions of the same programs to the two
2493 profiles without conflict.
2494
2495 @item
2496 Deduplication: Profiles share dependencies that happens to be the exact same.
2497 This makes multiple profiles storage-efficient.
2498
2499 @item
2500 Reproducible: when used with declarative manifests, a profile can be fully
2501 specified by the Guix commit that was active when it was set up. This means
2502 that the exact same profile can be
2503 @uref{https://guix.gnu.org/blog/2018/multi-dimensional-transactions-and-rollbacks-oh-my/,
2504 set up anywhere and anytime}, with just the commit information. See the
2505 section on @ref{Reproducible profiles}.
2506
2507 @item
2508 Easier upgrades and maintenance: Multiple profiles make it easy to keep
2509 package listings at hand and make upgrades completely frictionless.
2510 @end itemize
2511
2512 Concretely, here follows some typical profiles:
2513
2514 @itemize
2515 @item
2516 The dependencies of a project you are working on.
2517
2518 @item
2519 Your favourite programming language libraries.
2520
2521 @item
2522 Laptop-specific programs (like @samp{powertop}) that you don't need on a desktop.
2523
2524 @item
2525 @TeX{}live (this one can be really useful when you need to install just one
2526 package for this one document you've just received over email).
2527
2528 @item
2529 Games.
2530 @end itemize
2531
2532 Let's dive in the set up!
2533
2534 @node Basic setup with manifests
2535 @subsection Basic setup with manifests
2536
2537 A Guix profile can be set up @emph{via} a so-called @emph{manifest specification} that looks like
2538 this:
2539
2540 @lisp
2541 (specifications->manifest
2542 '("package-1"
2543 ;; Version 1.3 of package-2.
2544 "package-2@@1.3"
2545 ;; The "lib" output of package-3.
2546 "package-3:lib"
2547 ; ...
2548 "package-N"))
2549 @end lisp
2550
2551 @pxref{Invoking guix package,,, guix, GNU Guix Reference Manual}, for
2552 the syntax details.
2553
2554 We can create a manifest specification per profile and install them this way:
2555
2556 @example
2557 GUIX_EXTRA_PROFILES=$HOME/.guix-extra-profiles
2558 mkdir -p "$GUIX_EXTRA_PROFILES"/my-project # if it does not exist yet
2559 guix package --manifest=/path/to/guix-my-project-manifest.scm --profile="$GUIX_EXTRA_PROFILES"/my-project/my-project
2560 @end example
2561
2562 Here we set an arbitrary variable @samp{GUIX_EXTRA_PROFILES} to point to the directory
2563 where we will store our profiles in the rest of this article.
2564
2565 Placing all your profiles in a single directory, with each profile getting its
2566 own sub-directory, is somewhat cleaner. This way, each sub-directory will
2567 contain all the symlinks for precisely one profile. Besides, ``looping over
2568 profiles'' becomes obvious from any programming language (e.g.@: a shell script) by
2569 simply looping over the sub-directories of @samp{$GUIX_EXTRA_PROFILES}.
2570
2571 Note that it's also possible to loop over the output of
2572
2573 @example
2574 guix package --list-profiles
2575 @end example
2576
2577 although you'll probably have to filter out @file{~/.config/guix/current}.
2578
2579 To enable all profiles on login, add this to your @file{~/.bash_profile} (or similar):
2580
2581 @example
2582 for i in $GUIX_EXTRA_PROFILES/*; do
2583 profile=$i/$(basename "$i")
2584 if [ -f "$profile"/etc/profile ]; then
2585 GUIX_PROFILE="$profile"
2586 . "$GUIX_PROFILE"/etc/profile
2587 fi
2588 unset profile
2589 done
2590 @end example
2591
2592 Note to Guix System users: the above reflects how your default profile
2593 @file{~/.guix-profile} is activated from @file{/etc/profile}, that latter being loaded by
2594 @file{~/.bashrc} by default.
2595
2596 You can obviously choose to only enable a subset of them:
2597
2598 @example
2599 for i in "$GUIX_EXTRA_PROFILES"/my-project-1 "$GUIX_EXTRA_PROFILES"/my-project-2; do
2600 profile=$i/$(basename "$i")
2601 if [ -f "$profile"/etc/profile ]; then
2602 GUIX_PROFILE="$profile"
2603 . "$GUIX_PROFILE"/etc/profile
2604 fi
2605 unset profile
2606 done
2607 @end example
2608
2609 When a profile is off, it's straightforward to enable it for an individual shell
2610 without "polluting" the rest of the user session:
2611
2612 @example
2613 GUIX_PROFILE="path/to/my-project" ; . "$GUIX_PROFILE"/etc/profile
2614 @end example
2615
2616 The key to enabling a profile is to @emph{source} its @samp{etc/profile} file. This file
2617 contains shell code that exports the right environment variables necessary to
2618 activate the software contained in the profile. It is built automatically by
2619 Guix and meant to be sourced.
2620 It contains the same variables you would get if you ran:
2621
2622 @example
2623 guix package --search-paths=prefix --profile=$my_profile"
2624 @end example
2625
2626 Once again, see (@pxref{Invoking guix package,,, guix, GNU Guix Reference Manual})
2627 for the command line options.
2628
2629 To upgrade a profile, simply install the manifest again:
2630
2631 @example
2632 guix package -m /path/to/guix-my-project-manifest.scm -p "$GUIX_EXTRA_PROFILES"/my-project/my-project
2633 @end example
2634
2635 To upgrade all profiles, it's easy enough to loop over them. For instance,
2636 assuming your manifest specifications are stored in
2637 @file{~/.guix-manifests/guix-$profile-manifest.scm}, with @samp{$profile} being the name
2638 of the profile (e.g.@: "project1"), you could do the following in Bourne shell:
2639
2640 @example
2641 for profile in "$GUIX_EXTRA_PROFILES"/*; do
2642 guix package --profile="$profile" --manifest="$HOME/.guix-manifests/guix-$profile-manifest.scm"
2643 done
2644 @end example
2645
2646 Each profile has its own generations:
2647
2648 @example
2649 guix package -p "$GUIX_EXTRA_PROFILES"/my-project/my-project --list-generations
2650 @end example
2651
2652 You can roll-back to any generation of a given profile:
2653
2654 @example
2655 guix package -p "$GUIX_EXTRA_PROFILES"/my-project/my-project --switch-generations=17
2656 @end example
2657
2658 Finally, if you want to switch to a profile without inheriting from the
2659 current environment, you can activate it from an empty shell:
2660
2661 @example
2662 env -i $(which bash) --login --noprofile --norc
2663 . my-project/etc/profile
2664 @end example
2665
2666 @node Required packages
2667 @subsection Required packages
2668
2669 Activating a profile essentially boils down to exporting a bunch of
2670 environmental variables. This is the role of the @samp{etc/profile} within the
2671 profile.
2672
2673 @emph{Note: Only the environmental variables of the packages that consume them will
2674 be set.}
2675
2676 For instance, @samp{MANPATH} won't be set if there is no consumer application for man
2677 pages within the profile. So if you need to transparently access man pages once
2678 the profile is loaded, you've got two options:
2679
2680 @itemize
2681 @item
2682 Either export the variable manually, e.g.
2683 @example
2684 export MANPATH=/path/to/profile$@{MANPATH:+:@}$MANPATH
2685 @end example
2686
2687 @item
2688 Or include @samp{man-db} to the profile manifest.
2689 @end itemize
2690
2691 The same is true for @samp{INFOPATH} (you can install @samp{info-reader}),
2692 @samp{PKG_CONFIG_PATH} (install @samp{pkg-config}), etc.
2693
2694 @node Default profile
2695 @subsection Default profile
2696
2697 What about the default profile that Guix keeps in @file{~/.guix-profile}?
2698
2699 You can assign it the role you want. Typically you would install the manifest
2700 of the packages you want to use all the time.
2701
2702 Alternatively, you could keep it ``manifest-less'' for throw-away packages
2703 that you would just use for a couple of days.
2704 This way makes it convenient to run
2705
2706 @example
2707 guix install package-foo
2708 guix upgrade package-bar
2709 @end example
2710
2711 without having to specify the path to a profile.
2712
2713 @node The benefits of manifests
2714 @subsection The benefits of manifests
2715
2716 Manifests are a convenient way to keep your package lists around and, say,
2717 to synchronize them across multiple machines using a version control system.
2718
2719 A common complaint about manifests is that they can be slow to install when they
2720 contain large number of packages. This is especially cumbersome when you just
2721 want get an upgrade for one package within a big manifest.
2722
2723 This is one more reason to use multiple profiles, which happen to be just
2724 perfect to break down manifests into multiple sets of semantically connected
2725 packages. Using multiple, small profiles provides more flexibility and
2726 usability.
2727
2728 Manifests come with multiple benefits. In particular, they ease maintenance:
2729
2730 @itemize
2731 @item
2732 When a profile is set up from a manifest, the manifest itself is
2733 self-sufficient to keep a ``package listing'' around and reinstall the profile
2734 later or on a different system. For ad-hoc profiles, we would need to
2735 generate a manifest specification manually and maintain the package versions
2736 for the packages that don't use the default version.
2737
2738 @item
2739 @code{guix package --upgrade} always tries to update the packages that have
2740 propagated inputs, even if there is nothing to do. Guix manifests remove this
2741 problem.
2742
2743 @item
2744 When partially upgrading a profile, conflicts may arise (due to diverging
2745 dependencies between the updated and the non-updated packages) and they can be
2746 annoying to resolve manually. Manifests remove this problem altogether since
2747 all packages are always upgraded at once.
2748
2749 @item
2750 As mentioned above, manifests allow for reproducible profiles, while the
2751 imperative @code{guix install}, @code{guix upgrade}, etc. do not, since they produce
2752 different profiles every time even when they hold the same packages. See
2753 @uref{https://issues.guix.gnu.org/issue/33285, the related discussion on the matter}.
2754
2755 @item
2756 Manifest specifications are usable by other @samp{guix} commands. For example, you
2757 can run @code{guix weather -m manifest.scm} to see how many substitutes are
2758 available, which can help you decide whether you want to try upgrading today
2759 or wait a while. Another example: you can run @code{guix pack -m manifest.scm} to
2760 create a pack containing all the packages in the manifest (and their
2761 transitive references).
2762
2763 @item
2764 Finally, manifests have a Scheme representation, the @samp{<manifest>} record type.
2765 They can be manipulated in Scheme and passed to the various Guix @uref{https://en.wikipedia.org/wiki/Api, APIs}.
2766 @end itemize
2767
2768 It's important to understand that while manifests can be used to declare
2769 profiles, they are not strictly equivalent: profiles have the side effect that
2770 they ``pin'' packages in the store, which prevents them from being
2771 garbage-collected (@pxref{Invoking guix gc,,, guix, GNU Guix Reference Manual})
2772 and ensures that they will still be available at any point in
2773 the future.
2774
2775 Let's take an example:
2776
2777 @enumerate
2778 @item
2779 We have an environment for hacking on a project for which there isn't a Guix
2780 package yet. We build the environment using a manifest, and then run @code{guix
2781 environment -m manifest.scm}. So far so good.
2782
2783 @item
2784 Many weeks pass and we have run a couple of @code{guix pull} in the mean time.
2785 Maybe a dependency from our manifest has been updated; or we may have run
2786 @code{guix gc} and some packages needed by our manifest have been
2787 garbage-collected.
2788
2789 @item
2790 Eventually, we set to work on that project again, so we run @code{guix environment
2791 -m manifest.scm}. But now we have to wait for Guix to build and install
2792 stuff!
2793 @end enumerate
2794
2795 Ideally, we could spare the rebuild time. And indeed we can, all we need is to
2796 install the manifest to a profile and use @code{GUIX_PROFILE=/the/profile;
2797 . "$GUIX_PROFILE"/etc/profile} as explained above: this guarantees that our
2798 hacking environment will be available at all times.
2799
2800 @emph{Security warning:} While keeping old profiles around can be convenient, keep in
2801 mind that outdated packages may not have received the latest security fixes.
2802
2803 @node Reproducible profiles
2804 @subsection Reproducible profiles
2805
2806 To reproduce a profile bit-for-bit, we need two pieces of information:
2807
2808 @itemize
2809 @item
2810 a manifest,
2811 @item
2812 a Guix channel specification.
2813 @end itemize
2814
2815 Indeed, manifests alone might not be enough: different Guix versions (or
2816 different channels) can produce different outputs for a given manifest.
2817
2818 You can output the Guix channel specification with @samp{guix describe
2819 --format=channels}.
2820 Save this to a file, say @samp{channel-specs.scm}.
2821
2822 On another computer, you can use the channel specification file and the manifest
2823 to reproduce the exact same profile:
2824
2825 @example
2826 GUIX_EXTRA_PROFILES=$HOME/.guix-extra-profiles
2827 GUIX_EXTRA=$HOME/.guix-extra
2828
2829 mkdir "$GUIX_EXTRA"/my-project
2830 guix pull --channels=channel-specs.scm --profile "$GUIX_EXTRA/my-project/guix"
2831
2832 mkdir -p "$GUIX_EXTRA_PROFILES/my-project"
2833 "$GUIX_EXTRA"/my-project/guix/bin/guix package --manifest=/path/to/guix-my-project-manifest.scm --profile="$GUIX_EXTRA_PROFILES"/my-project/my-project
2834 @end example
2835
2836 It's safe to delete the Guix channel profile you've just installed with the
2837 channel specification, the project profile does not depend on it.
2838
2839 @c *********************************************************************
2840 @node Environment management
2841 @chapter Environment management
2842
2843 Guix provides multiple tools to manage environment. This chapter
2844 demonstrate such utilities.
2845
2846 @menu
2847 * Guix environment via direnv:: Setup Guix environment with direnv
2848 @end menu
2849
2850 @node Guix environment via direnv
2851 @section Guix environment via direnv
2852
2853 Guix provides a @samp{direnv} package, which could extend shell after
2854 directory change. This tool could be used to prepare a pure Guix
2855 environment.
2856
2857 The following example provides a shell function for @file{~/.direnvrc}
2858 file, which could be used from Guix Git repository in
2859 @file{~/src/guix/.envrc} file to setup a build environment similar to
2860 described in @pxref{Building from Git,,, guix, GNU Guix Reference
2861 Manual}.
2862
2863 Create a @file{~/.direnvrc} with a Bash code:
2864
2865 @example
2866 # Thanks <https://github.com/direnv/direnv/issues/73#issuecomment-152284914>
2867 export_function()
2868 @{
2869 local name=$1
2870 local alias_dir=$PWD/.direnv/aliases
2871 mkdir -p "$alias_dir"
2872 PATH_add "$alias_dir"
2873 local target="$alias_dir/$name"
2874 if declare -f "$name" >/dev/null; then
2875 echo "#!$SHELL" > "$target"
2876 declare -f "$name" >> "$target" 2>/dev/null
2877 # Notice that we add shell variables to the function trigger.
2878 echo "$name \$*" >> "$target"
2879 chmod +x "$target"
2880 fi
2881 @}
2882
2883 use_guix()
2884 @{
2885 # Set GitHub token.
2886 export GUIX_GITHUB_TOKEN="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
2887
2888 # Unset 'GUIX_PACKAGE_PATH'.
2889 export GUIX_PACKAGE_PATH=""
2890
2891 # Recreate a garbage collector root.
2892 gcroots="$HOME/.config/guix/gcroots"
2893 mkdir -p "$gcroots"
2894 gcroot="$gcroots/guix"
2895 if [ -L "$gcroot" ]
2896 then
2897 rm -v "$gcroot"
2898 fi
2899
2900 # Miscellaneous packages.
2901 PACKAGES_MAINTENANCE=(
2902 direnv
2903 git
2904 git:send-email
2905 git-cal
2906 gnupg
2907 guile-colorized
2908 guile-readline
2909 less
2910 ncurses
2911 openssh
2912 xdot
2913 )
2914
2915 # Environment packages.
2916 PACKAGES=(help2man guile-sqlite3 guile-gcrypt)
2917
2918 # Thanks <https://lists.gnu.org/archive/html/guix-devel/2016-09/msg00859.html>
2919 eval "$(guix environment --search-paths --root="$gcroot" --pure guix --ad-hoc $@{PACKAGES[@@]@} $@{PACKAGES_MAINTENANCE[@@]@} "$@@")"
2920
2921 # Predefine configure flags.
2922 configure()
2923 @{
2924 ./configure --localstatedir=/var --prefix=
2925 @}
2926 export_function configure
2927
2928 # Run make and optionally build something.
2929 build()
2930 @{
2931 make -j 2
2932 if [ $# -gt 0 ]
2933 then
2934 ./pre-inst-env guix build "$@@"
2935 fi
2936 @}
2937 export_function build
2938
2939 # Predefine push Git command.
2940 push()
2941 @{
2942 git push --set-upstream origin
2943 @}
2944 export_function push
2945
2946 clear # Clean up the screen.
2947 git-cal --author='Your Name' # Show contributions calendar.
2948
2949 # Show commands help.
2950 echo "
2951 build build a package or just a project if no argument provided
2952 configure run ./configure with predefined parameters
2953 push push to upstream Git repository
2954 "
2955 @}
2956 @end example
2957
2958 Every project containing @file{.envrc} with a string @code{use guix}
2959 will have predefined environment variables and procedures.
2960
2961 Run @command{direnv allow} to setup the environment for the first time.
2962
2963 @c *********************************************************************
2964 @node Acknowledgments
2965 @chapter Acknowledgments
2966
2967 Guix is based on the @uref{https://nixos.org/nix/, Nix package manager},
2968 which was designed and
2969 implemented by Eelco Dolstra, with contributions from other people (see
2970 the @file{nix/AUTHORS} file in Guix.) Nix pioneered functional package
2971 management, and promoted unprecedented features, such as transactional
2972 package upgrades and rollbacks, per-user profiles, and referentially
2973 transparent build processes. Without this work, Guix would not exist.
2974
2975 The Nix-based software distributions, Nixpkgs and NixOS, have also been
2976 an inspiration for Guix.
2977
2978 GNU@tie{}Guix itself is a collective work with contributions from a
2979 number of people. See the @file{AUTHORS} file in Guix for more
2980 information on these fine people. The @file{THANKS} file lists people
2981 who have helped by reporting bugs, taking care of the infrastructure,
2982 providing artwork and themes, making suggestions, and more---thank you!
2983
2984 This document includes adapted sections from articles that have previously
2985 been published on the Guix blog at @uref{https://guix.gnu.org/blog}.
2986
2987
2988 @c *********************************************************************
2989 @node GNU Free Documentation License
2990 @appendix GNU Free Documentation License
2991 @cindex license, GNU Free Documentation License
2992 @include fdl-1.3.texi
2993
2994 @c *********************************************************************
2995 @node Concept Index
2996 @unnumbered Concept Index
2997 @printindex cp
2998
2999 @bye
3000
3001 @c Local Variables:
3002 @c ispell-local-dictionary: "american";
3003 @c End: