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