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