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