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