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