doc: cookbook: Mention translations of the cookbook.
[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 (snippet '(begin
799 ;; Remove bundled software.
800 (delete-file-recursively "deps")
801 #true))))
802 (build-system cmake-build-system)
803 (outputs '("out" "debug"))
804 (arguments
805 `(#:tests? #true ; Run the test suite (this is the default)
806 #:configure-flags '("-DUSE_SHA1DC=ON") ; SHA-1 collision detection
807 #:phases
808 (modify-phases %standard-phases
809 (add-after 'unpack 'fix-hardcoded-paths
810 (lambda _
811 (substitute* "tests/repo/init.c"
812 (("#!/bin/sh") (string-append "#!" (which "sh"))))
813 (substitute* "tests/clar/fs.h"
814 (("/bin/cp") (which "cp"))
815 (("/bin/rm") (which "rm")))
816 #true))
817 ;; Run checks more verbosely.
818 (replace 'check
819 (lambda _ (invoke "./libgit2_clar" "-v" "-Q")))
820 (add-after 'unpack 'make-files-writable-for-tests
821 (lambda _ (for-each make-file-writable (find-files "." ".*")))))))
822 (inputs
823 `(("libssh2" ,libssh2)
824 ("http-parser" ,http-parser)
825 ("python" ,python-wrapper)))
826 (native-inputs
827 `(("pkg-config" ,pkg-config)))
828 (propagated-inputs
829 ;; These two libraries are in 'Requires.private' in libgit2.pc.
830 `(("openssl" ,openssl)
831 ("zlib" ,zlib)))
832 (home-page "https://libgit2.github.com/")
833 (synopsis "Library providing Git core methods")
834 (description
835 "Libgit2 is a portable, pure C implementation of the Git core methods
836 provided as a re-entrant linkable library with a solid API, allowing you to
837 write native speed custom Git applications in any language with bindings.")
838 ;; GPLv2 with linking exception
839 (license license:gpl2))))
840 @end lisp
841
842 (In those cases were you only want to tweak a few fields from a package
843 definition, you should rely on inheritance instead of copy-pasting everything.
844 See below.)
845
846 Let's discuss those fields in depth.
847
848 @subsubsection @code{git-fetch} method
849
850 Unlike the @code{url-fetch} method, @code{git-fetch} expects a @code{git-reference} which takes
851 a Git repository and a commit. The commit can be any Git reference such as
852 tags, so if the @code{version} is tagged, then it can be used directly. Sometimes
853 the tag is prefixed with a @code{v}, in which case you'd use @code{(commit (string-append
854 "v" version))}.
855
856 To ensure that the source code from the Git repository is stored in a
857 directory with a descriptive name, we use @code{(file-name (git-file-name name
858 version))}.
859
860 The @code{git-version} procedure can be used to derive the
861 version when packaging programs for a specific commit, following the
862 Guix contributor guidelines (@pxref{Version Numbers,,, guix, GNU Guix
863 Reference Manual}).
864
865 How does one obtain the @code{sha256} hash that's in there, you ask? By
866 invoking @command{guix hash} on a checkout of the desired commit, along
867 these lines:
868
869 @example
870 git clone https://github.com/libgit2/libgit2/
871 cd libgit2
872 git checkout v0.26.6
873 guix hash -rx .
874 @end example
875
876 @command{guix hash -rx} computes a SHA256 hash over the whole directory,
877 excluding the @file{.git} sub-directory (@pxref{Invoking guix hash,,,
878 guix, GNU Guix Reference Manual}).
879
880 In the future, @command{guix download} will hopefully be able to do
881 these steps for you, just like it does for regular downloads.
882
883 @subsubsection Snippets
884
885 Snippets are quoted (i.e. non-evaluated) Scheme code that are a means of patching
886 the source. They are a Guix-y alternative to the traditional @file{.patch} files.
887 Because of the quote, the code in only evaluated when passed to the Guix daemon
888 for building. There can be as many snippets as needed.
889
890 Snippets might need additional Guile modules which can be imported from the
891 @code{modules} field.
892
893 @subsubsection Inputs
894
895 First, a syntactic comment: See the quasi-quote / comma syntax?
896
897 @lisp
898 (native-inputs
899 `(("pkg-config" ,pkg-config)))
900 @end lisp
901
902 is equivalent to
903
904 @lisp
905 (native-inputs
906 (list (list "pkg-config" pkg-config)))
907 @end lisp
908
909 You'll mostly see the former because it's shorter.
910
911 There are 3 different input types. In short:
912
913 @table @asis
914 @item native-inputs
915 Required for building but not runtime -- installing a package
916 through a substitute won't install these inputs.
917 @item inputs
918 Installed in the store but not in the profile, as well as being
919 present at build time.
920 @item propagated-inputs
921 Installed in the store and in the profile, as well as
922 being present at build time.
923 @end table
924
925 @xref{Package Reference,,, guix, GNU Guix Reference Manual} for more details.
926
927 The distinction between the various inputs is important: if a dependency can be
928 handled as an @emph{input} instead of a @emph{propagated input}, it should be done so, or
929 else it ``pollutes'' the user profile for no good reason.
930
931 For instance, a user installing a graphical program that depends on a
932 command line tool might only be interested in the graphical part, so there is no
933 need to force the command line tool into the user profile. The dependency is a
934 concern to the package, not to the user. @emph{Inputs} make it possible to handle
935 dependencies without bugging the user by adding undesired executable files (or
936 libraries) to their profile.
937
938 Same goes for @emph{native-inputs}: once the program is installed, build-time
939 dependencies can be safely garbage-collected.
940 It also matters when a substitute is available, in which case only the @emph{inputs}
941 and @emph{propagated inputs} will be fetched: the @emph{native inputs} are not required to
942 install a package from a substitute.
943
944 @subsubsection Outputs
945
946 Just like how a package can have multiple inputs, it can also produce multiple
947 outputs.
948
949 Each output corresponds to a separate directory in the store.
950
951 The user can choose which output to install; this is useful to save space or
952 to avoid polluting the user profile with unwanted executables or libraries.
953
954 Output separation is optional. When the @code{outputs} field is left out, the
955 default and only output (the complete package) is referred to as @code{"out"}.
956
957 Typical separate output names include @code{debug} and @code{doc}.
958
959 It's advised to separate outputs only when you've shown it's worth it: if the
960 output size is significant (compare with @code{guix size}) or in case the package is
961 modular.
962
963 @subsubsection Build system arguments
964
965 The @code{arguments} is a keyword-value list used to configure the build process.
966
967 The simplest argument @code{#:tests?} can be used to disable the test suite when
968 building the package. This is mostly useful when the package does not feature
969 any test suite. It's strongly recommended to keep the test suite on if there is
970 one.
971
972 Another common argument is @code{:make-flags}, which specifies a list of flags to
973 append when running make, as you would from the command line. For instance, the
974 following flags
975
976 @lisp
977 #:make-flags (list (string-append "prefix=" (assoc-ref %outputs "out"))
978 "CC=gcc")
979 @end lisp
980
981 translate into
982
983 @example
984 $ make CC=gcc prefix=/gnu/store/...-<out>
985 @end example
986
987 This sets the C compiler to @code{gcc} and the @code{prefix} variable (the installation
988 directory in Make parlance) to @code{(assoc-ref %outputs "out")}, which is a build-stage
989 global variable pointing to the destination directory in the store (something like
990 @file{/gnu/store/...-my-libgit2-20180408}).
991
992 Similarly, it's possible to set the configure flags:
993
994 @lisp
995 #:configure-flags '("-DUSE_SHA1DC=ON")
996 @end lisp
997
998 The @code{%build-inputs} variable is also generated in scope. It's an association
999 table that maps the input names to their store directories.
1000
1001 The @code{phases} keyword lists the sequential steps of the build system. Typically
1002 phases include @code{unpack}, @code{configure}, @code{build}, @code{install} and @code{check}. To know
1003 more about those phases, you need to work out the appropriate build system
1004 definition in @samp{$GUIX_CHECKOUT/guix/build/gnu-build-system.scm}:
1005
1006 @lisp
1007 (define %standard-phases
1008 ;; Standard build phases, as a list of symbol/procedure pairs.
1009 (let-syntax ((phases (syntax-rules ()
1010 ((_ p ...) `((p . ,p) ...)))))
1011 (phases set-SOURCE-DATE-EPOCH set-paths install-locale unpack
1012 bootstrap
1013 patch-usr-bin-file
1014 patch-source-shebangs configure patch-generated-file-shebangs
1015 build check install
1016 patch-shebangs strip
1017 validate-runpath
1018 validate-documentation-location
1019 delete-info-dir-file
1020 patch-dot-desktop-files
1021 install-license-files
1022 reset-gzip-timestamps
1023 compress-documentation)))
1024 @end lisp
1025
1026 Or from the REPL:
1027
1028 @lisp
1029 (add-to-load-path "/path/to/guix/checkout")
1030 ,use (guix build gnu-build-system)
1031 (map first %standard-phases)
1032 @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)
1033 @end lisp
1034
1035 If you want to know more about what happens during those phases, consult the
1036 associated procedures.
1037
1038 For instance, as of this writing the definition of @code{unpack} for the GNU build
1039 system is:
1040
1041 @lisp
1042 (define* (unpack #:key source #:allow-other-keys)
1043 "Unpack SOURCE in the working directory, and change directory within the
1044 source. When SOURCE is a directory, copy it in a sub-directory of the current
1045 working directory."
1046 (if (file-is-directory? source)
1047 (begin
1048 (mkdir "source")
1049 (chdir "source")
1050
1051 ;; Preserve timestamps (set to the Epoch) on the copied tree so that
1052 ;; things work deterministically.
1053 (copy-recursively source "."
1054 #:keep-mtime? #true))
1055 (begin
1056 (if (string-suffix? ".zip" source)
1057 (invoke "unzip" source)
1058 (invoke "tar" "xvf" source))
1059 (chdir (first-subdirectory "."))))
1060 #true)
1061 @end lisp
1062
1063 Note the @code{chdir} call: it changes the working directory to where the source was
1064 unpacked.
1065 Thus every phase following the @code{unpack} will use the source as a working
1066 directory, which is why we can directly work on the source files.
1067 That is to say, unless a later phase changes the working directory to something
1068 else.
1069
1070 We modify the list of @code{%standard-phases} of the build system with the
1071 @code{modify-phases} macro as per the list of specified modifications, which may have
1072 the following forms:
1073
1074 @itemize
1075 @item
1076 @code{(add-before @var{phase} @var{new-phase} @var{procedure})}: Run @var{procedure} named @var{new-phase} before @var{phase}.
1077 @item
1078 @code{(add-after @var{phase} @var{new-phase} @var{procedure})}: Same, but afterwards.
1079 @item
1080 @code{(replace @var{phase} @var{procedure})}.
1081 @item
1082 @code{(delete @var{phase})}.
1083 @end itemize
1084
1085 The @var{procedure} supports the keyword arguments @code{inputs} and @code{outputs}. Each
1086 input (whether @emph{native}, @emph{propagated} or not) and output directory is referenced
1087 by their name in those variables. Thus @code{(assoc-ref outputs "out")} is the store
1088 directory of the main output of the package. A phase procedure may look like
1089 this:
1090
1091 @lisp
1092 (lambda* (#:key inputs outputs #:allow-other-keys)
1093 (let ((bash-directory (assoc-ref inputs "bash"))
1094 (output-directory (assoc-ref outputs "out"))
1095 (doc-directory (assoc-ref outputs "doc")))
1096 ;; ...
1097 #true))
1098 @end lisp
1099
1100 The procedure must return @code{#true} on success. It's brittle to rely on the return
1101 value of the last expression used to tweak the phase because there is no
1102 guarantee it would be a @code{#true}. Hence the trailing @code{#true} to ensure the right value
1103 is returned on success.
1104
1105 @subsubsection Code staging
1106
1107 The astute reader may have noticed the quasi-quote and comma syntax in the
1108 argument field. Indeed, the build code in the package declaration should not be
1109 evaluated on the client side, but only when passed to the Guix daemon. This
1110 mechanism of passing code around two running processes is called @uref{https://arxiv.org/abs/1709.00833, code staging}.
1111
1112 @subsubsection Utility functions
1113
1114 When customizing @code{phases}, we often need to write code that mimics the
1115 equivalent system invocations (@code{make}, @code{mkdir}, @code{cp}, etc.)@: commonly used during
1116 regular ``Unix-style'' installations.
1117
1118 Some like @code{chmod} are native to Guile.
1119 @xref{,,, guile, Guile reference manual} for a complete list.
1120
1121 Guix provides additional helper functions which prove especially handy in the
1122 context of package management.
1123
1124 Some of those functions can be found in
1125 @samp{$GUIX_CHECKOUT/guix/guix/build/utils.scm}. Most of them mirror the behaviour
1126 of the traditional Unix system commands:
1127
1128 @table @code
1129 @item which
1130 Like the @samp{which} system command.
1131 @item find-files
1132 Akin to the @samp{find} system command.
1133 @item mkdir-p
1134 Like @samp{mkdir -p}, which creates all parents as needed.
1135 @item install-file
1136 Similar to @samp{install} when installing a file to a (possibly
1137 non-existing) directory. Guile has @code{copy-file} which works
1138 like @samp{cp}.
1139 @item copy-recursively
1140 Like @samp{cp -r}.
1141 @item delete-file-recursively
1142 Like @samp{rm -rf}.
1143 @item invoke
1144 Run an executable. This should be used instead of @code{system*}.
1145 @item with-directory-excursion
1146 Run the body in a different working directory,
1147 then restore the previous working directory.
1148 @item substitute*
1149 A ``@command{sed}-like'' function.
1150 @end table
1151
1152 @xref{Build Utilities,,, guix, GNU Guix Reference Manual}, for more
1153 information on these utilities.
1154
1155 @subsubsection Module prefix
1156
1157 The license in our last example needs a prefix: this is because of how the
1158 @code{license} module was imported in the package, as @code{#:use-module ((guix licenses)
1159 #:prefix license:)}. The Guile module import mechanism
1160 (@pxref{Using Guile Modules,,, guile, Guile reference manual})
1161 gives the user full control over namespacing: this is needed to avoid
1162 clashes between, say, the
1163 @samp{zlib} variable from @samp{licenses.scm} (a @emph{license} value) and the @samp{zlib} variable
1164 from @samp{compression.scm} (a @emph{package} value).
1165
1166 @node Other build systems
1167 @subsection Other build systems
1168
1169 What we've seen so far covers the majority of packages using a build system
1170 other than the @code{trivial-build-system}. The latter does not automate anything
1171 and leaves you to build everything manually. This can be more demanding and we
1172 won't cover it here for now, but thankfully it is rarely necessary to fall back
1173 on this system.
1174
1175 For the other build systems, such as ASDF, Emacs, Perl, Ruby and many more, the
1176 process is very similar to the GNU build system except for a few specialized
1177 arguments.
1178
1179 @xref{Build Systems,,, guix, GNU Guix Reference Manual}, for more
1180 information on build systems, or check the source code in the
1181 @samp{$GUIX_CHECKOUT/guix/build} and
1182 @samp{$GUIX_CHECKOUT/guix/build-system} directories.
1183
1184 @node Programmable and automated package definition
1185 @subsection Programmable and automated package definition
1186
1187 We can't repeat it enough: having a full-fledged programming language at hand
1188 empowers us in ways that reach far beyond traditional package management.
1189
1190 Let's illustrate this with some awesome features of Guix!
1191
1192 @node Recursive importers
1193 @subsubsection Recursive importers
1194
1195 You might find some build systems good enough that there is little to do at all
1196 to write a package, to the point that it becomes repetitive and tedious after a
1197 while. A @emph{raison d'être} of computers is to replace human beings at those
1198 boring tasks. So let's tell Guix to do this for us and create the package
1199 definition of an R package from CRAN (the output is trimmed for conciseness):
1200
1201 @example
1202 $ guix import cran --recursive walrus
1203
1204 (define-public r-mc2d
1205 ; ...
1206 (license gpl2+)))
1207
1208 (define-public r-jmvcore
1209 ; ...
1210 (license gpl2+)))
1211
1212 (define-public r-wrs2
1213 ; ...
1214 (license gpl3)))
1215
1216 (define-public r-walrus
1217 (package
1218 (name "r-walrus")
1219 (version "1.0.3")
1220 (source
1221 (origin
1222 (method url-fetch)
1223 (uri (cran-uri "walrus" version))
1224 (sha256
1225 (base32
1226 "1nk2glcvy4hyksl5ipq2mz8jy4fss90hx6cq98m3w96kzjni6jjj"))))
1227 (build-system r-build-system)
1228 (propagated-inputs
1229 `(("r-ggplot2" ,r-ggplot2)
1230 ("r-jmvcore" ,r-jmvcore)
1231 ("r-r6" ,r-r6)
1232 ("r-wrs2" ,r-wrs2)))
1233 (home-page "https://github.com/jamovi/walrus")
1234 (synopsis "Robust Statistical Methods")
1235 (description
1236 "This package provides a toolbox of common robust statistical
1237 tests, including robust descriptives, robust t-tests, and robust ANOVA.
1238 It is also available as a module for 'jamovi' (see
1239 <https://www.jamovi.org> for more information). Walrus is based on the
1240 WRS2 package by Patrick Mair, which is in turn based on the scripts and
1241 work of Rand Wilcox. These analyses are described in depth in the book
1242 'Introduction to Robust Estimation & Hypothesis Testing'.")
1243 (license gpl3)))
1244 @end example
1245
1246 The recursive importer won't import packages for which Guix already has package
1247 definitions, except for the very first.
1248
1249 Not all applications can be packaged this way, only those relying on a select
1250 number of supported systems. Read about the full list of importers in
1251 the guix import section of the manual
1252 (@pxref{Invoking guix import,,, guix, GNU Guix Reference Manual}).
1253
1254 @node Automatic update
1255 @subsubsection Automatic update
1256
1257 Guix can be smart enough to check for updates on systems it knows. It can
1258 report outdated package definitions with
1259
1260 @example
1261 $ guix refresh hello
1262 @end example
1263
1264 In most cases, updating a package to a newer version requires little more than
1265 changing the version number and the checksum. Guix can do that automatically as
1266 well:
1267
1268 @example
1269 $ guix refresh hello --update
1270 @end example
1271
1272 @node Inheritance
1273 @subsubsection Inheritance
1274
1275 If you've started browsing the existing package definitions, you might have
1276 noticed that a significant number of them have a @code{inherit} field:
1277
1278 @lisp
1279 (define-public adwaita-icon-theme
1280 (package (inherit gnome-icon-theme)
1281 (name "adwaita-icon-theme")
1282 (version "3.26.1")
1283 (source (origin
1284 (method url-fetch)
1285 (uri (string-append "mirror://gnome/sources/" name "/"
1286 (version-major+minor version) "/"
1287 name "-" version ".tar.xz"))
1288 (sha256
1289 (base32
1290 "17fpahgh5dyckgz7rwqvzgnhx53cx9kr2xw0szprc6bnqy977fi8"))))
1291 (native-inputs
1292 `(("gtk-encode-symbolic-svg" ,gtk+ "bin")))))
1293 @end lisp
1294
1295 All unspecified fields are inherited from the parent package. This is very
1296 convenient to create alternative packages, for instance with different source,
1297 version or compilation options.
1298
1299 @node Getting help
1300 @subsection Getting help
1301
1302 Sadly, some applications can be tough to package. Sometimes they need a patch to
1303 work with the non-standard file system hierarchy enforced by the store.
1304 Sometimes the tests won't run properly. (They can be skipped but this is not
1305 recommended.) Other times the resulting package won't be reproducible.
1306
1307 Should you be stuck, unable to figure out how to fix any sort of packaging
1308 issue, don't hesitate to ask the community for help.
1309
1310 See the @uref{https://www.gnu.org/software/guix/contact/, Guix homepage} for information on the mailing lists, IRC, etc.
1311
1312 @node Conclusion
1313 @subsection Conclusion
1314
1315 This tutorial was a showcase of the sophisticated package management that Guix
1316 boasts. At this point we have mostly restricted this introduction to the
1317 @code{gnu-build-system} which is a core abstraction layer on which more advanced
1318 abstractions are based.
1319
1320 Where do we go from here? Next we ought to dissect the innards of the build
1321 system by removing all abstractions, using the @code{trivial-build-system}: this
1322 should give us a thorough understanding of the process before investigating some
1323 more advanced packaging techniques and edge cases.
1324
1325 Other features worth exploring are the interactive editing and debugging
1326 capabilities of Guix provided by the Guile REPL@.
1327
1328 Those fancy features are completely optional and can wait; now is a good time
1329 to take a well-deserved break. With what we've introduced here you should be
1330 well armed to package lots of programs. You can get started right away and
1331 hopefully we will see your contributions soon!
1332
1333 @node References
1334 @subsection References
1335
1336 @itemize
1337 @item
1338 The @uref{https://www.gnu.org/software/guix/manual/en/html_node/Defining-Packages.html, package reference in the manual}
1339
1340 @item
1341 @uref{https://gitlab.com/pjotrp/guix-notes/blob/master/HACKING.org, Pjotr’s hacking guide to GNU Guix}
1342
1343 @item
1344 @uref{https://www.gnu.org/software/guix/guix-ghm-andreas-20130823.pdf, ``GNU Guix: Package without a scheme!''}, by Andreas Enge
1345 @end itemize
1346
1347 @c *********************************************************************
1348 @node System Configuration
1349 @chapter System Configuration
1350
1351 Guix offers a flexible language for declaratively configuring your Guix
1352 System. This flexibility can at times be overwhelming. The purpose of this
1353 chapter is to demonstrate some advanced configuration concepts.
1354
1355 @pxref{System Configuration,,, guix, GNU Guix Reference Manual} for a complete
1356 reference.
1357
1358 @menu
1359 * Auto-Login to a Specific TTY:: Automatically Login a User to a Specific TTY
1360 * Customizing the Kernel:: Creating and using a custom Linux kernel on Guix System.
1361 * Guix System Image API:: Customizing images to target specific platforms.
1362 * Connecting to Wireguard VPN:: Connecting to a Wireguard VPN.
1363 * Customizing a Window Manager:: Handle customization of a Window manager on Guix System.
1364 * Running Guix on a Linode Server:: Running Guix on a Linode Server
1365 * Setting up a bind mount:: Setting up a bind mount in the file-systems definition.
1366 * Getting substitutes from Tor:: Configuring Guix daemon to get substitutes through Tor.
1367 * Setting up NGINX with Lua:: Configuring NGINX web-server to load Lua modules.
1368 @end menu
1369
1370 @node Auto-Login to a Specific TTY
1371 @section Auto-Login to a Specific TTY
1372
1373 While the Guix manual explains auto-login one user to @emph{all} TTYs (
1374 @pxref{auto-login to TTY,,, guix, GNU Guix Reference Manual}), some
1375 might prefer a situation, in which one user is logged into one TTY with
1376 the other TTYs either configured to login different users or no one at
1377 all. Note that one can auto-login one user to any TTY, but it is
1378 usually advisable to avoid @code{tty1}, which, by default, is used to
1379 log warnings and errors.
1380
1381 Here is how one might set up auto login for one user to one tty:
1382
1383 @lisp
1384 (define (auto-login-to-tty config tty user)
1385 (if (string=? tty (mingetty-configuration-tty config))
1386 (mingetty-configuration
1387 (inherit config)
1388 (auto-login user))
1389 config))
1390
1391 (define %my-services
1392 (modify-services %base-services
1393 ;; @dots{}
1394 (mingetty-service-type config =>
1395 (auto-login-to-tty
1396 config "tty3" "alice"))))
1397
1398 (operating-system
1399 ;; @dots{}
1400 (services %my-services))
1401 @end lisp
1402
1403 One could also @code{compose} (@pxref{Higher-Order Functions,,, guile,
1404 The Guile Reference Manual}) @code{auto-login-to-tty} to login multiple
1405 users to multiple ttys.
1406
1407 Finally, here is a note of caution. Setting up auto login to a TTY,
1408 means that anyone can turn on your computer and run commands as your
1409 regular user.
1410 However, if you have an encrypted root partition, and thus already need
1411 to enter a passphrase when the system boots, auto-login might be a
1412 convenient option.
1413
1414
1415 @node Customizing the Kernel
1416 @section Customizing the Kernel
1417
1418 Guix is, at its core, a source based distribution with substitutes
1419 (@pxref{Substitutes,,, guix, GNU Guix Reference Manual}), and as such building
1420 packages from their source code is an expected part of regular package
1421 installations and upgrades. Given this starting point, it makes sense that
1422 efforts are made to reduce the amount of time spent compiling packages, and
1423 recent changes and upgrades to the building and distribution of substitutes
1424 continues to be a topic of discussion within Guix.
1425
1426 The kernel, while not requiring an overabundance of RAM to build, does take a
1427 rather long time on an average machine. The official kernel configuration, as
1428 is the case with many GNU/Linux distributions, errs on the side of
1429 inclusiveness, and this is really what causes the build to take such a long
1430 time when the kernel is built from source.
1431
1432 The Linux kernel, however, can also just be described as a regular old
1433 package, and as such can be customized just like any other package. The
1434 procedure is a little bit different, although this is primarily due to the
1435 nature of how the package definition is written.
1436
1437 The @code{linux-libre} kernel package definition is actually a procedure which
1438 creates a package.
1439
1440 @lisp
1441 (define* (make-linux-libre version hash supported-systems
1442 #:key
1443 ;; A function that takes an arch and a variant.
1444 ;; See kernel-config for an example.
1445 (extra-version #false)
1446 (configuration-file #false)
1447 (defconfig "defconfig")
1448 (extra-options %default-extra-linux-options)
1449 (patches (list %boot-logo-patch)))
1450 ...)
1451 @end lisp
1452
1453 The current @code{linux-libre} package is for the 5.1.x series, and is
1454 declared like this:
1455
1456 @lisp
1457 (define-public linux-libre
1458 (make-linux-libre %linux-libre-version
1459 %linux-libre-hash
1460 '("x86_64-linux" "i686-linux" "armhf-linux" "aarch64-linux")
1461 #:patches %linux-libre-5.1-patches
1462 #:configuration-file kernel-config))
1463 @end lisp
1464
1465 Any keys which are not assigned values inherit their default value from the
1466 @code{make-linux-libre} definition. When comparing the two snippets above,
1467 you may notice that the code comment in the first doesn't actually refer to
1468 the @code{#:extra-version} keyword; it is actually for
1469 @code{#:configuration-file}. Because of this, it is not actually easy to
1470 include a custom kernel configuration from the definition, but don't worry,
1471 there are other ways to work with what we do have.
1472
1473 There are two ways to create a kernel with a custom kernel configuration. The
1474 first is to provide a standard @file{.config} file during the build process by
1475 including an actual @file{.config} file as a native input to our custom
1476 kernel. The following is a snippet from the custom @code{'configure} phase of
1477 the @code{make-linux-libre} package definition:
1478
1479 @lisp
1480 (let ((build (assoc-ref %standard-phases 'build))
1481 (config (assoc-ref (or native-inputs inputs) "kconfig")))
1482
1483 ;; Use a custom kernel configuration file or a default
1484 ;; configuration file.
1485 (if config
1486 (begin
1487 (copy-file config ".config")
1488 (chmod ".config" #o666))
1489 (invoke "make" ,defconfig)))
1490 @end lisp
1491
1492 Below is a sample kernel package. The @code{linux-libre} package is nothing
1493 special and can be inherited from and have its fields overridden like any
1494 other package:
1495
1496 @lisp
1497 (define-public linux-libre/E2140
1498 (package
1499 (inherit linux-libre)
1500 (native-inputs
1501 `(("kconfig" ,(local-file "E2140.config"))
1502 ,@@(alist-delete "kconfig"
1503 (package-native-inputs linux-libre))))))
1504 @end lisp
1505
1506 In the same directory as the file defining @code{linux-libre-E2140} is a file
1507 named @file{E2140.config}, which is an actual kernel configuration file. The
1508 @code{defconfig} keyword of @code{make-linux-libre} is left blank here, so the
1509 only kernel configuration in the package is the one which was included in the
1510 @code{native-inputs} field.
1511
1512 The second way to create a custom kernel is to pass a new value to the
1513 @code{extra-options} keyword of the @code{make-linux-libre} procedure. The
1514 @code{extra-options} keyword works with another function defined right below
1515 it:
1516
1517 @lisp
1518 (define %default-extra-linux-options
1519 `(;; https://lists.gnu.org/archive/html/guix-devel/2014-04/msg00039.html
1520 ("CONFIG_DEVPTS_MULTIPLE_INSTANCES" . #true)
1521 ;; Modules required for initrd:
1522 ("CONFIG_NET_9P" . m)
1523 ("CONFIG_NET_9P_VIRTIO" . m)
1524 ("CONFIG_VIRTIO_BLK" . m)
1525 ("CONFIG_VIRTIO_NET" . m)
1526 ("CONFIG_VIRTIO_PCI" . m)
1527 ("CONFIG_VIRTIO_BALLOON" . m)
1528 ("CONFIG_VIRTIO_MMIO" . m)
1529 ("CONFIG_FUSE_FS" . m)
1530 ("CONFIG_CIFS" . m)
1531 ("CONFIG_9P_FS" . m)))
1532
1533 (define (config->string options)
1534 (string-join (map (match-lambda
1535 ((option . 'm)
1536 (string-append option "=m"))
1537 ((option . #true)
1538 (string-append option "=y"))
1539 ((option . #false)
1540 (string-append option "=n")))
1541 options)
1542 "\n"))
1543 @end lisp
1544
1545 And in the custom configure script from the `make-linux-libre` package:
1546
1547 @lisp
1548 ;; Appending works even when the option wasn't in the
1549 ;; file. The last one prevails if duplicated.
1550 (let ((port (open-file ".config" "a"))
1551 (extra-configuration ,(config->string extra-options)))
1552 (display extra-configuration port)
1553 (close-port port))
1554
1555 (invoke "make" "oldconfig")
1556 @end lisp
1557
1558 So by not providing a configuration-file the @file{.config} starts blank, and
1559 then we write into it the collection of flags that we want. Here's another
1560 custom kernel:
1561
1562 @lisp
1563 (define %macbook41-full-config
1564 (append %macbook41-config-options
1565 %file-systems
1566 %efi-support
1567 %emulation
1568 (@@@@ (gnu packages linux) %default-extra-linux-options)))
1569
1570 (define-public linux-libre-macbook41
1571 ;; XXX: Access the internal 'make-linux-libre' procedure, which is
1572 ;; private and unexported, and is liable to change in the future.
1573 ((@@@@ (gnu packages linux) make-linux-libre) (@@@@ (gnu packages linux) %linux-libre-version)
1574 (@@@@ (gnu packages linux) %linux-libre-hash)
1575 '("x86_64-linux")
1576 #:extra-version "macbook41"
1577 #:patches (@@@@ (gnu packages linux) %linux-libre-5.1-patches)
1578 #:extra-options %macbook41-config-options))
1579 @end lisp
1580
1581 In the above example @code{%file-systems} is a collection of flags enabling
1582 different file system support, @code{%efi-support} enables EFI support and
1583 @code{%emulation} enables a x86_64-linux machine to act in 32-bit mode also.
1584 @code{%default-extra-linux-options} are the ones quoted above, which had to be
1585 added in since they were replaced in the @code{extra-options} keyword.
1586
1587 This all sounds like it should be doable, but how does one even know which
1588 modules are required for a particular system? Two places that can be helpful
1589 in trying to answer this question is the
1590 @uref{https://wiki.gentoo.org/wiki/Handbook:AMD64/Installation/Kernel, Gentoo
1591 Handbook} and the
1592 @uref{https://www.kernel.org/doc/html/latest/admin-guide/README.html?highlight=localmodconfig,
1593 documentation from the kernel itself}. From the kernel documentation, it
1594 seems that @code{make localmodconfig} is the command we want.
1595
1596 In order to actually run @code{make localmodconfig} we first need to get and
1597 unpack the kernel source code:
1598
1599 @example shell
1600 tar xf $(guix build linux-libre --source)
1601 @end example
1602
1603 Once inside the directory containing the source code run @code{touch .config}
1604 to create an initial, empty @file{.config} to start with. @code{make
1605 localmodconfig} works by seeing what you already have in @file{.config} and
1606 letting you know what you're missing. If the file is blank then you're
1607 missing everything. The next step is to run:
1608
1609 @example shell
1610 guix environment linux-libre -- make localmodconfig
1611 @end example
1612
1613 and note the output. Do note that the @file{.config} file is still empty.
1614 The output generally contains two types of warnings. The first start with
1615 "WARNING" and can actually be ignored in our case. The second read:
1616
1617 @example shell
1618 module pcspkr did not have configs CONFIG_INPUT_PCSPKR
1619 @end example
1620
1621 For each of these lines, copy the @code{CONFIG_XXXX_XXXX} portion into the
1622 @file{.config} in the directory, and append @code{=m}, so in the end it looks
1623 like this:
1624
1625 @example shell
1626 CONFIG_INPUT_PCSPKR=m
1627 CONFIG_VIRTIO=m
1628 @end example
1629
1630 After copying all the configuration options, run @code{make localmodconfig}
1631 again to make sure that you don't have any output starting with ``module''.
1632 After all of these machine specific modules there are a couple more left that
1633 are also needed. @code{CONFIG_MODULES} is necessary so that you can build and
1634 load modules separately and not have everything built into the kernel.
1635 @code{CONFIG_BLK_DEV_SD} is required for reading from hard drives. It is
1636 possible that there are other modules which you will need.
1637
1638 This post does not aim to be a guide to configuring your own kernel however,
1639 so if you do decide to build a custom kernel you'll have to seek out other
1640 guides to create a kernel which is just right for your needs.
1641
1642 The second way to setup the kernel configuration makes more use of Guix's
1643 features and allows you to share configuration segments between different
1644 kernels. For example, all machines using EFI to boot have a number of EFI
1645 configuration flags that they need. It is likely that all the kernels will
1646 share a list of file systems to support. By using variables it is easier to
1647 see at a glance what features are enabled and to make sure you don't have
1648 features in one kernel but missing in another.
1649
1650 Left undiscussed however, is Guix's initrd and its customization. It is
1651 likely that you'll need to modify the initrd on a machine using a custom
1652 kernel, since certain modules which are expected to be built may not be
1653 available for inclusion into the initrd.
1654
1655 @node Guix System Image API
1656 @section Guix System Image API
1657
1658 Historically, Guix System is centered around an @code{operating-system}
1659 structure. This structure contains various fields ranging from the
1660 bootloader and kernel declaration to the services to install.
1661
1662 Depending on the target machine, that can go from a standard
1663 @code{x86_64} machine to a small ARM single board computer such as the
1664 Pine64, the image constraints can vary a lot. The hardware
1665 manufacturers will impose different image formats with various partition
1666 sizes and offsets.
1667
1668 To create images suitable for all those machines, a new abstraction is
1669 necessary: that's the goal of the @code{image} record. This record
1670 contains all the required information to be transformed into a
1671 standalone image, that can be directly booted on any target machine.
1672
1673 @lisp
1674 (define-record-type* <image>
1675 image make-image
1676 image?
1677 (name image-name ;symbol
1678 (default #f))
1679 (format image-format) ;symbol
1680 (target image-target
1681 (default #f))
1682 (size image-size ;size in bytes as integer
1683 (default 'guess))
1684 (operating-system image-operating-system ;<operating-system>
1685 (default #f))
1686 (partitions image-partitions ;list of <partition>
1687 (default '()))
1688 (compression? image-compression? ;boolean
1689 (default #t))
1690 (volatile-root? image-volatile-root? ;boolean
1691 (default #t))
1692 (substitutable? image-substitutable? ;boolean
1693 (default #t)))
1694 @end lisp
1695
1696 This record contains the operating-system to instantiate. The
1697 @code{format} field defines the image type and can be @code{efi-raw},
1698 @code{qcow2} or @code{iso9660} for instance. In the future, it could be
1699 extended to @code{docker} or other image types.
1700
1701 A new directory in the Guix sources is dedicated to images definition. For now
1702 there are four files:
1703
1704 @itemize @bullet
1705 @item @file{gnu/system/images/hurd.scm}
1706 @item @file{gnu/system/images/pine64.scm}
1707 @item @file{gnu/system/images/novena.scm}
1708 @item @file{gnu/system/images/pinebook-pro.scm}
1709 @end itemize
1710
1711 Let's have a look to @file{pine64.scm}. It contains the
1712 @code{pine64-barebones-os} variable which is a minimal definition of an
1713 operating-system dedicated to the @b{Pine A64 LTS} board.
1714
1715 @lisp
1716 (define pine64-barebones-os
1717 (operating-system
1718 (host-name "vignemale")
1719 (timezone "Europe/Paris")
1720 (locale "en_US.utf8")
1721 (bootloader (bootloader-configuration
1722 (bootloader u-boot-pine64-lts-bootloader)
1723 (targets '("/dev/vda"))))
1724 (initrd-modules '())
1725 (kernel linux-libre-arm64-generic)
1726 (file-systems (cons (file-system
1727 (device (file-system-label "my-root"))
1728 (mount-point "/")
1729 (type "ext4"))
1730 %base-file-systems))
1731 (services (cons (service agetty-service-type
1732 (agetty-configuration
1733 (extra-options '("-L")) ; no carrier detect
1734 (baud-rate "115200")
1735 (term "vt100")
1736 (tty "ttyS0")))
1737 %base-services))))
1738 @end lisp
1739
1740 The @code{kernel} and @code{bootloader} fields are pointing to packages
1741 dedicated to this board.
1742
1743 Right below, the @code{pine64-image-type} variable is also defined.
1744
1745 @lisp
1746 (define pine64-image-type
1747 (image-type
1748 (name 'pine64-raw)
1749 (constructor (cut image-with-os arm64-disk-image <>))))
1750 @end lisp
1751
1752 It's using a record we haven't talked about yet, the @code{image-type} record,
1753 defined this way:
1754
1755 @lisp
1756 (define-record-type* <image-type>
1757 image-type make-image-type
1758 image-type?
1759 (name image-type-name) ;symbol
1760 (constructor image-type-constructor)) ;<operating-system> -> <image>
1761 @end lisp
1762
1763 The main purpose of this record is to associate a name to a procedure
1764 transforming an @code{operating-system} to an image. To understand why
1765 it is necessary, let's have a look to the command producing an image
1766 from an @code{operating-system} configuration file:
1767
1768 @example
1769 guix system image my-os.scm
1770 @end example
1771
1772 This command expects an @code{operating-system} configuration but how
1773 should we indicate that we want an image targeting a Pine64 board? We
1774 need to provide an extra information, the @code{image-type}, by passing
1775 the @code{--image-type} or @code{-t} flag, this way:
1776
1777 @example
1778 guix system image --image-type=pine64-raw my-os.scm
1779 @end example
1780
1781 This @code{image-type} parameter points to the @code{pine64-image-type}
1782 defined above. Hence, the @code{operating-system} declared in
1783 @code{my-os.scm} will be applied the @code{(cut image-with-os
1784 arm64-disk-image <>)} procedure to turn it into an image.
1785
1786 The resulting image looks like:
1787
1788 @lisp
1789 (image
1790 (format 'disk-image)
1791 (target "aarch64-linux-gnu")
1792 (operating-system my-os)
1793 (partitions
1794 (list (partition
1795 (inherit root-partition)
1796 (offset root-offset)))))
1797 @end lisp
1798
1799 which is the aggregation of the @code{operating-system} defined in
1800 @code{my-os.scm} to the @code{arm64-disk-image} record.
1801
1802 But enough Scheme madness. What does this image API bring to the Guix user?
1803
1804 One can run:
1805
1806 @example
1807 mathieu@@cervin:~$ guix system --list-image-types
1808 The available image types are:
1809
1810 - pinebook-pro-raw
1811 - pine64-raw
1812 - novena-raw
1813 - hurd-raw
1814 - hurd-qcow2
1815 - qcow2
1816 - uncompressed-iso9660
1817 - efi-raw
1818 - arm64-raw
1819 - arm32-raw
1820 - iso9660
1821 @end example
1822
1823 and by writing an @code{operating-system} file based on
1824 @code{pine64-barebones-os}, you can customize your image to your
1825 preferences in a file (@file{my-pine-os.scm}) like this:
1826
1827 @lisp
1828 (use-modules (gnu services linux)
1829 (gnu system images pine64))
1830
1831 (let ((base-os pine64-barebones-os))
1832 (operating-system
1833 (inherit base-os)
1834 (timezone "America/Indiana/Indianapolis")
1835 (services
1836 (cons
1837 (service earlyoom-service-type
1838 (earlyoom-configuration
1839 (prefer-regexp "icecat|chromium")))
1840 (operating-system-user-services base-os)))))
1841 @end lisp
1842
1843 run:
1844
1845 @example
1846 guix system image --image-type=pine64-raw my-pine-os.scm
1847 @end example
1848
1849 or,
1850
1851 @example
1852 guix system image --image-type=hurd-raw my-hurd-os.scm
1853 @end example
1854
1855 to get an image that can be written directly to a hard drive and booted
1856 from.
1857
1858 Without changing anything to @code{my-hurd-os.scm}, calling:
1859
1860 @example
1861 guix system image --image-type=hurd-qcow2 my-hurd-os.scm
1862 @end example
1863
1864 will instead produce a Hurd QEMU image.
1865
1866 @node Connecting to Wireguard VPN
1867 @section Connecting to Wireguard VPN
1868
1869 To connect to a Wireguard VPN server you need the kernel module to be
1870 loaded in memory and a package providing networking tools that support
1871 it (e.g. @code{wireguard-tools} or @code{network-manager}).
1872
1873 Here is a configuration example for Linux-Libre < 5.6, where the module
1874 is out of tree and need to be loaded manually---following revisions of
1875 the kernel have it built-in and so don't need such configuration:
1876
1877 @lisp
1878 (use-modules (gnu))
1879 (use-service-modules desktop)
1880 (use-package-modules vpn)
1881
1882 (operating-system
1883 ;; …
1884 (services (cons (simple-service 'wireguard-module
1885 kernel-module-loader-service-type
1886 '("wireguard"))
1887 %desktop-services))
1888 (packages (cons wireguard-tools %base-packages))
1889 (kernel-loadable-modules (list wireguard-linux-compat)))
1890 @end lisp
1891
1892 After reconfiguring and restarting your system you can either use
1893 Wireguard tools or NetworkManager to connect to a VPN server.
1894
1895 @subsection Using Wireguard tools
1896
1897 To test your Wireguard setup it is convenient to use @command{wg-quick}.
1898 Just give it a configuration file @command{wg-quick up ./wg0.conf}; or
1899 put that file in @file{/etc/wireguard} and run @command{wg-quick up wg0}
1900 instead.
1901
1902 @quotation Note
1903 Be warned that the author described this command as a: “[…] very quick
1904 and dirty bash script […]”.
1905 @end quotation
1906
1907 @subsection Using NetworkManager
1908
1909 Thanks to NetworkManager support for Wireguard we can connect to our VPN
1910 using @command{nmcli} command. Up to this point this guide assumes that
1911 you're using Network Manager service provided by
1912 @code{%desktop-services}. Ortherwise you need to adjust your services
1913 list to load @code{network-manager-service-type} and reconfigure your
1914 Guix system.
1915
1916 To import your VPN configuration execute nmcli import command:
1917
1918 @example shell
1919 # nmcli connection import type wireguard file wg0.conf
1920 Connection 'wg0' (edbee261-aa5a-42db-b032-6c7757c60fde) successfully added
1921 @end example
1922
1923 This will create a configuration file in
1924 @file{/etc/NetworkManager/wg0.nmconnection}. Next connect to the
1925 Wireguard server:
1926
1927 @example shell
1928 $ nmcli connection up wg0
1929 Connection successfully activated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/6)
1930 @end example
1931
1932 By default NetworkManager will connect automatically on system boot. To
1933 change that behaviour you need to edit your config:
1934
1935 @example shell
1936 # nmcli connection modify wg0 connection.autoconnect no
1937 @end example
1938
1939 For more specific information about NetworkManager and wireguard
1940 @uref{https://blogs.gnome.org/thaller/2019/03/15/wireguard-in-networkmanager/,see
1941 this post by thaller}.
1942
1943 @node Customizing a Window Manager
1944 @section Customizing a Window Manager
1945 @cindex wm
1946
1947 @node StumpWM
1948 @subsection StumpWM
1949 @cindex stumpwm
1950
1951 You could install StumpWM with a Guix system by adding
1952 @code{stumpwm} and optionally @code{`(,stumpwm "lib")}
1953 packages to a system configuration file, e.g.@: @file{/etc/config.scm}.
1954
1955 An example configuration can look like this:
1956
1957 @lisp
1958 (use-modules (gnu))
1959 (use-package-modules wm)
1960
1961 (operating-system
1962 ;; …
1963 (packages (append (list sbcl stumpwm `(,stumpwm "lib"))
1964 %base-packages)))
1965 @end lisp
1966
1967 @cindex stumpwm fonts
1968 By default StumpWM uses X11 fonts, which could be small or pixelated on
1969 your system. You could fix this by installing StumpWM contrib Lisp
1970 module @code{sbcl-ttf-fonts}, adding it to Guix system packages:
1971
1972 @lisp
1973 (use-modules (gnu))
1974 (use-package-modules fonts wm)
1975
1976 (operating-system
1977 ;; …
1978 (packages (append (list sbcl stumpwm `(,stumpwm "lib"))
1979 sbcl-ttf-fonts font-dejavu %base-packages)))
1980 @end lisp
1981
1982 Then you need to add the following code to a StumpWM configuration file
1983 @file{~/.stumpwm.d/init.lisp}:
1984
1985 @lisp
1986 (require :ttf-fonts)
1987 (setf xft:*font-dirs* '("/run/current-system/profile/share/fonts/"))
1988 (setf clx-truetype:+font-cache-filename+ (concat (getenv "HOME") "/.fonts/font-cache.sexp"))
1989 (xft:cache-fonts)
1990 (set-font (make-instance 'xft:font :family "DejaVu Sans Mono" :subfamily "Book" :size 11))
1991 @end lisp
1992
1993 @node Session lock
1994 @subsection Session lock
1995 @cindex sessionlock
1996
1997 Depending on your environment, locking the screen of your session might come built in
1998 or it might be something you have to set up yourself. If you use a desktop environment
1999 like GNOME or KDE, it's usually built in. If you use a plain window manager like
2000 StumpWM or EXWM, you might have to set it up yourself.
2001
2002 @node Xorg
2003 @subsubsection Xorg
2004
2005 If you use Xorg, you can use the utility
2006 @uref{https://www.mankier.com/1/xss-lock, xss-lock} to lock the screen of your session.
2007 xss-lock is triggered by DPMS which since Xorg 1.8 is auto-detected and enabled if
2008 ACPI is also enabled at kernel runtime.
2009
2010 To use xss-lock, you can simple execute it and put it into the background before
2011 you start your window manager from e.g. your @file{~/.xsession}:
2012
2013 @example
2014 xss-lock -- slock &
2015 exec stumpwm
2016 @end example
2017
2018 In this example, xss-lock uses @code{slock} to do the actual locking of the screen when
2019 it determines it's appropriate, like when you suspend your device.
2020
2021 For slock to be allowed to be a screen locker for the graphical session, it needs to
2022 be made setuid-root so it can authenticate users, and it needs a PAM service. This
2023 can be achieved by adding the following service to your @file{config.scm}:
2024
2025 @lisp
2026 (screen-locker-service slock)
2027 @end lisp
2028
2029 If you manually lock your screen, e.g. by directly calling slock when you want to lock
2030 your screen but not suspend it, it's a good idea to notify xss-lock about this so no
2031 confusion occurs. This can be done by executing @code{xset s activate} immediately
2032 before you execute slock.
2033
2034 @node Running Guix on a Linode Server
2035 @section Running Guix on a Linode Server
2036 @cindex linode, Linode
2037
2038 To run Guix on a server hosted by @uref{https://www.linode.com, Linode},
2039 start with a recommended Debian server. We recommend using the default
2040 distro as a way to bootstrap Guix. Create your SSH keys.
2041
2042 @example
2043 ssh-keygen
2044 @end example
2045
2046 Be sure to add your SSH key for easy login to the remote server.
2047 This is trivially done via Linode's graphical interface for adding
2048 SSH keys. Go to your profile and click add SSH Key.
2049 Copy into it the output of:
2050
2051 @example
2052 cat ~/.ssh/<username>_rsa.pub
2053 @end example
2054
2055 Power the Linode down.
2056
2057 In the Linode's Storage tab, resize the Debian disk to be smaller.
2058 30 GB free space is recommended. Then click "Add a disk", and fill
2059 out the form with the following:
2060
2061 @itemize @bullet
2062 @item
2063 Label: "Guix"
2064
2065 @item
2066 Filesystem: ext4
2067
2068 @item
2069 Set it to the remaining size
2070 @end itemize
2071
2072 In the Configurations tab, press "Edit" on the default Debian profile.
2073 Under "Block Device Assignment" click "Add a Device". It should be
2074 @file{/dev/sdc} and you can select the "Guix" disk. Save Changes.
2075
2076 Now "Add a Configuration", with the following:
2077 @itemize @bullet
2078 @item
2079 Label: Guix
2080
2081 @item
2082 Kernel:GRUB 2 (it's at the bottom! This step is @b{IMPORTANT!})
2083
2084 @item
2085 Block device assignment:
2086
2087 @item
2088 @file{/dev/sda}: Guix
2089
2090 @item
2091 @file{/dev/sdb}: swap
2092
2093 @item
2094 Root device: @file{/dev/sda}
2095
2096 @item
2097 Turn off all the filesystem/boot helpers
2098 @end itemize
2099
2100 Now power it back up, booting with the Debian configuration. Once it's
2101 running, ssh to your server via @code{ssh
2102 root@@@var{<your-server-IP-here>}}. (You can find your server IP address in
2103 your Linode Summary section.) Now you can run the "install guix from
2104 @pxref{Binary Installation,,, guix, GNU Guix}" steps:
2105
2106 @example
2107 sudo apt-get install gpg
2108 wget https://sv.gnu.org/people/viewgpg.php?user_id=15145 -qO - | gpg --import -
2109 wget https://git.savannah.gnu.org/cgit/guix.git/plain/etc/guix-install.sh
2110 chmod +x guix-install.sh
2111 ./guix-install.sh
2112 guix pull
2113 @end example
2114
2115 Now it's time to write out a config for the server. The key information
2116 is below. Save the resulting file as @file{guix-config.scm}.
2117
2118 @lisp
2119 (use-modules (gnu)
2120 (guix modules))
2121 (use-service-modules networking
2122 ssh)
2123 (use-package-modules admin
2124 certs
2125 package-management
2126 ssh
2127 tls)
2128
2129 (operating-system
2130 (host-name "my-server")
2131 (timezone "America/New_York")
2132 (locale "en_US.UTF-8")
2133 ;; This goofy code will generate the grub.cfg
2134 ;; without installing the grub bootloader on disk.
2135 (bootloader (bootloader-configuration
2136 (bootloader
2137 (bootloader
2138 (inherit grub-bootloader)
2139 (installer #~(const #true))))))
2140 (file-systems (cons (file-system
2141 (device "/dev/sda")
2142 (mount-point "/")
2143 (type "ext4"))
2144 %base-file-systems))
2145
2146
2147 (swap-devices (list "/dev/sdb"))
2148
2149
2150 (initrd-modules (cons "virtio_scsi" ; Needed to find the disk
2151 %base-initrd-modules))
2152
2153 (users (cons (user-account
2154 (name "janedoe")
2155 (group "users")
2156 ;; Adding the account to the "wheel" group
2157 ;; makes it a sudoer.
2158 (supplementary-groups '("wheel"))
2159 (home-directory "/home/janedoe"))
2160 %base-user-accounts))
2161
2162 (packages (cons* nss-certs ;for HTTPS access
2163 openssh-sans-x
2164 %base-packages))
2165
2166 (services (cons*
2167 (service dhcp-client-service-type)
2168 (service openssh-service-type
2169 (openssh-configuration
2170 (openssh openssh-sans-x)
2171 (password-authentication? #false)
2172 (authorized-keys
2173 `(("janedoe" ,(local-file "janedoe_rsa.pub"))
2174 ("root" ,(local-file "janedoe_rsa.pub"))))))
2175 %base-services)))
2176 @end lisp
2177
2178 Replace the following fields in the above configuration:
2179 @lisp
2180 (host-name "my-server") ; replace with your server name
2181 ; if you chose a linode server outside the U.S., then
2182 ; use tzselect to find a correct timezone string
2183 (timezone "America/New_York") ; if needed replace timezone
2184 (name "janedoe") ; replace with your username
2185 ("janedoe" ,(local-file "janedoe_rsa.pub")) ; replace with your ssh key
2186 ("root" ,(local-file "janedoe_rsa.pub")) ; replace with your ssh key
2187 @end lisp
2188
2189 The last line in the above example lets you log into the server as root
2190 and set the initial root password (see the note at the end of this
2191 recipe about root login). After you have done this, you may
2192 delete that line from your configuration and reconfigure to prevent root
2193 login.
2194
2195 Copy your ssh public key (eg: @file{~/.ssh/id_rsa.pub}) as
2196 @file{@var{<your-username-here>}_rsa.pub} and put
2197 @file{guix-config.scm} in the same directory. In a new terminal run
2198 these commands.
2199
2200 @example
2201 sftp root@@<remote server ip address>
2202 put /path/to/files/<username>_rsa.pub .
2203 put /path/to/files/guix-config.scm .
2204 @end example
2205
2206 In your first terminal, mount the guix drive:
2207
2208 @example
2209 mkdir /mnt/guix
2210 mount /dev/sdc /mnt/guix
2211 @end example
2212
2213 Due to the way we set up the bootloader section of the guix-config.scm,
2214 only the grub configuration file will be installed. So, we need to copy
2215 over some of the other GRUB stuff already installed on the Debian system:
2216
2217 @example
2218 mkdir -p /mnt/guix/boot/grub
2219 cp -r /boot/grub/* /mnt/guix/boot/grub/
2220 @end example
2221
2222 Now initialize the Guix installation:
2223
2224 @example
2225 guix system init guix-config.scm /mnt/guix
2226 @end example
2227
2228 Ok, power it down!
2229 Now from the Linode console, select boot and select "Guix".
2230
2231 Once it boots, you should be able to log in via SSH! (The server config
2232 will have changed though.) You may encounter an error like:
2233
2234 @example
2235 $ ssh root@@<server ip address>
2236 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
2237 @ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @
2238 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
2239 IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
2240 Someone could be eavesdropping on you right now (man-in-the-middle attack)!
2241 It is also possible that a host key has just been changed.
2242 The fingerprint for the ECDSA key sent by the remote host is
2243 SHA256:0B+wp33w57AnKQuHCvQP0+ZdKaqYrI/kyU7CfVbS7R4.
2244 Please contact your system administrator.
2245 Add correct host key in /home/joshua/.ssh/known_hosts to get rid of this message.
2246 Offending ECDSA key in /home/joshua/.ssh/known_hosts:3
2247 ECDSA host key for 198.58.98.76 has changed and you have requested strict checking.
2248 Host key verification failed.
2249 @end example
2250
2251 Either delete @file{~/.ssh/known_hosts} file, or delete the offending line
2252 starting with your server IP address.
2253
2254 Be sure to set your password and root's password.
2255
2256 @example
2257 ssh root@@<remote ip address>
2258 passwd ; for the root password
2259 passwd <username> ; for the user password
2260 @end example
2261
2262 You may not be able to run the above commands at this point. If you
2263 have issues remotely logging into your linode box via SSH, then you may
2264 still need to set your root and user password initially by clicking on
2265 the ``Launch Console'' option in your linode. Choose the ``Glish''
2266 instead of ``Weblish''. Now you should be able to ssh into the machine.
2267
2268 Hooray! At this point you can shut down the server, delete the
2269 Debian disk, and resize the Guix to the rest of the size.
2270 Congratulations!
2271
2272 By the way, if you save it as a disk image right at this point, you'll
2273 have an easy time spinning up new Guix images! You may need to
2274 down-size the Guix image to 6144MB, to save it as an image. Then you
2275 can resize it again to the max size.
2276
2277 @node Setting up a bind mount
2278 @section Setting up a bind mount
2279
2280 To bind mount a file system, one must first set up some definitions
2281 before the @code{operating-system} section of the system definition. In
2282 this example we will bind mount a folder from a spinning disk drive to
2283 @file{/tmp}, to save wear and tear on the primary SSD, without
2284 dedicating an entire partition to be mounted as @file{/tmp}.
2285
2286 First, the source drive that hosts the folder we wish to bind mount
2287 should be defined, so that the bind mount can depend on it.
2288
2289 @lisp
2290 (define source-drive ;; "source-drive" can be named anything you want.
2291 (file-system
2292 (device (uuid "UUID goes here"))
2293 (mount-point "/path-to-spinning-disk-goes-here")
2294 (type "ext4"))) ;; Make sure to set this to the appropriate type for your drive.
2295 @end lisp
2296
2297 The source folder must also be defined, so that guix will know it's not
2298 a regular block device, but a folder.
2299 @lisp
2300 (define (%source-directory) "/path-to-spinning-disk-goes-here/tmp") ;; "source-directory" can be named any valid variable name.
2301 @end lisp
2302
2303 Finally, inside the @code{file-systems} definition, we must add the
2304 mount itself.
2305
2306 @lisp
2307 (file-systems (cons*
2308
2309 ...<other drives omitted for clarity>...
2310
2311 source-drive ;; Must match the name you gave the source drive in the earlier definition.
2312
2313 (file-system
2314 (device (%source-directory)) ;; Make sure "source-directory" matches your earlier definition.
2315 (mount-point "/tmp")
2316 (type "none") ;; We are mounting a folder, not a partition, so this type needs to be "none"
2317 (flags '(bind-mount))
2318 (dependencies (list source-drive)) ;; Ensure "source-drive" matches what you've named the variable for the drive.
2319 )
2320
2321 ...<other drives omitted for clarity>...
2322
2323 ))
2324 @end lisp
2325
2326 @node Getting substitutes from Tor
2327 @section Getting substitutes from Tor
2328
2329 Guix daemon can use a HTTP proxy to get substitutes, here we are
2330 configuring it to get them via Tor.
2331
2332 @quotation Warning
2333 @emph{Not all} Guix daemon's traffic will go through Tor! Only
2334 HTTP/HTTPS will get proxied; FTP, Git protocol, SSH, etc connections
2335 will still go through the clearnet. Again, this configuration isn't
2336 foolproof some of your traffic won't get routed by Tor at all. Use it
2337 at your own risk.
2338
2339 Also note that the procedure described here applies only to package
2340 substitution. When you update your guix distribution with
2341 @command{guix pull}, you still need to use @command{torsocks} if
2342 you want to route the connection to guix's git repository servers
2343 through Tor.
2344 @end quotation
2345
2346 Guix's substitute server is available as a Onion service, if you want
2347 to use it to get your substitutes through Tor configure your system as
2348 follow:
2349
2350 @lisp
2351 (use-modules (gnu))
2352 (use-service-module base networking)
2353
2354 (operating-system
2355
2356 (services
2357 (cons
2358 (service tor-service-type
2359 (tor-configuration
2360 (config-file (plain-file "tor-config"
2361 "HTTPTunnelPort 127.0.0.1:9250"))))
2362 (modify-services %base-services
2363 (guix-service-type
2364 config => (guix-configuration
2365 (inherit config)
2366 ;; ci.guix.gnu.org's Onion service
2367 (substitute-urls "https://bp7o7ckwlewr4slm.onion")
2368 (http-proxy "http://localhost:9250")))))))
2369 @end lisp
2370
2371 This will keep a tor process running that provides a HTTP CONNECT tunnel
2372 which will be used by @command{guix-daemon}. The daemon can use other
2373 protocols than HTTP(S) to get remote resources, request using those
2374 protocols won't go through Tor since we are only setting a HTTP tunnel
2375 here. Note that @code{substitutes-urls} is using HTTPS and not HTTP or
2376 it won't work, that's a limitation of Tor's tunnel; you may want to use
2377 @command{privoxy} instead to avoid such limitations.
2378
2379 If you don't want to always get substitutes through Tor but using it just
2380 some of the times, then skip the @code{guix-configuration}. When you
2381 want to get a substitute from the Tor tunnel run:
2382
2383 @example
2384 sudo herd set-http-proxy guix-daemon http://localhost:9250
2385 guix build --substitute-urls=https://bp7o7ckwlewr4slm.onion …
2386 @end example
2387
2388 @node Setting up NGINX with Lua
2389 @section Setting up NGINX with Lua
2390 @cindex nginx, lua, openresty, resty
2391
2392 NGINX could be extended with Lua scripts.
2393
2394 Guix provides NGINX service with ability to load Lua module and specific
2395 Lua packages, and reply to requests by evaluating Lua scripts.
2396
2397 The following example demonstrates system definition with configuration
2398 to evaluate @file{index.lua} Lua script on HTTP request to
2399 @uref{http://localhost/hello} endpoint:
2400
2401 @example
2402 local shell = require "resty.shell"
2403
2404 local stdin = ""
2405 local timeout = 1000 -- ms
2406 local max_size = 4096 -- byte
2407
2408 local ok, stdout, stderr, reason, status =
2409 shell.run([[/run/current-system/profile/bin/ls /tmp]], stdin, timeout, max_size)
2410
2411 ngx.say(stdout)
2412 @end example
2413
2414 @lisp
2415 (use-modules (gnu))
2416 (use-service-modules #;… web)
2417 (use-package-modules #;… lua)
2418 (operating-system
2419 ;; …
2420 (services
2421 ;; …
2422 (service nginx-service-type
2423 (nginx-configuration
2424 (modules
2425 (list
2426 (file-append nginx-lua-module "/etc/nginx/modules/ngx_http_lua_module.so")))
2427 (lua-package-path (list lua-resty-core
2428 lua-resty-lrucache
2429 lua-resty-signal
2430 lua-tablepool
2431 lua-resty-shell))
2432 (lua-package-cpath (list lua-resty-signal))
2433 (server-blocks
2434 (list (nginx-server-configuration
2435 (server-name '("localhost"))
2436 (listen '("80"))
2437 (root "/etc")
2438 (locations (list
2439 (nginx-location-configuration
2440 (uri "/hello")
2441 (body (list #~(format #f "content_by_lua_file ~s;"
2442 #$(local-file "index.lua"))))))))))))))
2443 @end lisp
2444
2445 @c *********************************************************************
2446 @node Advanced package management
2447 @chapter Advanced package management
2448
2449 Guix is a functional package manager that offers many features beyond
2450 what more traditional package managers can do. To the uninitiated,
2451 those features might not have obvious use cases at first. The purpose
2452 of this chapter is to demonstrate some advanced package management
2453 concepts.
2454
2455 @pxref{Package Management,,, guix, GNU Guix Reference Manual} for a complete
2456 reference.
2457
2458 @menu
2459 * Guix Profiles in Practice:: Strategies for multiple profiles and manifests.
2460 @end menu
2461
2462 @node Guix Profiles in Practice
2463 @section Guix Profiles in Practice
2464
2465 Guix provides a very useful feature that may be quite foreign to newcomers:
2466 @emph{profiles}. They are a way to group package installations together and all users
2467 on the same system are free to use as many profiles as they want.
2468
2469 Whether you're a developer or not, you may find that multiple profiles bring you
2470 great power and flexibility. While they shift the paradigm somewhat compared to
2471 @emph{traditional package managers}, they are very convenient to use once you've
2472 understood how to set them up.
2473
2474 If you are familiar with Python's @samp{virtualenv}, you can think of a profile as a
2475 kind of universal @samp{virtualenv} that can hold any kind of software whatsoever, not
2476 just Python software. Furthermore, profiles are self-sufficient: they capture
2477 all the runtime dependencies which guarantees that all programs within a profile
2478 will always work at any point in time.
2479
2480 Multiple profiles have many benefits:
2481
2482 @itemize
2483 @item
2484 Clean semantic separation of the various packages a user needs for different contexts.
2485
2486 @item
2487 Multiple profiles can be made available into the environment either on login
2488 or within a dedicated shell.
2489
2490 @item
2491 Profiles can be loaded on demand. For instance, the user can use multiple
2492 shells, each of them running different profiles.
2493
2494 @item
2495 Isolation: Programs from one profile will not use programs from the other, and
2496 the user can even install different versions of the same programs to the two
2497 profiles without conflict.
2498
2499 @item
2500 Deduplication: Profiles share dependencies that happens to be the exact same.
2501 This makes multiple profiles storage-efficient.
2502
2503 @item
2504 Reproducible: when used with declarative manifests, a profile can be fully
2505 specified by the Guix commit that was active when it was set up. This means
2506 that the exact same profile can be
2507 @uref{https://guix.gnu.org/blog/2018/multi-dimensional-transactions-and-rollbacks-oh-my/,
2508 set up anywhere and anytime}, with just the commit information. See the
2509 section on @ref{Reproducible profiles}.
2510
2511 @item
2512 Easier upgrades and maintenance: Multiple profiles make it easy to keep
2513 package listings at hand and make upgrades completely frictionless.
2514 @end itemize
2515
2516 Concretely, here follows some typical profiles:
2517
2518 @itemize
2519 @item
2520 The dependencies of a project you are working on.
2521
2522 @item
2523 Your favourite programming language libraries.
2524
2525 @item
2526 Laptop-specific programs (like @samp{powertop}) that you don't need on a desktop.
2527
2528 @item
2529 @TeX{}live (this one can be really useful when you need to install just one
2530 package for this one document you've just received over email).
2531
2532 @item
2533 Games.
2534 @end itemize
2535
2536 Let's dive in the set up!
2537
2538 @node Basic setup with manifests
2539 @subsection Basic setup with manifests
2540
2541 A Guix profile can be set up @emph{via} a so-called @emph{manifest specification} that looks like
2542 this:
2543
2544 @lisp
2545 (specifications->manifest
2546 '("package-1"
2547 ;; Version 1.3 of package-2.
2548 "package-2@@1.3"
2549 ;; The "lib" output of package-3.
2550 "package-3:lib"
2551 ; ...
2552 "package-N"))
2553 @end lisp
2554
2555 @pxref{Invoking guix package,,, guix, GNU Guix Reference Manual}, for
2556 the syntax details.
2557
2558 We can create a manifest specification per profile and install them this way:
2559
2560 @example
2561 GUIX_EXTRA_PROFILES=$HOME/.guix-extra-profiles
2562 mkdir -p "$GUIX_EXTRA_PROFILES"/my-project # if it does not exist yet
2563 guix package --manifest=/path/to/guix-my-project-manifest.scm --profile="$GUIX_EXTRA_PROFILES"/my-project/my-project
2564 @end example
2565
2566 Here we set an arbitrary variable @samp{GUIX_EXTRA_PROFILES} to point to the directory
2567 where we will store our profiles in the rest of this article.
2568
2569 Placing all your profiles in a single directory, with each profile getting its
2570 own sub-directory, is somewhat cleaner. This way, each sub-directory will
2571 contain all the symlinks for precisely one profile. Besides, ``looping over
2572 profiles'' becomes obvious from any programming language (e.g.@: a shell script) by
2573 simply looping over the sub-directories of @samp{$GUIX_EXTRA_PROFILES}.
2574
2575 Note that it's also possible to loop over the output of
2576
2577 @example
2578 guix package --list-profiles
2579 @end example
2580
2581 although you'll probably have to filter out @file{~/.config/guix/current}.
2582
2583 To enable all profiles on login, add this to your @file{~/.bash_profile} (or similar):
2584
2585 @example
2586 for i in $GUIX_EXTRA_PROFILES/*; do
2587 profile=$i/$(basename "$i")
2588 if [ -f "$profile"/etc/profile ]; then
2589 GUIX_PROFILE="$profile"
2590 . "$GUIX_PROFILE"/etc/profile
2591 fi
2592 unset profile
2593 done
2594 @end example
2595
2596 Note to Guix System users: the above reflects how your default profile
2597 @file{~/.guix-profile} is activated from @file{/etc/profile}, that latter being loaded by
2598 @file{~/.bashrc} by default.
2599
2600 You can obviously choose to only enable a subset of them:
2601
2602 @example
2603 for i in "$GUIX_EXTRA_PROFILES"/my-project-1 "$GUIX_EXTRA_PROFILES"/my-project-2; do
2604 profile=$i/$(basename "$i")
2605 if [ -f "$profile"/etc/profile ]; then
2606 GUIX_PROFILE="$profile"
2607 . "$GUIX_PROFILE"/etc/profile
2608 fi
2609 unset profile
2610 done
2611 @end example
2612
2613 When a profile is off, it's straightforward to enable it for an individual shell
2614 without "polluting" the rest of the user session:
2615
2616 @example
2617 GUIX_PROFILE="path/to/my-project" ; . "$GUIX_PROFILE"/etc/profile
2618 @end example
2619
2620 The key to enabling a profile is to @emph{source} its @samp{etc/profile} file. This file
2621 contains shell code that exports the right environment variables necessary to
2622 activate the software contained in the profile. It is built automatically by
2623 Guix and meant to be sourced.
2624 It contains the same variables you would get if you ran:
2625
2626 @example
2627 guix package --search-paths=prefix --profile=$my_profile"
2628 @end example
2629
2630 Once again, see (@pxref{Invoking guix package,,, guix, GNU Guix Reference Manual})
2631 for the command line options.
2632
2633 To upgrade a profile, simply install the manifest again:
2634
2635 @example
2636 guix package -m /path/to/guix-my-project-manifest.scm -p "$GUIX_EXTRA_PROFILES"/my-project/my-project
2637 @end example
2638
2639 To upgrade all profiles, it's easy enough to loop over them. For instance,
2640 assuming your manifest specifications are stored in
2641 @file{~/.guix-manifests/guix-$profile-manifest.scm}, with @samp{$profile} being the name
2642 of the profile (e.g.@: "project1"), you could do the following in Bourne shell:
2643
2644 @example
2645 for profile in "$GUIX_EXTRA_PROFILES"/*; do
2646 guix package --profile="$profile" --manifest="$HOME/.guix-manifests/guix-$profile-manifest.scm"
2647 done
2648 @end example
2649
2650 Each profile has its own generations:
2651
2652 @example
2653 guix package -p "$GUIX_EXTRA_PROFILES"/my-project/my-project --list-generations
2654 @end example
2655
2656 You can roll-back to any generation of a given profile:
2657
2658 @example
2659 guix package -p "$GUIX_EXTRA_PROFILES"/my-project/my-project --switch-generations=17
2660 @end example
2661
2662 Finally, if you want to switch to a profile without inheriting from the
2663 current environment, you can activate it from an empty shell:
2664
2665 @example
2666 env -i $(which bash) --login --noprofile --norc
2667 . my-project/etc/profile
2668 @end example
2669
2670 @node Required packages
2671 @subsection Required packages
2672
2673 Activating a profile essentially boils down to exporting a bunch of
2674 environmental variables. This is the role of the @samp{etc/profile} within the
2675 profile.
2676
2677 @emph{Note: Only the environmental variables of the packages that consume them will
2678 be set.}
2679
2680 For instance, @samp{MANPATH} won't be set if there is no consumer application for man
2681 pages within the profile. So if you need to transparently access man pages once
2682 the profile is loaded, you've got two options:
2683
2684 @itemize
2685 @item
2686 Either export the variable manually, e.g.
2687 @example
2688 export MANPATH=/path/to/profile$@{MANPATH:+:@}$MANPATH
2689 @end example
2690
2691 @item
2692 Or include @samp{man-db} to the profile manifest.
2693 @end itemize
2694
2695 The same is true for @samp{INFOPATH} (you can install @samp{info-reader}),
2696 @samp{PKG_CONFIG_PATH} (install @samp{pkg-config}), etc.
2697
2698 @node Default profile
2699 @subsection Default profile
2700
2701 What about the default profile that Guix keeps in @file{~/.guix-profile}?
2702
2703 You can assign it the role you want. Typically you would install the manifest
2704 of the packages you want to use all the time.
2705
2706 Alternatively, you could keep it ``manifest-less'' for throw-away packages
2707 that you would just use for a couple of days.
2708 This way makes it convenient to run
2709
2710 @example
2711 guix install package-foo
2712 guix upgrade package-bar
2713 @end example
2714
2715 without having to specify the path to a profile.
2716
2717 @node The benefits of manifests
2718 @subsection The benefits of manifests
2719
2720 Manifests are a convenient way to keep your package lists around and, say,
2721 to synchronize them across multiple machines using a version control system.
2722
2723 A common complaint about manifests is that they can be slow to install when they
2724 contain large number of packages. This is especially cumbersome when you just
2725 want get an upgrade for one package within a big manifest.
2726
2727 This is one more reason to use multiple profiles, which happen to be just
2728 perfect to break down manifests into multiple sets of semantically connected
2729 packages. Using multiple, small profiles provides more flexibility and
2730 usability.
2731
2732 Manifests come with multiple benefits. In particular, they ease maintenance:
2733
2734 @itemize
2735 @item
2736 When a profile is set up from a manifest, the manifest itself is
2737 self-sufficient to keep a ``package listing'' around and reinstall the profile
2738 later or on a different system. For ad-hoc profiles, we would need to
2739 generate a manifest specification manually and maintain the package versions
2740 for the packages that don't use the default version.
2741
2742 @item
2743 @code{guix package --upgrade} always tries to update the packages that have
2744 propagated inputs, even if there is nothing to do. Guix manifests remove this
2745 problem.
2746
2747 @item
2748 When partially upgrading a profile, conflicts may arise (due to diverging
2749 dependencies between the updated and the non-updated packages) and they can be
2750 annoying to resolve manually. Manifests remove this problem altogether since
2751 all packages are always upgraded at once.
2752
2753 @item
2754 As mentioned above, manifests allow for reproducible profiles, while the
2755 imperative @code{guix install}, @code{guix upgrade}, etc. do not, since they produce
2756 different profiles every time even when they hold the same packages. See
2757 @uref{https://issues.guix.gnu.org/issue/33285, the related discussion on the matter}.
2758
2759 @item
2760 Manifest specifications are usable by other @samp{guix} commands. For example, you
2761 can run @code{guix weather -m manifest.scm} to see how many substitutes are
2762 available, which can help you decide whether you want to try upgrading today
2763 or wait a while. Another example: you can run @code{guix pack -m manifest.scm} to
2764 create a pack containing all the packages in the manifest (and their
2765 transitive references).
2766
2767 @item
2768 Finally, manifests have a Scheme representation, the @samp{<manifest>} record type.
2769 They can be manipulated in Scheme and passed to the various Guix @uref{https://en.wikipedia.org/wiki/Api, APIs}.
2770 @end itemize
2771
2772 It's important to understand that while manifests can be used to declare
2773 profiles, they are not strictly equivalent: profiles have the side effect that
2774 they ``pin'' packages in the store, which prevents them from being
2775 garbage-collected (@pxref{Invoking guix gc,,, guix, GNU Guix Reference Manual})
2776 and ensures that they will still be available at any point in
2777 the future.
2778
2779 Let's take an example:
2780
2781 @enumerate
2782 @item
2783 We have an environment for hacking on a project for which there isn't a Guix
2784 package yet. We build the environment using a manifest, and then run @code{guix
2785 environment -m manifest.scm}. So far so good.
2786
2787 @item
2788 Many weeks pass and we have run a couple of @code{guix pull} in the mean time.
2789 Maybe a dependency from our manifest has been updated; or we may have run
2790 @code{guix gc} and some packages needed by our manifest have been
2791 garbage-collected.
2792
2793 @item
2794 Eventually, we set to work on that project again, so we run @code{guix environment
2795 -m manifest.scm}. But now we have to wait for Guix to build and install
2796 stuff!
2797 @end enumerate
2798
2799 Ideally, we could spare the rebuild time. And indeed we can, all we need is to
2800 install the manifest to a profile and use @code{GUIX_PROFILE=/the/profile;
2801 . "$GUIX_PROFILE"/etc/profile} as explained above: this guarantees that our
2802 hacking environment will be available at all times.
2803
2804 @emph{Security warning:} While keeping old profiles around can be convenient, keep in
2805 mind that outdated packages may not have received the latest security fixes.
2806
2807 @node Reproducible profiles
2808 @subsection Reproducible profiles
2809
2810 To reproduce a profile bit-for-bit, we need two pieces of information:
2811
2812 @itemize
2813 @item
2814 a manifest,
2815 @item
2816 a Guix channel specification.
2817 @end itemize
2818
2819 Indeed, manifests alone might not be enough: different Guix versions (or
2820 different channels) can produce different outputs for a given manifest.
2821
2822 You can output the Guix channel specification with @samp{guix describe
2823 --format=channels}.
2824 Save this to a file, say @samp{channel-specs.scm}.
2825
2826 On another computer, you can use the channel specification file and the manifest
2827 to reproduce the exact same profile:
2828
2829 @example
2830 GUIX_EXTRA_PROFILES=$HOME/.guix-extra-profiles
2831 GUIX_EXTRA=$HOME/.guix-extra
2832
2833 mkdir "$GUIX_EXTRA"/my-project
2834 guix pull --channels=channel-specs.scm --profile "$GUIX_EXTRA/my-project/guix"
2835
2836 mkdir -p "$GUIX_EXTRA_PROFILES/my-project"
2837 "$GUIX_EXTRA"/my-project/guix/bin/guix package --manifest=/path/to/guix-my-project-manifest.scm --profile="$GUIX_EXTRA_PROFILES"/my-project/my-project
2838 @end example
2839
2840 It's safe to delete the Guix channel profile you've just installed with the
2841 channel specification, the project profile does not depend on it.
2842
2843 @c *********************************************************************
2844 @node Environment management
2845 @chapter Environment management
2846
2847 Guix provides multiple tools to manage environment. This chapter
2848 demonstrate such utilities.
2849
2850 @menu
2851 * Guix environment via direnv:: Setup Guix environment with direnv
2852 @end menu
2853
2854 @node Guix environment via direnv
2855 @section Guix environment via direnv
2856
2857 Guix provides a @samp{direnv} package, which could extend shell after
2858 directory change. This tool could be used to prepare a pure Guix
2859 environment.
2860
2861 The following example provides a shell function for @file{~/.direnvrc}
2862 file, which could be used from Guix Git repository in
2863 @file{~/src/guix/.envrc} file to setup a build environment similar to
2864 described in @pxref{Building from Git,,, guix, GNU Guix Reference
2865 Manual}.
2866
2867 Create a @file{~/.direnvrc} with a Bash code:
2868
2869 @example
2870 # Thanks <https://github.com/direnv/direnv/issues/73#issuecomment-152284914>
2871 export_function()
2872 @{
2873 local name=$1
2874 local alias_dir=$PWD/.direnv/aliases
2875 mkdir -p "$alias_dir"
2876 PATH_add "$alias_dir"
2877 local target="$alias_dir/$name"
2878 if declare -f "$name" >/dev/null; then
2879 echo "#!$SHELL" > "$target"
2880 declare -f "$name" >> "$target" 2>/dev/null
2881 # Notice that we add shell variables to the function trigger.
2882 echo "$name \$*" >> "$target"
2883 chmod +x "$target"
2884 fi
2885 @}
2886
2887 use_guix()
2888 @{
2889 # Set GitHub token.
2890 export GUIX_GITHUB_TOKEN="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
2891
2892 # Unset 'GUIX_PACKAGE_PATH'.
2893 export GUIX_PACKAGE_PATH=""
2894
2895 # Recreate a garbage collector root.
2896 gcroots="$HOME/.config/guix/gcroots"
2897 mkdir -p "$gcroots"
2898 gcroot="$gcroots/guix"
2899 if [ -L "$gcroot" ]
2900 then
2901 rm -v "$gcroot"
2902 fi
2903
2904 # Miscellaneous packages.
2905 PACKAGES_MAINTENANCE=(
2906 direnv
2907 git
2908 git:send-email
2909 git-cal
2910 gnupg
2911 guile-colorized
2912 guile-readline
2913 less
2914 ncurses
2915 openssh
2916 xdot
2917 )
2918
2919 # Environment packages.
2920 PACKAGES=(help2man guile-sqlite3 guile-gcrypt)
2921
2922 # Thanks <https://lists.gnu.org/archive/html/guix-devel/2016-09/msg00859.html>
2923 eval "$(guix environment --search-paths --root="$gcroot" --pure guix --ad-hoc $@{PACKAGES[@@]@} $@{PACKAGES_MAINTENANCE[@@]@} "$@@")"
2924
2925 # Predefine configure flags.
2926 configure()
2927 @{
2928 ./configure --localstatedir=/var --prefix=
2929 @}
2930 export_function configure
2931
2932 # Run make and optionally build something.
2933 build()
2934 @{
2935 make -j 2
2936 if [ $# -gt 0 ]
2937 then
2938 ./pre-inst-env guix build "$@@"
2939 fi
2940 @}
2941 export_function build
2942
2943 # Predefine push Git command.
2944 push()
2945 @{
2946 git push --set-upstream origin
2947 @}
2948 export_function push
2949
2950 clear # Clean up the screen.
2951 git-cal --author='Your Name' # Show contributions calendar.
2952
2953 # Show commands help.
2954 echo "
2955 build build a package or just a project if no argument provided
2956 configure run ./configure with predefined parameters
2957 push push to upstream Git repository
2958 "
2959 @}
2960 @end example
2961
2962 Every project containing @file{.envrc} with a string @code{use guix}
2963 will have predefined environment variables and procedures.
2964
2965 Run @command{direnv allow} to setup the environment for the first time.
2966
2967 @c *********************************************************************
2968 @node Acknowledgments
2969 @chapter Acknowledgments
2970
2971 Guix is based on the @uref{https://nixos.org/nix/, Nix package manager},
2972 which was designed and
2973 implemented by Eelco Dolstra, with contributions from other people (see
2974 the @file{nix/AUTHORS} file in Guix.) Nix pioneered functional package
2975 management, and promoted unprecedented features, such as transactional
2976 package upgrades and rollbacks, per-user profiles, and referentially
2977 transparent build processes. Without this work, Guix would not exist.
2978
2979 The Nix-based software distributions, Nixpkgs and NixOS, have also been
2980 an inspiration for Guix.
2981
2982 GNU@tie{}Guix itself is a collective work with contributions from a
2983 number of people. See the @file{AUTHORS} file in Guix for more
2984 information on these fine people. The @file{THANKS} file lists people
2985 who have helped by reporting bugs, taking care of the infrastructure,
2986 providing artwork and themes, making suggestions, and more---thank you!
2987
2988 This document includes adapted sections from articles that have previously
2989 been published on the Guix blog at @uref{https://guix.gnu.org/blog}.
2990
2991
2992 @c *********************************************************************
2993 @node GNU Free Documentation License
2994 @appendix GNU Free Documentation License
2995 @cindex license, GNU Free Documentation License
2996 @include fdl-1.3.texi
2997
2998 @c *********************************************************************
2999 @node Concept Index
3000 @unnumbered Concept Index
3001 @printindex cp
3002
3003 @bye
3004
3005 @c Local Variables:
3006 @c ispell-local-dictionary: "american";
3007 @c End: