Próximo: Introdução, Acima: (dir) [Conteúdo][Índice]
Esse documento descreve Guix versão 9356a8c, uma ferramenta de gerenciamento de pacotes funcional escrita para o sistema GNU.
This manual is also available in Simplified Chinese (veja GNU Guix参考手册), French (veja Manuel de référence de GNU Guix), German (veja Referenzhandbuch zu GNU Guix), Spanish (veja Manual de referencia de GNU Guix), Brazilian Portuguese (veja Manual de referência do GNU Guix), and Russian (veja Руководство GNU Guix). If you would like to translate it in your native language, consider joining Weblate (veja Traduzindo o Guix).
guix repl
guix build
guix edit
guix download
guix hash
guix import
guix refresh
guix style
guix lint
guix size
guix graph
guix publish
guix challenge
guix copy
guix container
guix weather
guix processes
operating-system
Referenceguix system
guix deploy
guix home
Próximo: Instalação, Anterior: GNU Guix, Acima: GNU Guix [Conteúdo][Índice]
GNU Guix1 é uma ferramenta de gerenciamento de pacotes e distribuição do sistema GNU. O Guix facilita a instalação, a atualização ou a remoção de pacotes de software, a reversão para um conjunto de pacotes anterior, a compilação de pacotes a partir do código-fonte e geralmente ajuda na criação e manutenção de ambientes de software.
Você pode instalar o GNU Guix sobre um sistema GNU/Linux existente, onde ele complementa as ferramentas disponíveis sem interferência (veja Instalação) ou você pode usá-lo como uma distribuição de sistema operacional independente, Guix System2. Veja Distribuição GNU.
Próximo: Distribuição GNU, Acima: Introdução [Conteúdo][Índice]
Guix provides a command-line package management interface (veja Gerenciamento de pacote), tools to help with software development (veja Desenvolvimento), command-line utilities for more advanced usage (veja Utilitários), as well as Scheme programming interfaces (veja Interface de programação). O build daemon é responsável por compilar pacotes em nome dos usuários (veja Configurando o daemon) e por baixar binários pré-compilados de fontes autorizados (veja Substitutos).
Guix inclui definições de pacotes para muitos pacotes GNU e não-GNU, todos os quais respeitam a liberdade de computação do usuário. É extensível: os usuários podem escrever suas próprias definições de pacotes (veja Definindo pacotes) e disponibilizá-los como módulos de pacotes independentes (veja Módulos de pacote). Também é personalizável: os usuários podem derivar definições de pacotes especializados das existentes, incluindo da linha de comando (veja Opções de transformação de pacote).
Nos bastidores, a Guix implementa a disciplina gerenciamento de pacotes funcional pioneira da Nix (veja Agradecimentos). No Guix, o processo de compilação e instalação de pacotes é visto como uma função, no sentido matemático. Essa função recebe entradas, como scripts de compilação, um compilador e bibliotecas, e retorna um pacote instalado. Como uma função pura, seu resultado depende apenas de suas entradas – por exemplo, não pode fazer referência a um software ou scripts que não foram explicitamente passados como entradas. Uma função de compilação sempre produz o mesmo resultado ao passar por um determinado conjunto de entradas. Não pode alterar o ambiente do sistema em execução de qualquer forma; por exemplo, ele não pode criar, modificar ou excluir arquivos fora de seus diretórios de compilação e instalação. Isto é conseguido através da execução de processos de compilação em ambientes isolados (ou containers), onde somente suas entradas explícitas são visíveis.
O resultado das funções de compilação do pacote é mantido (cached) no sistema de arquivos, em um diretório especial chamado armazém (veja O armazém). Cada pacote é instalado em um diretório próprio no armazém – por padrão, em /gnu/store. O nome do diretório contém um hash de todas as entradas usadas para compilar esse pacote; Assim, a alteração uma entrada gera um nome de diretório diferente.
Essa abordagem é a fundação para os principais recursos do Guix: suporte para atualização transacional de pacotes e reversão, instalação por usuário e coleta de lixo de pacotes (veja Recursos).
Anterior: Gerenciando software do jeito do Guix, Acima: Introdução [Conteúdo][Índice]
O Guix vem com uma distribuição do sistema GNU que consiste inteiramente de software livre3. A distribuição pode ser instalada por conta própria (veja Instalação do sistema), mas também é possível instalar o Guix como um gerenciador de pacotes em cima de um sistema GNU/Linux instalado (veja Instalação). Quando precisamos distinguir entre os dois, nos referimos à distribuição independente como Guix System.
A distribuição fornece pacotes GNU principais, como GNU libc, GCC e
Binutils, além de muitos aplicativos GNU e não GNU. A lista completa de
pacotes disponíveis pode ser acessada
online ou executando
guix package
(veja Invocando guix package
):
guix package --list-available
Nosso objetivo é fornecer uma distribuição prática e 100% de software livre, baseada em Linux e outras variantes do GNU, com foco na promoção e forte integração de componentes do GNU e ênfase em programas e ferramentas que ajudam os usuários a exercer essa liberdade.
Os pacotes estão atualmente disponíveis nas seguintes plataformas:
x86_64-linux
Intel/AMD x86_64
architecture, Linux-Libre kernel.
i686-linux
Intel 32-bit architecture (IA32), Linux-Libre kernel.
armhf-linux
Arquitetura ARMv7-A com hard float, Thumb-2 e NEON, usando a interface binária de aplicativos EABI hard-float (ABI) e o kernel Linux-Libre.
aarch64-linux
little-endian 64-bit ARMv8-A processors, Linux-Libre kernel.
i586-gnu
GNU/Hurd on the Intel 32-bit architecture (IA32).
This configuration is experimental and under development. The easiest way
for you to give it a try is by setting up an instance of
hurd-vm-service-type
on your GNU/Linux machine
(veja hurd-vm-service-type
).
Veja Contribuindo, on how to help!
mips64el-linux (unsupported)
little-endian 64-bit MIPS processors, specifically the Loongson series, n32 ABI, and Linux-Libre kernel. This configuration is no longer fully supported; in particular, there is no ongoing work to ensure that this architecture still works. Should someone decide they wish to revive this architecture then the code is still available.
powerpc-linux (unsupported)
big-endian 32-bit PowerPC processors, specifically the PowerPC G4 with AltiVec support, and Linux-Libre kernel. This configuration is not fully supported and there is no ongoing work to ensure this architecture works.
powerpc64le-linux
little-endian 64-bit Power ISA processors, Linux-Libre kernel. This includes POWER9 systems such as the RYF Talos II mainboard. This platform is available as a "technology preview": although it is supported, substitutes are not yet available from the build farm (veja Substitutos), and some packages may fail to build (veja Rastreando Bugs e Mudanças). That said, the Guix community is actively working on improving this support, and now is a great time to try it and get involved!
riscv64-linux
little-endian 64-bit RISC-V processors, specifically RV64GC, and Linux-Libre kernel. This platform is available as a "technology preview": although it is supported, substitutes are not yet available from the build farm (veja Substitutos), and some packages may fail to build (veja Rastreando Bugs e Mudanças). That said, the Guix community is actively working on improving this support, and now is a great time to try it and get involved!
Com o Guix System, você declara todos os aspectos da configuração do sistema operacional, e o Guix cuida de instanciar a configuração de maneira transacional, reproduzível e sem estado (veja Configuração do sistema). O Guix System usa o kernel Linux-libre, o sistema de inicialização Shepherd (veja Introduction em The GNU Shepherd Manual), os conhecidos utilitários do GNU e cadeia de ferramentas, bem como o ambiente gráfico ou os serviços de sistema do sua escolha.
Guix System is available on all the above platforms except
mips64el-linux
, powerpc-linux
, powerpc64le-linux
and
riscv64-linux
.
Para obter informações sobre como portar para outras arquiteturas ou kernels, veja Portando para uma nova plataforma.
A construção desta distribuição é um esforço cooperativo e você está convidado a participar! Veja Contribuindo, para obter informações sobre como você pode ajudar.
Próximo: Instalação do sistema, Anterior: Introdução, Acima: GNU Guix [Conteúdo][Índice]
You can install the package management tool Guix on top of an existing GNU/Linux or GNU/Hurd system4, referred to as a foreign distro. If, instead, you want to install the complete, standalone GNU system distribution, Guix System, veja Instalação do sistema. This section is concerned only with the installation of Guix on a foreign distro.
Importante: This section only applies to systems without Guix. Following it for existing Guix installations will overwrite important system files.
Quando instalado sobre uma distro alheia. GNU Guix complementa as ferramentas disponíveis sem interferência. Seus dados residem exclusivamente em dois diretórios, geralmente /gnu/store e /var/guix; outros arquivos no seu sistema, como /etc, são deixados intactos.
Uma vez instalado, o Guix pode ser atualizado executando guix pull
(veja Invocando guix pull
).
guix-daemon
Próximo: Configurando o daemon, Acima: Instalação [Conteúdo][Índice]
This section describes how to install Guix from a self-contained tarball providing binaries for Guix and for all its dependencies. This is often quicker than installing from source, described later (veja Compilando do git).
Importante: This section only applies to systems without Guix. Following it for existing Guix installations will overwrite important system files.
Some GNU/Linux distributions, such as Debian, Ubuntu, and openSUSE provide Guix through their own package managers. The version of Guix may be older than 9356a8c but you can update it afterwards by running ‘guix pull’.
We advise system administrators who install Guix, both from the installation
script or via the native package manager of their foreign distribution,
to also regularly read and follow security notices, as shown by
guix pull
.
For Debian or derivatives such as Ubuntu or Trisquel, call:
sudo apt install guix
Likewise, on openSUSE:
sudo zypper install guix
If you are running Parabola, after enabling the pcr (Parabola Community Repo) repository, you can install Guix with:
sudo pacman -S guix
The Guix project also provides a shell script, guix-install.sh, which automates the binary installation process without use of a foreign distro package manager5. Use of guix-install.sh requires Bash, GnuPG, GNU tar, wget, and Xz.
The script guides you through the following:
As root, run:
# cd /tmp # wget https://git.savannah.gnu.org/cgit/guix.git/plain/etc/guix-install.sh # chmod +x guix-install.sh # ./guix-install.sh
The script to install Guix is also packaged in Parabola (in the pcr repository). You can install and run it with:
sudo pacman -S guix-installer sudo guix-install.sh
Nota: By default, guix-install.sh will configure Guix to download pre-built package binaries, called substitutes (veja Substitutos), from the project’s build farms. If you choose not to permit this, Guix will build everything from source, making each installation and upgrade very expensive. Veja Confiança em binários for a discussion of why you may want to build packages from source.
To use substitutes from
bordeaux.guix.gnu.org
,ci.guix.gnu.org
or a mirror, you must authorize them. For example,# guix archive --authorize < \ ~root/.config/guix/current/share/guix/bordeaux.guix.gnu.org.pub # guix archive --authorize < \ ~root/.config/guix/current/share/guix/ci.guix.gnu.org.pub
When you’re done installing Guix, veja Configuração de aplicativo for extra configuration you might need, and Começando for your first steps!
Nota: O tarball da instalação binária pode ser (re)produzido e verificado simplesmente executando o seguinte comando na árvore de código-fonte do Guix:
make guix-binary.system.tar.xz... que, por sua vez, executa:
guix pack -s system --localstatedir \ --profile-name=current-guix guixVeja Invocando
guix pack
, para mais informações sobre essa ferramenta útil.
Should you eventually want to uninstall Guix, run the same script with the --uninstall flag:
./guix-install.sh --uninstall
With --uninstall, the script irreversibly deletes all the Guix files, configuration, and services.
Próximo: Invocando guix-daemon
, Anterior: Instalação de binários, Acima: Instalação [Conteúdo][Índice]
During installation, the build daemon that must be running to use Guix
has already been set up and you can run guix
commands in your
terminal program, veja Começando:
guix build hello
If this runs through without error, feel free to skip this section. You should continue with the following section, Configuração de aplicativo.
However, now would be a good time to replace outdated daemon versions, tweak
it, perform builds on other machines (veja Usando o recurso de descarregamento), or
start it manually in special environments like “chroots” (veja Acessando um sistema existente via chroot) or WSL (not needed for WSL images created with
Guix, veja wsl2-image-type
). If you want to know
more or optimize your system, this section is worth reading.
Operações como compilar um pacote ou executar o coletor de lixo são todas
executadas por um processo especializado, o build daemon, em nome dos
clientes. Apenas o daemon pode acessar o armazém e seu banco de dados
associado. Assim, qualquer operação que manipule o armazém passa pelo
daemon. Por exemplo, ferramentas de linha de comando como guix
package
e guix build
se comunicam com o daemon (via chamadas
de procedimento remoto) para instruir o que fazer.
The following sections explain how to prepare the build daemon’s environment. Veja Substitutos for how to allow the daemon to download pre-built binaries.
Próximo: Usando o recurso de descarregamento, Acima: Configurando o daemon [Conteúdo][Índice]
Em uma configuração multiusuário padrão, o Guix e seu daemon – o programa
guix-daemon
– são instalados pelo administrador do sistema;
/gnu/store é de propriedade de root
e guix-daemon
é
executado como root
. Usuários desprivilegiados podem usar ferramentas
Guix para criar pacotes ou acessar o armazém, e o daemon fará isso em seu
nome, garantindo que o armazém seja mantido em um estado consistente e
permitindo que pacotes construídos sejam compartilhados entre os usuários.
Quando guix-daemon
é executado como root
, você pode não
querer que os próprios processos de compilação de pacotes também sejam
executados como root
, por razões óbvias de segurança. Para evitar
isso, um conjunto especial de usuários de compilação deve ser criado
para uso pelos processos de construção iniciados pelo daemon. Esses usuários
de compilação não precisam ter um shell e um diretório inicial: eles serão
usados apenas quando o daemon der um privilégio root
nos processos de
compilação. Ter vários desses usuários permite que o daemon ative processos
de compilação distintos sob UIDs separados, o que garante que eles não
interfiram uns com os outros - um recurso essencial, pois as compilações são
consideradas funções puras (veja Introdução).
Em um sistema GNU/Linux, um conjunto de usuários de construção pode ser
criado assim (usando a sintaxe Bash e os comandos shadow
):
# groupadd --system guixbuild # for i in $(seq -w 1 10); do useradd -g guixbuild -G guixbuild \ -d /var/empty -s $(which nologin) \ -c "Guix build user $i" --system \ guixbuilder$i; done
O número de usuários de compilação determina quantos trabalhos de compilação
podem ser executados em paralelo, conforme especificado pela opção
--max-jobs (veja --max-jobs). Para usar guix system vm
e comandos
relacionados, você pode precisar adicionar os usuários de compilação ao
grupo kvm
para que eles possam acessar /dev/kvm, usando
-G guixbuild,kvm
em vez de -G guixbuild
(veja Invoking guix system
).
The guix-daemon
program may then be run as root
with the
following command6:
# guix-daemon --build-users-group=guixbuild
Dessa forma, o daemon inicia os processos de compilação em um chroot, sob um
dos usuários guixbuilder
. No GNU/Linux, por padrão, o ambiente chroot
contém nada além de:
/dev
mínimo, criado principalmente independentemente do
/dev
do hospedeiro7;
/proc
; mostra apenas os processos do contêiner desde que
um espaço de nome PID separado é usado;
localhost
para
127.0.0.1
;
The chroot does not contain a /home directory, and the HOME
environment variable is set to the non-existent /homeless-shelter.
This helps to highlight inappropriate uses of HOME
in the build
scripts of packages.
All this usually enough to ensure details of the environment do not influence build processes. In some exceptional cases where more control is needed—typically over the date, kernel, or CPU—you can resort to a virtual build machine (veja virtual build machines).
You can influence the directory where the daemon stores build trees via
the TMPDIR
environment variable. However, the build tree within the
chroot is always called /tmp/guix-build-name.drv-0, where
name is the derivation name—e.g., coreutils-8.24
. This way,
the value of TMPDIR
does not leak inside build environments, which
avoids discrepancies in cases where build processes capture the name of
their build tree.
The daemon also honors the http_proxy
and https_proxy
environment variables for HTTP and HTTPS downloads it performs, be it for
fixed-output derivations (veja Derivações) or for substitutes
(veja Substitutos).
If you are installing Guix as an unprivileged user, it is still possible to
run guix-daemon
provided you pass --disable-chroot.
However, build processes will not be isolated from one another, and not from
the rest of the system. Thus, build processes may interfere with each
other, and may access programs, libraries, and other files available on the
system—making it much harder to view them as pure functions.
Próximo: Suporte a SELinux, Anterior: Configuração do ambiente de compilação, Acima: Configurando o daemon [Conteúdo][Índice]
When desired, the build daemon can offload derivation builds to other
machines running Guix, using the offload
build
hook8.
When that feature is enabled, a list of user-specified build machines is
read from /etc/guix/machines.scm; every time a build is requested,
for instance via guix build
, the daemon attempts to offload it to one
of the machines that satisfy the constraints of the derivation, in
particular its system types—e.g., x86_64-linux
. A single machine
can have multiple system types, either because its architecture natively
supports it, via emulation (veja Transparent
Emulation with QEMU), or both. Missing prerequisites for the build are
copied over SSH to the target machine, which then proceeds with the build;
upon success the output(s) of the build are copied back to the initial
machine. The offload facility comes with a basic scheduler that attempts to
select the best machine. The best machine is chosen among the available
machines based on criteria such as:
parallel-builds
field of its
build-machine
object.
speed
field of its
build-machine
object.
overload-threshold
field of its
build-machine
object.
O arquivo /etc/guix/machines.scm geralmente se parece com isso:
(list (build-machine
(name "eightysix.example.org")
(systems (list "x86_64-linux" "i686-linux"))
(host-key "ssh-ed25519 AAAAC3Nza…")
(user "bob")
(speed 2.)) ;incredibly fast!
(build-machine
(name "armeight.example.org")
(systems (list "aarch64-linux"))
(host-key "ssh-rsa AAAAB3Nza…")
(user "alice")
;; Remember 'guix offload' is spawned by
;; 'guix-daemon' as root.
(private-key "/root/.ssh/identity-for-guix")))
In the example above we specify a list of two build machines, one for the
x86_64
and i686
architectures and one for the aarch64
architecture.
De fato, esse arquivo é – não surpreendentemente! – um arquivo de esquema
que é avaliado quando o hook offload
é iniciado. Seu valor de retorno
deve ser uma lista de objetos de build-machine
. Embora este exemplo
mostre uma lista fixa de máquinas de compilação, pode-se imaginar, digamos,
usando DNS-SD para retornar uma lista de possíveis máquinas de compilação
descobertas na rede local (veja Guile-Avahi em Using Avahi in Guile Scheme Programs). O tipo de dados de
build-machine
está detalhado abaixo.
Esse tipo de dados representa máquinas de compilação nas quais o daemon pode descarregar compilações. Os campos importantes são:
name
O nome de host da máquina remota.
systems
The system types the remote machine supports—e.g., (list
"x86_64-linux" "i686-linux")
.
user
The user account on the remote machine to use when connecting over SSH. Note that the SSH key pair must not be passphrase-protected, to allow non-interactive logins.
host-key
Essa deve ser a SSH chave pública do host da máquina no formato OpenSSH. Isso é usado para autenticar a máquina quando nos conectamos a ela. É uma string longa que se parece com isso:
ssh-ed25519 AAAAC3NzaC…mde+UhL hint@example.org
Se a máquina estiver executando o daemon OpenSSH, sshd
, a chave do
host poderá ser encontrada em um arquivo como
/etc/ssh/ssh_host_ed25519_key.pub.
Se a máquina estiver executando o daemon SSH do GNU lsh,
lshd
, a chave do host estará em /etc/lsh/host-key.pub ou em
um arquivo semelhante. Ele pode ser convertido para o formato OpenSSH usando
o lsh-export-key
(veja Converting keys em LSH Manual):
$ lsh-export-key --openssh < /etc/lsh/host-key.pub ssh-rsa AAAAB3NzaC1yc2EAAAAEOp8FoQAAAQEAs1eB46LV…
Vários campos opcionais podem ser especificados:
port
(padrão: 22
)O número da porta para o servidor SSH na máquina.
private-key
(padrão: ~root/.ssh/id_rsa)O arquivo de chave privada SSH a ser usado ao conectar-se à máquina, no formato OpenSSH. Esta chave não deve ser protegida com uma senha.
Observe que o valor padrão é a chave privada da usuário root. Verifique se ele existe se você usar o padrão.
compression
(padrão: "zlib@openssh.com,zlib"
)compression-level
(padrão: 3
)Os métodos de compactação no nível SSH e o nível de compactação solicitado.
Observe que o descarregamento depende da compactação SSH para reduzir o uso da largura de banda ao transferir arquivos de e para máquinas de compilação.
daemon-socket
(padrão: "/var/guix/daemon-socket/socket"
)O nome do arquivo do soquete do domínio Unix guix-daemon
está
escutando nessa máquina.
overload-threshold
(default: 0.8
)The load threshold above which a potential offload machine is disregarded by
the offload scheduler. The value roughly translates to the total processor
usage of the build machine, ranging from 0.0 (0%) to 1.0 (100%). It can
also be disabled by setting overload-threshold
to #f
.
parallel-builds
(padrão: 1
)O número de compilações que podem ser executadas paralelamente na máquina.
speed
(padrão: 1.0
)Um “fator de velocidade relativo”. O agendador de descarregamento tenderá a preferir máquinas com um fator de velocidade mais alto.
features
(padrão: '()
)Uma lista de strgins que denotam recursos específicos suportados pela
máquina. Um exemplo é "kvm"
para máquinas que possuem os módulos KVM
Linux e o suporte de hardware correspondente. As derivações podem solicitar
recursos pelo nome e serão agendadas nas máquinas de compilação
correspondentes.
Nota: On Guix System, instead of managing /etc/guix/machines.scm independently, you can choose to specify build machines directly in the
operating-system
declaration, in thebuild-machines
field ofguix-configuration
. Vejabuild-machines
field ofguix-configuration
.
O comando guix
deve estar no caminho de pesquisa nas máquinas de
compilação. Você pode verificar se este é o caso executando:
ssh build-machine guix repl --version
Há uma última coisa a fazer quando o machines.scm está em vigor. Como
explicado acima, ao descarregar, os arquivos são transferidos entre os
armazéns das máquinas. Para que isso funcione, primeiro você precisa gerar
um par de chaves em cada máquina para permitir que o daemon exporte arquivos
assinados de arquivos do armazém (veja Invocando guix archive
):
# guix archive --generate-key
Nota: This key pair is not related to the SSH key pair that was previously mentioned in the description of the
build-machine
data type.
Cada máquina de construção deve autorizar a chave da máquina principal para que ela aceite itens do armazém que recebe do mestre:
# guix archive --authorize < master-public-key.txt
Da mesma forma, a máquina principal deve autorizar a chave de cada máquina de compilação.
Todo esse barulho com as chaves está aqui para expressar relações de confiança mútua de pares entre a máquina mestre e as de compilação. Concretamente, quando o mestre recebe arquivos de uma máquina de compilação (e vice-versa), seu daemon de compilação pode garantir que eles sejam genuínos, não tenham sido violados e que sejam assinados por uma chave autorizada.
Para testar se sua configuração está operacional, execute este comando no nó principal:
# guix offload test
This will attempt to connect to each of the build machines specified in /etc/guix/machines.scm, make sure Guix is available on each machine, attempt to export to the machine and import from it, and report any error in the process.
Se você quiser testar um arquivo de máquina diferente, basta especificá-lo na linha de comando:
# guix offload test machines-qualif.scm
Por fim, você pode testar o subconjunto das máquinas cujo nome corresponde a uma expressão regular como esta:
# guix offload test machines.scm '\.gnu\.org$'
Para exibir o carregamento atual de todos os hosts de compilação, execute este comando no nó principal:
# guix offload status
Anterior: Usando o recurso de descarregamento, Acima: Configurando o daemon [Conteúdo][Índice]
O Guix inclui um arquivo de políticas do SELinux em etc/guix-daemon.cil que pode ser instalado em um sistema em que o SELinux está ativado, para rotular os arquivos do Guix e especificar o comportamento esperado do daemon. Como o Guix System não fornece uma política básica do SELinux, a política do daemon não pode ser usada no Guix System.
Nota: The
guix-install.sh
binary installation script offers to perform the steps below for you (veja Instalação de binários).
Para instalar a política, execute esse comando como root:
semodule -i /var/guix/profiles/per-user/root/current-guix/share/selinux/guix-daemon.cil
Then, as root, relabel the file system, possibly after making it writable:
mount -o remount,rw /gnu/store restorecon -R /gnu /var/guix
At this point you can start or restart guix-daemon
; on a
distribution that uses systemd as its service manager, you can do that with:
systemctl restart guix-daemon
Depois que a política é instalada, o sistema de arquivos foi rotulado
novamente e o daemon foi reiniciado, ele deve estar em execução no contexto
guix_daemon_t
. Você pode confirmar isso com o seguinte comando:
ps -Zax | grep guix-daemon
Monitore os arquivos de log do SELinux enquanto executa um comando como
guix build hello
para se convencer de que o SELinux permite todas as
operações necessárias.
Esta política não é perfeita. Aqui está uma lista de limitações ou peculiaridades que devem ser consideradas ao implementar a política SELinux fornecida para o daemon Guix.
guix_daemon_socket_t
isn’t actually used. None of the socket
operations involve contexts that have anything to do with
guix_daemon_socket_t
. It doesn’t hurt to have this unused label, but
it would be preferable to define socket rules for only this label.
guix gc
cannot access arbitrary links to profiles. By design, the
file label of the destination of a symlink is independent of the file label
of the link itself. Although all profiles under $localstatedir are
labelled, the links to these profiles inherit the label of the directory
they are in. For links in the user’s home directory this will be
user_home_t
. But for links from the root user’s home directory, or
/tmp, or the HTTP server’s working directory, etc, this won’t work.
guix gc
would be prevented from reading and following these links.
/gnu/store/.+-(guix-.+|profile)/bin/guix-daemon
recebem o rótulo
guix_daemon_exec_t
; isso significa que qualquer arquivo com
esse nome em qualquer perfil poderá ser executado no domínio de
guix_daemon_t
. Isto não é o ideal. Um invasor pode criar um pacote
que forneça esse executável e convencer um usuário a instalar e executá-lo,
o que o eleva ao domínio de guix_daemon_t
. Nesse ponto, o SELinux não
poderia impedir o acesso a arquivos permitidos para processos nesse domínio.
You will need to relabel the store directory after all upgrades to
guix-daemon, such as after running guix pull
. Assuming the
store is in /gnu, you can do this with restorecon -vR /gnu
, or
by other means provided by your operating system.
Poderíamos gerar uma política muito mais restritiva no momento da
instalação, para que apenas o nome do arquivo exato do executável
guix-daemon
atualmente instalado seja rotulado com
guix_daemon_exec_t
, em vez de usar um amplo expressão regular. A
desvantagem é que o root precisaria instalar ou atualizar a política no
momento da instalação sempre que o pacote Guix que fornece o executável
guix-daemon
em execução efetiva for atualizado.
Próximo: Configuração de aplicativo, Anterior: Configurando o daemon, Acima: Instalação [Conteúdo][Índice]
guix-daemon
O programa guix-daemon
implementa todas as funcionalidades para
acessar o armazém. Isso inclui iniciar processos de compilação, executar o
coletor de lixo, consultar a disponibilidade de um resultado da compilação
etc. É normalmente executado como root
, assim:
# guix-daemon --build-users-group=guixbuild
This daemon can also be started following the systemd “socket activation”
protocol (veja make-systemd-constructor
em The GNU Shepherd Manual).
Para detalhes sobre como configurá-lo, veja Configurando o daemon.
By default, guix-daemon
launches build processes under different
UIDs, taken from the build group specified with
--build-users-group. In addition, each build process is run in a
chroot environment that only contains the subset of the store that the build
process depends on, as specified by its derivation (veja derivation), plus a set of specific system directories. By
default, the latter contains /dev and /dev/pts. Furthermore,
on GNU/Linux, the build environment is a container: in addition to
having its own file system tree, it has a separate mount name space, its own
PID name space, network name space, etc. This helps achieve reproducible
builds (veja Recursos).
When the daemon performs a build on behalf of the user, it creates a build
directory under /tmp or under the directory specified by its
TMPDIR
environment variable. This directory is shared with the
container for the duration of the build, though within the container, the
build tree is always called /tmp/guix-build-name.drv-0.
The build directory is automatically deleted upon completion, unless the build failed and the client specified --keep-failed (veja --keep-failed).
The daemon listens for connections and spawns one sub-process for each
session started by a client (one of the guix
sub-commands). The
guix processes
command allows you to get an overview of the
activity on your system by viewing each of the active sessions and clients.
Veja Invocando guix processes
, for more information.
As seguintes opções de linha de comando são suportadas:
--build-users-group=grupo
Obtém os usuários do grupo para executar os processos de compilação (veja usuários de compilação).
--no-substitutes
¶Não use substitutos para compilar produtos. Ou seja, sempre crie coisas localmente, em vez de permitir downloads de binários pré-compilados (veja Substitutos).
When the daemon runs with --no-substitutes, clients can still
explicitly enable substitution via the set-build-options
remote
procedure call (veja O armazém).
--substitute-urls=urls
Consider urls the default whitespace-separated list of substitute
source URLs. When this option is omitted,
‘https://bordeaux.guix.gnu.org https://ci.guix.gnu.org
’ is used.
Isso significa que os substitutos podem ser baixados de urls, desde que assinados por uma assinatura confiável (veja Substitutos).
Veja Getting Substitutes from Other Servers, for more information on how to configure the daemon to get substitutes from other servers.
--no-offload
Do not use offload builds to other machines (veja Usando o recurso de descarregamento). That is, always build things locally instead of offloading builds to remote machines.
--cache-failures
Armazena em cache as compilações que falharam. Por padrão, apenas compilações bem-sucedidas são armazenadas em cache.
Quando essa opção é usada, o guix gc --list-failures
pode ser
usado para consultar o conjunto de itens do armazém marcados como com falha;
O guix gc --clear-failures
remove os itens do armazém do conjunto
de falhas em cache. Veja Invocando guix gc
.
--cores=n
-c n
Usa n núcleos de CPU para compilar cada derivação; 0
significa
todos disponíveis.
The default value is 0
, but it may be overridden by clients, such as
the --cores option of guix build
(veja Invocando guix build
).
The effect is to define the NIX_BUILD_CORES
environment variable in
the build process, which can then use it to exploit internal
parallelism—for instance, by running make -j$NIX_BUILD_CORES
.
--max-jobs=n
-M n
Permite no máximo n tarefas de compilação em paralelo. O valor padrão
é 1
. Definir como 0
significa que nenhuma compilação será
executada localmente; em vez disso, o daemon descarregará as compilações
(veja Usando o recurso de descarregamento) ou simplesmente falhará.
--max-silent-time=segundos
Quando o processo de compilação ou substituição permanecer em silêncio por mais de segundos, encerra-o e relata uma falha de compilação.
The default value is 3600
(one hour).
The value specified here can be overridden by clients (veja --max-silent-time).
--timeout=segundos
Da mesma forma, quando o processo de compilação ou substituição durar mais que segundos, encerra-o e relata uma falha de compilação.
The default value is 24 hours.
The value specified here can be overridden by clients (veja --timeout).
--rounds=N
Compila cada derivação n vezes seguidas e gera um erro se os
resultados consecutivos da compilação não forem idênticos bit a bit. Observe
que essa configuração pode ser substituída por clientes como guix
build
(veja Invocando guix build
).
Quando usado em conjunto com --keep-failed, uma saída de comparação é mantida no armazém, sob /gnu/store/…-check. Isso facilita procurar por diferenças entre os dois resultados.
--debug
Produz uma saída de depuração.
This is useful to debug daemon start-up issues, but then it may be
overridden by clients, for example the --verbosity option of
guix build
(veja Invocando guix build
).
--chroot-directory=dir
adiciona dir ao chroot de compilação.
Isso pode alterar o resultado dos processos de compilação – por exemplo, se eles usam dependências opcionais encontradas em dir quando estão disponíveis, e não o contrário. Por esse motivo, não é recomendável fazê-lo. Em vez disso, verifique se cada derivação declara todas as entradas necessárias.
--disable-chroot
Desabilita compilações em chroot.
O uso dessa opção não é recomendado, pois, novamente, isso permitiria que os
processos de compilação obtivessem acesso a dependências não
declaradas. Porém, é necessário quando o guix-daemon
está sendo
executado em uma conta de usuário sem privilégios.
--log-compression=tipo
Compacta logs de compilação de aconrdo com tipo, que pode ser um entre
gzip
, bzip2
e none
.
Unless --lose-logs is used, all the build logs are kept in the localstatedir. To save space, the daemon automatically compresses them with gzip by default.
--discover[=yes|no]
Whether to discover substitute servers on the local network using mDNS and DNS-SD.
This feature is still experimental. However, here are a few considerations.
guix publish
on your LAN cannot serve you
malicious binaries, but they can learn what software you’re installing;
It is also possible to enable or disable substitute server discovery at run-time by running:
herd discover guix-daemon on herd discover guix-daemon off
--disable-deduplication
¶Desabilita “deduplicação” automática de arquivos no armazém.
Por padrão, os arquivos adicionados ao armazém são automaticamente “deduplicados”: se um arquivo recém-adicionado for idêntico a outro encontrado no armazém, o daemon tornará o novo arquivo um link físico para o outro arquivo. Isso pode reduzir notavelmente o uso do disco, às custas de um leve aumento na carga de entrada/saída no final de um processo de criação. Esta opção desativa essa otimização.
--gc-keep-outputs[=yes|no]
Diz se o coletor de lixo (GC) deve manter as saídas de derivações vivas.
When set to yes
, the GC will keep the outputs of any live derivation
available in the store—the .drv files. The default is no
,
meaning that derivation outputs are kept only if they are reachable from a
GC root. Veja Invocando guix gc
, for more on GC roots.
--gc-keep-derivations[=yes|no]
Diz se o coletor de lixo (GC) deve manter as derivações correspondentes às saídas vivas.
When set to yes
, as is the case by default, the GC keeps
derivations—i.e., .drv files—as long as at least one of their
outputs is live. This allows users to keep track of the origins of items in
their store. Setting it to no
saves a bit of disk space.
In this way, setting --gc-keep-derivations to yes
causes
liveness to flow from outputs to derivations, and setting
--gc-keep-outputs to yes
causes liveness to flow from
derivations to outputs. When both are set to yes
, the effect is to
keep all the build prerequisites (the sources, compiler, libraries, and
other build-time tools) of live objects in the store, regardless of whether
these prerequisites are reachable from a GC root. This is convenient for
developers since it saves rebuilds or downloads.
--impersonate-linux-2.6
On Linux-based systems, impersonate Linux 2.6. This means that the kernel’s
uname
system call will report 2.6 as the release number.
This might be helpful to build programs that (usually wrongfully) depend on the kernel version number.
--lose-logs
Do not keep build logs. By default they are kept under localstatedir/guix/log.
--system=system
Assume system as the current system type. By default it is the
architecture/kernel pair found at configure time, such as
x86_64-linux
.
--listen=endpoint
Listen for connections on endpoint. endpoint is interpreted as
the file name of a Unix-domain socket if it starts with /
(slash
sign). Otherwise, endpoint is interpreted as a host name or host name
and port to listen to. Here are a few examples:
--listen=/gnu/var/daemon
Listen for connections on the /gnu/var/daemon Unix-domain socket, creating it if needed.
--listen=localhost
¶Listen for TCP connections on the network interface corresponding to
localhost
, on port 44146.
--listen=128.0.0.42:1234
Listen for TCP connections on the network interface corresponding to
128.0.0.42
, on port 1234.
This option can be repeated multiple times, in which case
guix-daemon
accepts connections on all the specified endpoints.
Users can tell client commands what endpoint to connect to by setting the
GUIX_DAEMON_SOCKET
environment variable (veja GUIX_DAEMON_SOCKET
).
Nota: The daemon protocol is unauthenticated and unencrypted. Using --listen=host is suitable on local networks, such as clusters, where only trusted nodes may connect to the build daemon. In other cases where remote access to the daemon is needed, we recommend using Unix-domain sockets along with SSH.
When --listen is omitted, guix-daemon
listens for
connections on the Unix-domain socket located at
localstatedir/guix/daemon-socket/socket.
Próximo: Upgrading Guix, Anterior: Invocando guix-daemon
, Acima: Instalação [Conteúdo][Índice]
Ao usar Guix sobre uma distribuição GNU/Linux que não seja um Guix System — uma chamada distro alheia — algumas etapas adicionais são necessárias para colocar tudo no seu lugar. Aqui estão algumas delas.
Packages installed via Guix will not use the locale data of the host
system. Instead, you must first install one of the locale packages
available with Guix and then define the GUIX_LOCPATH
environment
variable:
$ guix install glibc-locales $ export GUIX_LOCPATH=$HOME/.guix-profile/lib/locale
Note that the glibc-locales
package contains data for all the locales
supported by the GNU libc and weighs in at around
930 MiB9. If
you only need a few locales, you can define your custom locales package via
the make-glibc-utf8-locales
procedure from the (gnu packages
base)
module. The following example defines a package containing the
various Canadian UTF-8 locales known to the GNU libc, that weighs
around 14 MiB:
(use-modules (gnu packages base)) (define my-glibc-locales (make-glibc-utf8-locales glibc #:locales (list "en_CA" "fr_CA" "ik_CA" "iu_CA" "shs_CA") #:name "glibc-canadian-utf8-locales"))
The GUIX_LOCPATH
variable plays a role similar to LOCPATH
(veja LOCPATH
em The GNU C Library Reference
Manual). There are two important differences though:
GUIX_LOCPATH
is honored only by the libc in Guix, and not by the libc
provided by foreign distros. Thus, using GUIX_LOCPATH
allows you to
make sure the programs of the foreign distro will not end up loading
incompatible locale data.
GUIX_LOCPATH
with /X.Y
, where
X.Y
is the libc version—e.g., 2.22
. This means that, should
your Guix profile contain a mixture of programs linked against different
libc version, each libc version will only try to load locale data in the
right format.
This is important because the locale data format used by different libc versions may be incompatible.
Ao usar o Guix em uma distro alheia, nós recomendamos fortemente que
o sistema use o daemon de cache de serviço de nomes da biblioteca C do
GNU, nscd
, que deve ouvir no soquete
/var/run/nscd/socket. Caso não faça isso, os aplicativos instalados
com Guix podem falhar em procurar nomes de máquina e contas de usuário, ou
até mesmo travar. Os próximos parágrafos explicam o porquê.
The GNU C library implements a name service switch (NSS), which is an extensible mechanism for “name lookups” in general: host name resolution, user accounts, and more (veja Name Service Switch em The GNU C Library Reference Manual).
Being extensible, the NSS supports plugins, which provide new name
lookup implementations: for example, the nss-mdns
plugin allow
resolution of .local
host names, the nis
plugin allows user
account lookup using the Network information service (NIS), and so on.
These extra “lookup services” are configured system-wide in
/etc/nsswitch.conf, and all the programs running on the system honor
those settings (veja NSS Configuration File em The GNU C Reference
Manual).
When they perform a name lookup—for instance by calling the
getaddrinfo
function in C—applications first try to connect to the
nscd; on success, nscd performs name lookups on their behalf. If the nscd
is not running, then they perform the name lookup by themselves, by loading
the name lookup services into their own address space and running it. These
name lookup services—the libnss_*.so files—are dlopen
’d,
but they may come from the host system’s C library, rather than from the C
library the application is linked against (the C library coming from Guix).
And this is where the problem is: if your application is linked against
Guix’s C library (say, glibc 2.24) and tries to load NSS plugins from
another C library (say, libnss_mdns.so
for glibc 2.22), it will
likely crash or have its name lookups fail unexpectedly.
Running nscd
on the system, among other advantages, eliminates
this binary incompatibility problem because those libnss_*.so
files
are loaded in the nscd
process, not in applications themselves.
The majority of graphical applications use Fontconfig to locate and load
fonts and perform X11-client-side rendering. The fontconfig
package
in Guix looks for fonts in $HOME/.guix-profile by default. Thus, to
allow graphical applications installed with Guix to display fonts, you have
to install fonts with Guix as well. Essential font packages include
font-ghostscript
, font-dejavu
, and font-gnu-freefont
.
Once you have installed or removed fonts, or when you notice an application that does not find fonts, you may need to install Fontconfig and to force an update of its font cache by running:
guix install fontconfig fc-cache -rv
To display text written in Chinese languages, Japanese, or Korean in
graphical applications, consider installing
font-adobe-source-han-sans
or font-wqy-zenhei
. The former has
multiple outputs, one per language family (veja Pacotes com múltiplas saídas). For instance, the following command installs fonts for Chinese
languages:
guix install font-adobe-source-han-sans:cn
Older programs such as xterm
do not use Fontconfig and instead
rely on server-side font rendering. Such programs require to specify a full
name of a font using XLFD (X Logical Font Description), like this:
-*-dejavu sans-medium-r-normal-*-*-100-*-*-*-*-*-1
To be able to use such full names for the TrueType fonts installed in your Guix profile, you need to extend the font path of the X server:
xset +fp $(dirname $(readlink -f ~/.guix-profile/share/fonts/truetype/fonts.dir))
After that, you can run xlsfonts
(from xlsfonts
package) to
make sure your TrueType fonts are listed there.
The nss-certs
package provides X.509 certificates, which allow
programs to authenticate Web servers accessed over HTTPS.
Ao usar uma Guix em uma distro alheia, você pode instalar esse pacote e definir as variáveis de ambiente relevantes de forma que os pacotes saibam onde procurar por certificados. Veja Certificados X.509, para informações detalhadas.
When you install Emacs packages with Guix, the Elisp files are placed under
the share/emacs/site-lisp/ directory of the profile in which they are
installed. The Elisp libraries are made available to Emacs through the
EMACSLOADPATH
environment variable, which is set when installing Emacs
itself.
Additionally, autoload definitions are automatically evaluated at the
initialization of Emacs, by the Guix-specific
guix-emacs-autoload-packages
procedure. This procedure can be
interactively invoked to have newly installed Emacs packages discovered,
without having to restart Emacs. If, for some reason, you want to avoid
auto-loading the Emacs packages installed with Guix, you can do so by
running Emacs with the --no-site-file option (veja Init File em The GNU Emacs Manual).
Nota: Most Emacs variants are now capable of doing native compilation. The approach taken by Guix Emacs however differs greatly from the approach taken upstream.
Upstream Emacs compiles packages just-in-time and typically places shared object files in a special folder within your
user-emacs-directory
. These shared objects within said folder are organized in a flat hierarchy, and their file names contain two hashes to verify the original file name and contents of the source code.Guix Emacs on the other hand prefers to compile packages ahead-of-time. Shared objects retain much of the original file name and no hashes are added to verify the original file name or the contents of the file. Crucially, this allows Guix Emacs and packages built against it to be grafted (veja grafts), but at the same time, Guix Emacs lacks the hash-based verification of source code baked into upstream Emacs. As this naming schema is trivial to exploit, we disable just-in-time compilation.
Further note, that
emacs-minimal
—the default Emacs for building packages—has been configured without native compilation. To natively compile your emacs packages ahead of time, use a transformation like --with-input=emacs-minimal=emacs.
Anterior: Configuração de aplicativo, Acima: Instalação [Conteúdo][Índice]
To upgrade Guix, run:
guix pull
Veja Invocando guix pull
, for more information.
On a foreign distro, you can upgrade the build daemon by running:
sudo -i guix pull
followed by (assuming your distro uses the systemd service management tool):
systemctl restart guix-daemon.service
On Guix System, upgrading the daemon is achieved by reconfiguring the system
(veja guix system reconfigure
).
Próximo: Começando, Anterior: Instalação, Acima: GNU Guix [Conteúdo][Índice]
This section explains how to install Guix System on a machine. Guix, as a package manager, can also be installed on top of a running GNU/Linux system, veja Instalação.
Próximo: Considerações de Hardware, Acima: Instalação do sistema [Conteúdo][Índice]
We consider Guix System to be ready for a wide range of “desktop” and server use cases. The reliability guarantees it provides—transactional upgrades and rollbacks, reproducibility—make it a solid foundation.
More and more system services are provided (veja Serviços).
Nevertheless, before you proceed with the installation, be aware that some services you rely on may still be missing from version 9356a8c.
More than a disclaimer, this is an invitation to report issues (and success stories!), and to join us in improving it. Veja Contribuindo, for more info.
Próximo: Instalação em um pendrive e em DVD, Anterior: Limitações, Acima: Instalação do sistema [Conteúdo][Índice]
GNU Guix focuses on respecting the user’s computing freedom. It builds around the kernel Linux-libre, which means that only hardware for which free software drivers and firmware exist is supported. Nowadays, a wide range of off-the-shelf hardware is supported on GNU/Linux-libre—from keyboards to graphics cards to scanners and Ethernet controllers. Unfortunately, there are still areas where hardware vendors deny users control over their own computing, and such hardware is not supported on Guix System.
One of the main areas where free drivers or firmware are lacking is WiFi
devices. WiFi devices known to work include those using Atheros chips
(AR9271 and AR7010), which corresponds to the ath9k
Linux-libre
driver, and those using Broadcom/AirForce chips (BCM43xx with Wireless-Core
Revision 5), which corresponds to the b43-open
Linux-libre driver.
Free firmware exists for both and is available out-of-the-box on Guix
System, as part of %base-firmware
(veja firmware
).
The installer warns you early on if it detects devices that are known not to work due to the lack of free firmware or free drivers.
The Free Software Foundation runs Respects Your Freedom (RYF), a certification program for hardware products that respect your freedom and your privacy and ensure that you have control over your device. We encourage you to check the list of RYF-certified devices.
Another useful resource is the H-Node web site. It contains a catalog of hardware devices with information about their support in GNU/Linux.
Próximo: Preparando para instalação, Anterior: Considerações de Hardware, Acima: Instalação do sistema [Conteúdo][Índice]
An ISO-9660 installation image that can be written to a USB stick or burnt
to a DVD can be downloaded from
‘https://ftp.gnu.org/gnu/guix/guix-system-install-9356a8c.x86_64-linux.iso
’,
where you can replace x86_64-linux
with one of:
x86_64-linux
for a GNU/Linux system on Intel/AMD-compatible 64-bit CPUs;
i686-linux
for a 32-bit GNU/Linux system on Intel-compatible CPUs.
Make sure to download the associated .sig file and to verify the authenticity of the image against it, along these lines:
$ wget https://ftp.gnu.org/gnu/guix/guix-system-install-9356a8c.x86_64-linux.iso.sig $ gpg --verify guix-system-install-9356a8c.x86_64-linux.iso.sig
Se esse comando falhar porque você não possui a chave pública requerida, execute este comando para importá-lo:
$ wget https://sv.gnu.org/people/viewgpg.php?user_id=15145 \ -qO - | gpg --import -
e execute novamente o comando gpg --verify
.
Take note that a warning like “This key is not certified with a trusted signature!” is normal.
This image contains the tools necessary for an installation. It is meant to be copied as is to a large-enough USB stick or DVD.
Insert a USB stick of 1 GiB or more into your machine, and determine its device name. Assuming that the USB stick is known as /dev/sdX, copy the image with:
dd if=guix-system-install-9356a8c.x86_64-linux.iso of=/dev/sdX status=progress sync
Access to /dev/sdX usually requires root privileges.
Insert a blank DVD into your machine, and determine its device name. Assuming that the DVD drive is known as /dev/srX, copy the image with:
growisofs -dvd-compat -Z /dev/srX=guix-system-install-9356a8c.x86_64-linux.iso
Access to /dev/srX usually requires root privileges.
Once this is done, you should be able to reboot the system and boot from the
USB stick or DVD. The latter usually requires you to get in the BIOS or
UEFI boot menu, where you can choose to boot from the USB stick. In order
to boot from Libreboot, switch to the command mode by pressing the c
key and type search_grub usb
.
Sadly, on some machines, the installation medium cannot be properly booted and you only see a black screen after booting even after you waited for ten minutes. This may indicate that your machine cannot run Guix System; perhaps you instead want to install Guix on a foreign distro (veja Instalação de binários). But don’t give up just yet; a possible workaround is pressing the e key in the GRUB boot menu and appending nomodeset to the Linux bootline. Sometimes the black screen issue can also be resolved by connecting a different display.
Veja Installing Guix in a Virtual Machine, if, instead, you would like to install Guix System in a virtual machine (VM).
Próximo: Instalação gráfica guiada, Anterior: Instalação em um pendrive e em DVD, Acima: Instalação do sistema [Conteúdo][Índice]
Once you have booted, you can use the guided graphical installer, which makes it easy to get started (veja Instalação gráfica guiada). Alternatively, if you are already familiar with GNU/Linux and if you want more control than what the graphical installer provides, you can choose the “manual” installation process (veja Instalação manual).
The graphical installer is available on TTY1. You can obtain root shells on TTYs 3 to 6 by hitting ctrl-alt-f3, ctrl-alt-f4, etc. TTY2 shows this documentation and you can reach it with ctrl-alt-f2. Documentation is browsable using the Info reader commands (veja Stand-alone GNU Info). The installation system runs the GPM mouse daemon, which allows you to select text with the left mouse button and to paste it with the middle button.
Nota: Installation requires access to the Internet so that any missing dependencies of your system configuration can be downloaded. See the “Networking” section below.
Próximo: Instalação manual, Anterior: Preparando para instalação, Acima: Instalação do sistema [Conteúdo][Índice]
The graphical installer is a text-based user interface. It will guide you, with dialog boxes, through the steps needed to install GNU Guix System.
The first dialog boxes allow you to set up the system as you use it during the installation: you can choose the language, keyboard layout, and set up networking, which will be used during the installation. The image below shows the networking dialog.
Later steps allow you to partition your hard disk, as shown in the image below, to choose whether or not to use encrypted file systems, to enter the host name and root password, and to create an additional account, among other things.
Note that, at any time, the installer allows you to exit the current installation step and resume at a previous step, as show in the image below.
Once you’re done, the installer produces an operating system configuration and displays it (veja Usando o sistema de configuração). At that point you can hit “OK” and installation will proceed. On success, you can reboot into the new system and enjoy. Veja Após a instalação do sistema, for what’s next!
Próximo: Após a instalação do sistema, Anterior: Instalação gráfica guiada, Acima: Instalação do sistema [Conteúdo][Índice]
This section describes how you would “manually” install GNU Guix System on your machine. This option requires familiarity with GNU/Linux, with the shell, and with common administration tools. If you think this is not for you, consider using the guided graphical installer (veja Instalação gráfica guiada).
The installation system provides root shells on TTYs 3 to 6; press
ctrl-alt-f3, ctrl-alt-f4, and so on to reach them. It includes
many common tools needed to install the system, but is also a full-blown
Guix System. This means that you can install additional packages, should
you need it, using guix package
(veja Invocando guix package
).
Próximo: Prosseguindo com a instalação, Acima: Instalação manual [Conteúdo][Índice]
Before you can install the system, you may want to adjust the keyboard layout, set up networking, and partition your target hard disk. This section will guide you through this.
The installation image uses the US qwerty keyboard layout. If you want to
change it, you can use the loadkeys
command. For example, the
following command selects the Dvorak keyboard layout:
loadkeys dvorak
See the files under /run/current-system/profile/share/keymaps for a
list of available keyboard layouts. Run man loadkeys
for more
information.
Run the following command to see what your network interfaces are called:
ifconfig -a
… or, using the GNU/Linux-specific ip
command:
ip address
Wired interfaces have a name starting with ‘e’; for example, the interface corresponding to the first on-board Ethernet controller is called ‘eno1’. Wireless interfaces have a name starting with ‘w’, like ‘w1p2s0’.
To configure a wired network run the following command, substituting interface with the name of the wired interface you want to use.
ifconfig interface up
… or, using the GNU/Linux-specific ip
command:
ip link set interface up
To configure wireless networking, you can create a configuration file for
the wpa_supplicant
configuration tool (its location is not
important) using one of the available text editors such as nano
:
nano wpa_supplicant.conf
As an example, the following stanza can go to this file and will work for many wireless networks, provided you give the actual SSID and passphrase for the network you are connecting to:
network={ ssid="my-ssid" key_mgmt=WPA-PSK psk="the network's secret passphrase" }
Start the wireless service and run it in the background with the following command (substitute interface with the name of the network interface you want to use):
wpa_supplicant -c wpa_supplicant.conf -i interface -B
Run man wpa_supplicant
for more information.
At this point, you need to acquire an IP address. On a network where IP addresses are automatically assigned via DHCP, you can run:
dhclient -v interface
Try to ping a server to see if networking is up and running:
ping -c 3 gnu.org
Setting up network access is almost always a requirement because the image does not contain all the software and tools that may be needed.
If you need HTTP and HTTPS access to go through a proxy, run the following command:
herd set-http-proxy guix-daemon URL
where URL is the proxy URL, for example
http://example.org:8118
.
If you want to, you can continue the installation remotely by starting an SSH server:
herd start ssh-daemon
Make sure to either set a password with passwd
, or configure
OpenSSH public key authentication before logging in.
Unless this has already been done, the next step is to partition, and then format the target partition(s).
The installation image includes several partitioning tools, including Parted
(veja Overview em GNU Parted User Manual), fdisk
, and
cfdisk
. Run it and set up your disk with the partition layout you
want:
cfdisk
If your disk uses the GUID Partition Table (GPT) format and you plan to install BIOS-based GRUB (which is the default), make sure a BIOS Boot Partition is available (veja BIOS installation em GNU GRUB manual).
If you instead wish to use EFI-based GRUB, a FAT32 EFI System
Partition (ESP) is required. This partition can be mounted at
/boot/efi for instance and must have the esp
flag set. E.g.,
for parted
:
parted /dev/sda set 1 esp on
Nota: Unsure whether to use EFI- or BIOS-based GRUB? If the directory /sys/firmware/efi exists in the installation image, then you should probably perform an EFI installation, using
grub-efi-bootloader
. Otherwise you should use the BIOS-based GRUB, known asgrub-bootloader
. Veja Configuração do carregador de inicialização, for more info on bootloaders.
Once you are done partitioning the target hard disk drive, you have to create a file system on the relevant partition(s)10. For the ESP, if you have one and assuming it is /dev/sda1, run:
mkfs.fat -F32 /dev/sda1
For the root file system, ext4 is the most widely used format. Other file systems, such as Btrfs, support compression, which is reported to nicely complement file deduplication that the daemon performs independently of the file system (veja deduplication).
Preferably, assign file systems a label so that you can easily and reliably
refer to them in file-system
declarations (veja Sistemas de arquivos).
This is typically done using the -L
option of mkfs.ext4
and
related commands. So, assuming the target root partition lives at
/dev/sda2, a file system with the label my-root
can be created
with:
mkfs.ext4 -L my-root /dev/sda2
If you are instead planning to encrypt the root partition, you can use the
Cryptsetup/LUKS utilities to do that (see man cryptsetup
for more information).
Assuming you want to store the root partition on /dev/sda2, the command sequence to format it as a LUKS partition would be along these lines:
cryptsetup luksFormat /dev/sda2 cryptsetup open /dev/sda2 my-partition mkfs.ext4 -L my-root /dev/mapper/my-partition
Once that is done, mount the target file system under /mnt with a
command like (again, assuming my-root
is the label of the root file
system):
mount LABEL=my-root /mnt
Also mount any other file systems you would like to use on the target system
relative to this path. If you have opted for /boot/efi as an EFI
mount point for example, mount it at /mnt/boot/efi now so it is found
by guix system init
afterwards.
Finally, if you plan to use one or more swap partitions (veja Swap Space), make sure to initialize them with mkswap
. Assuming you
have one swap partition on /dev/sda3, you would run:
mkswap /dev/sda3 swapon /dev/sda3
Alternatively, you may use a swap file. For example, assuming that in the new system you want to use the file /swapfile as a swap file, you would run11:
# This is 10 GiB of swap space. Adjust "count" to change the size. dd if=/dev/zero of=/mnt/swapfile bs=1MiB count=10240 # For security, make the file readable and writable only by root. chmod 600 /mnt/swapfile mkswap /mnt/swapfile swapon /mnt/swapfile
Note that if you have encrypted the root partition and created a swap file in its file system as described above, then the encryption also protects the swap file, just like any other file in that file system.
Anterior: Keyboard Layout, Networking, and Partitioning, Acima: Instalação manual [Conteúdo][Índice]
With the target partitions ready and the target root mounted on /mnt, we’re ready to go. First, run:
herd start cow-store /mnt
This makes /gnu/store copy-on-write, such that packages added to it
during the installation phase are written to the target disk on /mnt
rather than kept in memory. This is necessary because the first phase of
the guix system init
command (see below) entails downloads or
builds to /gnu/store which, initially, is an in-memory file system.
Next, you have to edit a file and provide the declaration of the operating
system to be installed. To that end, the installation system comes with
three text editors. We recommend GNU nano (veja GNU nano
Manual), which supports syntax highlighting and parentheses matching; other
editors include mg (an Emacs clone), and nvi (a clone of the original BSD
vi
editor). We strongly recommend storing that file on the target
root file system, say, as /mnt/etc/config.scm. Failing to do that,
you will have lost your configuration file once you have rebooted into the
newly-installed system.
Veja Usando o sistema de configuração, for an overview of the configuration file. The example configurations discussed in that section are available under /etc/configuration in the installation image. Thus, to get started with a system configuration providing a graphical display server (a “desktop” system), you can run something along these lines:
# mkdir /mnt/etc # cp /etc/configuration/desktop.scm /mnt/etc/config.scm # nano /mnt/etc/config.scm
You should pay attention to what your configuration file contains, and in particular:
bootloader-configuration
form refers to the targets you
want to install GRUB on. It should mention grub-bootloader
if you
are installing GRUB in the legacy way, or grub-efi-bootloader
for
newer UEFI systems. For legacy systems, the targets
field contain
the names of the devices, like (list "/dev/sda")
; for UEFI systems it
names the paths to mounted EFI partitions, like (list "/boot/efi")
;
do make sure the paths are currently mounted and a file-system
entry
is specified in your configuration.
device
fields in your file-system
configuration, assuming your
file-system
configuration uses the file-system-label
procedure
in its device
field.
mapped-devices
field to describe them (veja Dispositivos mapeados).
Once you are done preparing the configuration file, the new system must be initialized (remember that the target root file system is mounted under /mnt):
guix system init /mnt/etc/config.scm /mnt
This copies all the necessary files and installs GRUB on /dev/sdX,
unless you pass the --no-bootloader option. For more information,
veja Invoking guix system
. This command may trigger downloads or builds
of missing packages, which can take some time.
Após a conclusão desse comando – e esperamos que com sucesso! – você pode
executar o comando reboot
e inicializar no novo sistema. A senha
root
no novo sistema está inicialmente vazia; as senhas de outros
usuários precisam ser inicializadas executando o comando passwd
como root
, a menos que sua configuração especifique o contrário
(veja senhas de contas de usuário). Veja Após a instalação do sistema, para o que vem a seguir!
Próximo: Installing Guix in a Virtual Machine, Anterior: Instalação manual, Acima: Instalação do sistema [Conteúdo][Índice]
Success, you’ve now booted into Guix System! You can upgrade the system whenever you want by running:
guix pull sudo guix system reconfigure /etc/config.scm
This builds a new system generation with the latest packages and services.
Now, veja Começando, and join us on #guix
on
the Libera.Chat IRC network or on guix-devel@gnu.org to share your
experience!
Próximo: Compilando a imagem de instalação, Anterior: Após a instalação do sistema, Acima: Instalação do sistema [Conteúdo][Índice]
If you’d like to install Guix System in a virtual machine (VM) or on a virtual private server (VPS) rather than on your beloved machine, this section is for you.
To boot a QEMU VM for installing Guix System in a disk image, follow these steps:
qemu-img
command:
qemu-img create -f qcow2 guix-system.img 50G
The resulting file will be much smaller than 50 GB (typically less than 1 MB), but it will grow as the virtualized storage device is filled up.
qemu-system-x86_64 -m 1024 -smp 1 -enable-kvm \ -nic user,model=virtio-net-pci -boot menu=on,order=d \ -drive file=guix-system.img \ -drive media=cdrom,readonly=on,file=guix-system-install-9356a8c.system.iso
-enable-kvm
is optional, but significantly improves performance,
veja Usando o Guix em uma Máquina Virtual.
Once installation is complete, you can boot the system that’s on your guix-system.img image. Veja Usando o Guix em uma Máquina Virtual, for how to do that.
Anterior: Installing Guix in a Virtual Machine, Acima: Instalação do sistema [Conteúdo][Índice]
The installation image described above was built using the guix
system
command, specifically:
guix system image -t iso9660 gnu/system/install.scm
Have a look at gnu/system/install.scm in the source tree, and see
also Invoking guix system
for more information about the installation
image.
Many ARM boards require a specific variant of the U-Boot bootloader.
If you build a disk image and the bootloader is not available otherwise (on another boot drive etc), it’s advisable to build an image that includes the bootloader, specifically:
guix system image --system=armhf-linux -e '((@ (gnu system install) os-with-u-boot) (@ (gnu system install) installation-os) "A20-OLinuXino-Lime2")'
A20-OLinuXino-Lime2
is the name of the board. If you specify an
invalid board, a list of possible boards will be printed.
Próximo: Gerenciamento de pacote, Anterior: Instalação do sistema, Acima: GNU Guix [Conteúdo][Índice]
Presumably, you’ve reached this section because either you have installed Guix on top of another distribution (veja Instalação), or you’ve installed the standalone Guix System (veja Instalação do sistema). It’s time for you to get started using Guix and this section aims to help you do that and give you a feel of what it’s like.
Guix is about installing software, so probably the first thing you’ll want to do is to actually look for software. Let’s say you’re looking for a text editor, you can run:
guix search text editor
This command shows you a number of matching packages, each time showing the package’s name, version, a description, and additional info. Once you’ve found out the one you want to use, let’s say Emacs (ah ha!), you can go ahead and install it (run this command as a regular user, no need for root privileges!):
guix install emacs
You’ve installed your first package, congrats! The package is now visible in your default profile, $HOME/.guix-profile—a profile is a directory containing installed packages. In the process, you’ve probably noticed that Guix downloaded pre-built binaries; or, if you explicitly chose to not use pre-built binaries, then probably Guix is still building software (veja Substitutos, for more info).
Unless you’re using Guix System, the guix install
command must
have printed this hint:
hint: Consider setting the necessary environment variables by running: GUIX_PROFILE="$HOME/.guix-profile" . "$GUIX_PROFILE/etc/profile" Alternately, see `guix package --search-paths -p "$HOME/.guix-profile"'.
Indeed, you must now tell your shell where emacs
and other
programs installed with Guix are to be found. Pasting the two lines above
will do just that: it will add $HOME/.guix-profile/bin
—which is
where the installed package is—to the PATH
environment variable.
You can paste these two lines in your shell so they take effect right away,
but more importantly you should add them to ~/.bash_profile (or
equivalent file if you do not use Bash) so that environment variables are
set next time you spawn a shell. You only need to do this once and other
search paths environment variables will be taken care of similarly—e.g.,
if you eventually install python
and Python libraries,
GUIX_PYTHONPATH
will be defined.
You can go on installing packages at your will. To list installed packages, run:
guix package --list-installed
To remove a package, you would unsurprisingly run guix remove
. A
distinguishing feature is the ability to roll back any operation you
made—installation, removal, upgrade—by simply typing:
guix package --roll-back
This is because each operation is in fact a transaction that creates a new generation. These generations and the difference between them can be displayed by running:
guix package --list-generations
Now you know the basics of package management!
Indo além: Veja Gerenciamento de pacote, for more about package management. You may like declarative package management with
guix package --manifest
, managing separate profiles with --profile, deleting old generations, collecting garbage, and other nifty features that will come in handy as you become more familiar with Guix. If you are a developer, veja Desenvolvimento for additional tools. And if you’re curious, veja Recursos, to peek under the hood.You can also manage the configuration of your entire home environment—your user “dot files”, services, and packages—using Guix Home. Veja Home Configuration, to learn more about it!
Once you’ve installed a set of packages, you will want to periodically upgrade them to the latest and greatest version. To do that, you will first pull the latest revision of Guix and its package collection:
guix pull
The end result is a new guix
command, under
~/.config/guix/current/bin. Unless you’re on Guix System, the first
time you run guix pull
, be sure to follow the hint that the
command prints and, similar to what we saw above, paste these two lines in
your terminal and .bash_profile:
GUIX_PROFILE="$HOME/.config/guix/current" . "$GUIX_PROFILE/etc/profile"
You must also instruct your shell to point to this new guix
:
hash guix
At this point, you’re running a brand new Guix. You can thus go ahead and actually upgrade all the packages you previously installed:
guix upgrade
As you run this command, you will see that binaries are downloaded (or perhaps some packages are built), and eventually you end up with the upgraded packages. Should one of these upgraded packages not be to your liking, remember you can always roll back!
You can display the exact revision of Guix you’re currently using by running:
guix describe
The information it displays is all it takes to reproduce the exact same Guix, be it at a different point in time or on a different machine.
Indo além: Veja Invocando
guix pull
, for more information. Veja Canais, on how to specify additional channels to pull packages from, how to replicate Guix, and more. You may also findtime-machine
handy (veja Invokingguix time-machine
).
If you installed Guix System, one of the first things you’ll want to do is
to upgrade your system. Once you’ve run guix pull
to get the
latest Guix, you can upgrade the system like this:
sudo guix system reconfigure /etc/config.scm
Upon completion, the system runs the latest versions of its software packages. Just like for packages, you can always roll back to a previous generation of the whole system. Veja Começando, to learn how to manage your system.
Now you know enough to get started!
Resources: The rest of this manual provides a reference for all things Guix. Here are some additional resources you may find useful:
- Veja The GNU Guix Cookbook, for a list of “how-to” style of recipes for a variety of applications.
- The GNU Guix Reference Card lists in two pages most of the commands and options you’ll ever need.
- The web site contains instructional videos covering topics such as everyday use of Guix, how to get help, and how to become a contributor.
- Veja Documentação, to learn how to access documentation on your computer.
We hope you will enjoy Guix as much as the community enjoys building it!
The purpose of GNU Guix is to allow users to easily install, upgrade, and remove software packages, without having to know about their build procedures or dependencies. Guix also goes beyond this obvious set of features.
This chapter describes the main features of Guix, as well as the package
management tools it provides. Along with the command-line interface
described below (veja guix package
), you
may also use the Emacs-Guix interface (veja The
Emacs-Guix Reference Manual), after installing emacs-guix
package
(run M-x guix-help command to start with it):
guix install emacs-guix
guix package
guix locate
guix gc
guix pull
guix time-machine
guix describe
guix archive
Próximo: Invocando guix package
, Acima: Gerenciamento de pacote [Conteúdo][Índice]
Here we assume you’ve already made your first steps with Guix (veja Começando) and would like to get an overview about what’s going on under the hood.
When using Guix, each package ends up in the package store, in its own
directory—something that resembles /gnu/store/xxx-package-1.2,
where xxx
is a base32 string.
Instead of referring to these directories, users have their own
profile, which points to the packages that they actually want to use.
These profiles are stored within each user’s home directory, at
$HOME/.guix-profile
.
For example, alice
installs GCC 4.7.2. As a result,
/home/alice/.guix-profile/bin/gcc points to
/gnu/store/…-gcc-4.7.2/bin/gcc. Now, on the same machine,
bob
had already installed GCC 4.8.0. The profile of bob
simply continues to point to
/gnu/store/…-gcc-4.8.0/bin/gcc—i.e., both versions of GCC
coexist on the same system without any interference.
The guix package
command is the central tool to manage packages
(veja Invocando guix package
). It operates on the per-user profiles, and
can be used with normal user privileges.
The command provides the obvious install, remove, and upgrade operations.
Each invocation is actually a transaction: either the specified
operation succeeds, or nothing happens. Thus, if the guix package
process is terminated during the transaction, or if a power outage occurs
during the transaction, then the user’s profile remains in its previous
state, and remains usable.
In addition, any package transaction may be rolled back. So, if, for example, an upgrade installs a new version of a package that turns out to have a serious bug, users may roll back to the previous instance of their profile, which was known to work well. Similarly, the global system configuration on Guix is subject to transactional upgrades and roll-back (veja Começando).
All packages in the package store may be garbage-collected. Guix can
determine which packages are still referenced by user profiles, and remove
those that are provably no longer referenced (veja Invocando guix gc
).
Users may also explicitly remove old generations of their profile so that
the packages they refer to can be collected.
Guix takes a purely functional approach to package management, as described in the introduction (veja Introdução). Each /gnu/store package directory name contains a hash of all the inputs that were used to build that package—compiler, libraries, build scripts, etc. This direct correspondence allows users to make sure a given package installation matches the current state of their distribution. It also helps maximize build reproducibility: thanks to the isolated build environments that are used, a given build is likely to yield bit-identical files when performed on different machines (veja container).
This foundation allows Guix to support transparent binary/source
deployment. When a pre-built binary for a /gnu/store item is
available from an external source—a substitute, Guix just downloads
it and unpacks it; otherwise, it builds the package from source, locally
(veja Substitutos). Because build results are usually bit-for-bit
reproducible, users do not have to trust servers that provide substitutes:
they can force a local build and challenge providers (veja Invocando guix challenge
).
Control over the build environment is a feature that is also useful for
developers. The guix shell
command allows developers of a package
to quickly set up the right development environment for their package,
without having to manually install the dependencies of the package into
their profile (veja Invoking guix shell
).
All of Guix and its package definitions is version-controlled, and
guix pull
allows you to “travel in time” on the history of Guix
itself (veja Invocando guix pull
). This makes it possible to replicate a
Guix instance on a different machine or at a later point in time, which in
turn allows you to replicate complete software environments, while
retaining precise provenance tracking of the software.
Próximo: Substitutos, Anterior: Recursos, Acima: Gerenciamento de pacote [Conteúdo][Índice]
guix package
The guix package
command is the tool that allows users to install,
upgrade, and remove packages, as well as rolling back to previous
configurations. These operations work on a user profile—a directory
of installed packages. Each user has a default profile in
$HOME/.guix-profile. The command operates only on the user’s own
profile, and works with normal user privileges (veja Recursos). Its
syntax is:
guix package opções
Primarily, options specifies the operations to be performed during the transaction. Upon completion, a new profile is created, but previous generations of the profile remain available, should the user want to roll back.
For example, to remove lua
and install guile
and
guile-cairo
in a single transaction:
guix package -r lua -i guile guile-cairo
For your convenience, we also provide the following aliases:
guix search
is an alias for guix package -s
,
guix install
is an alias for guix package -i
,
guix remove
is an alias for guix package -r
,
guix upgrade
is an alias for guix package -u
,
guix show
is an alias for guix package --show=
.
These aliases are less expressive than guix package
and provide
fewer options, so in some cases you’ll probably want to use guix
package
directly.
guix package
also supports a declarative approach whereby
the user specifies the exact set of packages to be available and passes it
via the --manifest option (veja --manifest).
For each user, a symlink to the user’s default profile is automatically
created in $HOME/.guix-profile. This symlink always points to the
current generation of the user’s default profile. Thus, users can add
$HOME/.guix-profile/bin to their PATH
environment variable, and
so on.
If you are not using Guix System, consider adding the following lines to
your ~/.bash_profile (veja Bash Startup Files em The GNU Bash
Reference Manual) so that newly-spawned shells get all the right
environment variable definitions:
GUIX_PROFILE="$HOME/.guix-profile" ; \ source "$GUIX_PROFILE/etc/profile"
In a multi-user setup, user profiles are stored in a place registered as a
garbage-collector root, which $HOME/.guix-profile points to
(veja Invocando guix gc
). That directory is normally
localstatedir/guix/profiles/per-user/user
, where
localstatedir is the value passed to configure
as
--localstatedir, and user is the user name. The
per-user directory is created when guix-daemon
is started,
and the user sub-directory is created by guix package
.
The options can be among the following:
--install=package …
-i package …
Install the specified packages.
Each package may specify a simple package name, such as guile
,
optionally followed by an at-sign and version number, such as
guile@3.0.7
or simply guile@3.0
. In the latter case, the
newest version prefixed by 3.0
is selected.
If no version number is specified, the newest available version will be
selected. In addition, such a package specification may contain a
colon, followed by the name of one of the outputs of the package, as in
gcc:doc
or binutils@2.22:lib
(veja Pacotes com múltiplas saídas).
Packages with a corresponding name (and optionally version) are searched for among the GNU distribution modules (veja Módulos de pacote).
Alternatively, a package can directly specify a store file name such
as /gnu/store/...-guile-3.0.7, as produced by, e.g., guix
build
.
Sometimes packages have propagated inputs: these are dependencies that
automatically get installed along with the required package
(veja propagated-inputs
in
package
objects, for information about propagated inputs in package
definitions).
An example is the GNU MPC library: its C header files refer to those of the GNU MPFR library, which in turn refer to those of the GMP library. Thus, when installing MPC, the MPFR and GMP libraries also get installed in the profile; removing MPC also removes MPFR and GMP—unless they had also been explicitly installed by the user.
Besides, packages sometimes rely on the definition of environment variables for their search paths (see explanation of --search-paths below). Any missing or possibly incorrect environment variable definitions are reported here.
--install-from-expression=exp
-e exp
Install the package exp evaluates to.
exp must be a Scheme expression that evaluates to a <package>
object. This option is notably useful to disambiguate between same-named
variants of a package, with expressions such as (@ (gnu packages
commencement) guile-final)
.
Note that this option installs the first output of the specified package, which may be insufficient when needing a specific output of a multiple-output package.
--install-from-file=file
-f arquivo
Install the package that the code within file evaluates to.
As an example, file might contain a definition like this (veja Definindo pacotes):
(use-modules (guix) (guix build-system gnu) (guix licenses)) (package (name "hello") (version "2.10") (source (origin (method url-fetch) (uri (string-append "mirror://gnu/hello/hello-" version ".tar.gz")) (sha256 (base32 "0ssi1wpaf7plaswqqjwigppsg5fyh99vdlb9kzl7c9lng89ndq1i")))) (build-system gnu-build-system) (synopsis "Hello, GNU world: An example GNU package") (description "Guess what GNU Hello prints!") (home-page "http://www.gnu.org/software/hello/") (license gpl3+))
Developers may find it useful to include such a guix.scm file in the
root of their project source tree that can be used to test development
snapshots and create reproducible development environments (veja Invoking guix shell
).
The file may also contain a JSON representation of one or more package
definitions. Running guix package -f
on hello.json with the
following contents would result in installing the package greeter
after building myhello
:
[ { "name": "myhello", "version": "2.10", "source": "mirror://gnu/hello/hello-2.10.tar.gz", "build-system": "gnu", "arguments": { "tests?": false }, "home-page": "https://www.gnu.org/software/hello/", "synopsis": "Hello, GNU world: An example GNU package", "description": "GNU Hello prints a greeting.", "license": "GPL-3.0+", "native-inputs": ["gettext"] }, { "name": "greeter", "version": "1.0", "source": "mirror://gnu/hello/hello-2.10.tar.gz", "build-system": "gnu", "arguments": { "test-target": "foo", "parallel-build?": false }, "home-page": "https://example.com/", "synopsis": "Greeter using GNU Hello", "description": "This is a wrapper around GNU Hello.", "license": "GPL-3.0+", "inputs": ["myhello", "hello"] } ]
--remove=package …
-r pacote …
Remove the specified packages.
As for --install, each package may specify a version number
and/or output name in addition to the package name. For instance, ‘-r
glibc:debug’ would remove the debug
output of glibc
.
--upgrade[=regexp …]
¶-u [regexp …]
Upgrade all the installed packages. If one or more regexps are specified, upgrade only installed packages whose name matches a regexp. Also see the --do-not-upgrade option below.
Note that this upgrades package to the latest version of packages found in
the distribution currently installed. To update your distribution, you
should regularly run guix pull
(veja Invocando guix pull
).
When upgrading, package transformations that were originally applied when creating the profile are automatically re-applied (veja Opções de transformação de pacote). For example, assume you first installed Emacs from the tip of its development branch with:
guix install emacs-next --with-branch=emacs-next=master
Next time you run guix upgrade
, Guix will again pull the tip of
the Emacs development branch and build emacs-next
from that checkout.
Note that transformation options such as --with-branch and --with-source depend on external state; it is up to you to ensure that they work as expected. You can also discard a transformations that apply to a package by running:
guix install package
--do-not-upgrade[=regexp …]
When used together with the --upgrade option, do not upgrade any packages whose name matches a regexp. For example, to upgrade all packages in the current profile except those containing the substring “emacs”:
$ guix package --upgrade . --do-not-upgrade emacs
--manifest=arquivo
¶-m arquivo
Create a new generation of the profile from the manifest object returned by the Scheme code in file. This option can be repeated several times, in which case the manifests are concatenated.
This allows you to declare the profile’s contents rather than constructing it through a sequence of --install and similar commands. The advantage is that file can be put under version control, copied to different machines to reproduce the same profile, and so on.
file must return a manifest object, which is roughly a list of packages:
(use-package-modules guile emacs) (packages->manifest (list emacs guile-2.0 ;; Usa uma saída de pacote específica. (list guile-2.0 "debug")))
Veja Writing Manifests, for information on how to write a manifest. Veja --export-manifest, to learn how to obtain a manifest file from an existing profile.
--roll-back
¶Roll back to the previous generation of the profile—i.e., undo the last transaction.
When combined with options such as --install, roll back occurs before any other actions.
When rolling back from the first generation that actually contains installed packages, the profile is made to point to the zeroth generation, which contains no files apart from its own metadata.
After having rolled back, installing, removing, or upgrading packages overwrites previous future generations. Thus, the history of the generations in a profile is always linear.
--switch-generation=padrão
¶-S padrão
Switch to a particular generation defined by pattern.
pattern may be either a generation number or a number prefixed with “+” or “-”. The latter means: move forward/backward by a specified number of generations. For example, if you want to return to the latest generation after --roll-back, use --switch-generation=+1.
The difference between --roll-back and --switch-generation=-1 is that --switch-generation will not make a zeroth generation, so if a specified generation does not exist, the current generation will not be changed.
--search-paths[=tipo]
¶Report environment variable definitions, in Bash syntax, that may be needed in order to use the set of installed packages. These environment variables are used to specify search paths for files used by some of the installed packages.
For example, GCC needs the CPATH
and LIBRARY_PATH
environment
variables to be defined so it can look for headers and libraries in the
user’s profile (veja Environment Variables em Using the GNU Compiler
Collection (GCC)). If GCC and, say, the C library are installed in the
profile, then --search-paths will suggest setting these variables
to profile/include and profile/lib, respectively
(veja Search Paths, for info on search path specifications associated
with packages.)
The typical use case is to define these environment variables in the shell:
$ eval $(guix package --search-paths)
kind may be one of exact
, prefix
, or suffix
,
meaning that the returned environment variable definitions will either be
exact settings, or prefixes or suffixes of the current value of these
variables. When omitted, kind defaults to exact
.
This option can also be used to compute the combined search paths of several profiles. Consider this example:
$ guix package -p foo -i guile $ guix package -p bar -i guile-json $ guix package -p foo -p bar --search-paths
The last command above reports about the GUILE_LOAD_PATH
variable,
even though, taken individually, neither foo nor bar would
lead to that recommendation.
--profile=perfil
-p perfil
Use profile instead of the user’s default profile.
profile must be the name of a file that will be created upon completion. Concretely, profile will be a mere symbolic link (“symlink”) pointing to the actual profile where packages are installed:
$ guix install hello -p ~/code/my-profile … $ ~/code/my-profile/bin/hello Hello, world!
All it takes to get rid of the profile is to remove this symlink and its siblings that point to specific generations:
$ rm ~/code/my-profile ~/code/my-profile-*-link
--list-profiles
List all the user’s profiles:
$ guix package --list-profiles /home/charlie/.guix-profile /home/charlie/code/my-profile /home/charlie/code/devel-profile /home/charlie/tmp/test
When running as root, list all the profiles of all the users.
--allow-collisions
Allow colliding packages in the new profile. Use at your own risk!
By default, guix package
reports as an error collisions in
the profile. Collisions happen when two or more different versions or
variants of a given package end up in the profile.
--bootstrap
Use the bootstrap Guile to build the profile. This option is only useful to distribution developers.
In addition to these actions, guix package
supports the following
options to query the current state of a profile, or the availability of
packages:
List the available packages whose name, synopsis, or description matches
regexp (in a case-insensitive fashion), sorted by relevance. Print
all the metadata of matching packages in recutils
format (veja GNU recutils databases em GNU recutils manual).
This allows specific fields to be extracted using the recsel
command, for instance:
$ guix package -s malloc | recsel -p name,version,relevance name: jemalloc version: 4.5.0 relevance: 6 name: glibc version: 2.25 relevance: 1 name: libgc version: 7.6.0 relevance: 1
Similarly, to show the name of all the packages available under the terms of the GNU LGPL version 3:
$ guix package -s "" | recsel -p name -e 'license ~ "LGPL 3"' name: elfutils name: gmp …
It is also possible to refine search results using several -s
flags
to guix package
, or several arguments to guix search
.
For example, the following command returns a list of board games (this time
using the guix search
alias):
$ guix search '\<board\>' game | recsel -p name name: gnubg …
If we were to omit -s game
, we would also get software packages that
deal with printed circuit boards; removing the angle brackets around
board
would further add packages that have to do with keyboards.
And now for a more elaborate example. The following command searches for cryptographic libraries, filters out Haskell, Perl, Python, and Ruby libraries, and prints the name and synopsis of the matching packages:
$ guix search crypto library | \ recsel -e '! (name ~ "^(ghc|perl|python|ruby)")' -p name,synopsis
Veja Selection Expressions em GNU recutils manual, for more
information on selection expressions for recsel -e
.
Show details about package, taken from the list of available packages,
in recutils
format (veja GNU recutils databases em GNU recutils manual).
$ guix package --show=guile | recsel -p name,version name: guile version: 3.0.5 name: guile version: 3.0.2 name: guile version: 2.2.7 …
You may also specify the full name of a package to only get details about a
specific version of it (this time using the guix show
alias):
$ guix show guile@3.0.5 | recsel -p name,version name: guile version: 3.0.5
List the currently installed packages in the specified profile, with the most recently installed packages shown last. When regexp is specified, list only installed packages whose name matches regexp.
For each installed package, print the following items, separated by tabs:
the package name, its version string, the part of the package that is
installed (for instance, out
for the default output, include
for its headers, etc.), and the path of this package in the store.
List packages currently available in the distribution for this system (veja Distribuição GNU). When regexp is specified, list only available packages whose name matches regexp.
For each package, print the following items separated by tabs: its name, its version string, the parts of the package (veja Pacotes com múltiplas saídas), and the source location of its definition.
Return a list of generations along with their creation dates; for each generation, show the installed packages, with the most recently installed packages shown last. Note that the zeroth generation is never shown.
For each installed package, print the following items, separated by tabs: the name of a package, its version string, the part of the package that is installed (veja Pacotes com múltiplas saídas), and the location of this package in the store.
When pattern is used, the command returns only matching generations. Valid patterns include:
And --list-generations=1,8,2 outputs three generations in the specified order. Neither spaces nor trailing commas are allowed.
It is also possible to omit the endpoint. For example, --list-generations=2.., returns all generations starting from the second one.
When pattern is omitted, delete all generations except the current one.
This command accepts the same patterns as --list-generations. When pattern is specified, delete the matching generations. When pattern specifies a duration, generations older than the specified duration match. For instance, --delete-generations=1m deletes generations that are more than one month old.
If the current generation matches, it is not deleted. Also, the zeroth generation is never deleted.
Note that deleting generations prevents rolling back to them. Consequently, this command must be used with care.
Write to standard output a manifest suitable for --manifest corresponding to the chosen profile(s).
This option is meant to help you migrate from the “imperative” operating
mode—running guix install
, guix upgrade
, etc.—to the
declarative mode that --manifest offers.
Be aware that the resulting manifest approximates what your profile actually contains; for instance, depending on how your profile was created, it can refer to packages or package versions that are not exactly what you specified.
Keep in mind that a manifest is purely symbolic: it only contains package names and possibly versions, and their meaning varies over time. If you wish to “pin” channels to the revisions that were used to build the profile(s), see --export-channels below.
Write to standard output the list of channels used by the chosen profile(s),
in a format suitable for guix pull --channels
or guix
time-machine --channels
(veja Canais).
Together with --export-manifest, this option provides information allowing you to replicate the current profile (veja Replicating Guix).
However, note that the output of this command approximates what was actually used to build this profile. In particular, a single profile might have been built from several different revisions of the same channel. In that case, --export-manifest chooses the last one and writes the list of other revisions in a comment. If you really need to pick packages from different channel revisions, you can use inferiors in your manifest to do so (veja Inferiores).
Together with --export-manifest, this is a good starting point if you are willing to migrate from the “imperative” model to the fully declarative model consisting of a manifest file along with a channels file pinning the exact channel revision(s) you want.
Finally, since guix package
may actually start build processes, it
supports all the common build options (veja Opções de compilação comum). It
also supports package transformation options, such as
--with-source, and preserves them across upgrades (veja Opções de transformação de pacote).
Próximo: Pacotes com múltiplas saídas, Anterior: Invocando guix package
, Acima: Gerenciamento de pacote [Conteúdo][Índice]
Guix supports transparent source/binary deployment, which means that it can either build things locally, or download pre-built items from a server, or both. We call these pre-built items substitutes—they are substitutes for local build results. In many cases, downloading a substitute is much faster than building things locally.
Substitutes can be anything resulting from a derivation build (veja Derivações). Of course, in the common case, they are pre-built package binaries, but source tarballs, for instance, which also result from derivation builds, can be available as substitutes.
Próximo: Autorização de servidor substituto, Acima: Substitutos [Conteúdo][Índice]
bordeaux.guix.gnu.org
and ci.guix.gnu.org
are both front-ends to official build farms that build packages from Guix
continuously for some architectures, and make them available as
substitutes. These are the default source of substitutes; which can be
overridden by passing the --substitute-urls option either to
guix-daemon
(veja guix-daemon
--substitute-urls
) or to client tools such as guix package
(veja client --substitute-urls option).
Substitute URLs can be either HTTP or HTTPS. HTTPS is recommended because communications are encrypted; conversely, using HTTP makes all communications visible to an eavesdropper, who could use the information gathered to determine, for instance, whether your system has unpatched security vulnerabilities.
Substitutes from the official build farms are enabled by default when using Guix System (veja Distribuição GNU). However, they are disabled by default when using Guix on a foreign distribution, unless you have explicitly enabled them via one of the recommended installation steps (veja Instalação). The following paragraphs describe how to enable or disable substitutes for the official build farm; the same procedure can also be used to enable substitutes for any other substitute server.
Próximo: Getting Substitutes from Other Servers, Anterior: Official Substitute Servers, Acima: Substitutos [Conteúdo][Índice]
To allow Guix to download substitutes from
bordeaux.guix.gnu.org
, ci.guix.gnu.org
or a
mirror, you must add the relevant public key to the access control list
(ACL) of archive imports, using the guix archive
command
(veja Invocando guix archive
). Doing so implies that you trust the
substitute server to not be compromised and to serve genuine substitutes.
Nota: If you are using Guix System, you can skip this section: Guix System authorizes substitutes from
bordeaux.guix.gnu.org
andci.guix.gnu.org
by default.
The public keys for each of the project maintained substitute servers are
installed along with Guix, in prefix/share/guix/
, where
prefix is the installation prefix of Guix. If you installed Guix from
source, make sure you checked the GPG signature of
guix-9356a8c.tar.gz, which contains this public key file.
Then, you can run something like this:
# guix archive --authorize < prefix/share/guix/bordeaux.guix.gnu.org.pub # guix archive --authorize < prefix/share/guix/ci.guix.gnu.org.pub
Once this is in place, the output of a command like guix build
should
change from something like:
$ guix build emacs --dry-run The following derivations would be built: /gnu/store/yr7bnx8xwcayd6j95r2clmkdl1qh688w-emacs-24.3.drv /gnu/store/x8qsh1hlhgjx6cwsjyvybnfv2i37z23w-dbus-1.6.4.tar.gz.drv /gnu/store/1ixwp12fl950d15h2cj11c73733jay0z-alsa-lib-1.0.27.1.tar.bz2.drv /gnu/store/nlma1pw0p603fpfiqy7kn4zm105r5dmw-util-linux-2.21.drv …
to something like:
$ guix build emacs --dry-run 112.3 MB would be downloaded: /gnu/store/pk3n22lbq6ydamyymqkkz7i69wiwjiwi-emacs-24.3 /gnu/store/2ygn4ncnhrpr61rssa6z0d9x22si0va3-libjpeg-8d /gnu/store/71yz6lgx4dazma9dwn2mcjxaah9w77jq-cairo-1.12.16 /gnu/store/7zdhgp0n1518lvfn8mb96sxqfmvqrl7v-libxrender-0.9.7 …
The text changed from “The following derivations would be built” to “112.3 MB would be downloaded”. This indicates that substitutes from the configured substitute servers are usable and will be downloaded, when possible, for future builds.
The substitute mechanism can be disabled globally by running
guix-daemon
with --no-substitutes (veja Invocando guix-daemon
). It can also be disabled temporarily by passing the
--no-substitutes option to guix package
, guix
build
, and other command-line tools.
Próximo: Autenticação de substituto, Anterior: Autorização de servidor substituto, Acima: Substitutos [Conteúdo][Índice]
Guix can look up and fetch substitutes from several servers. This is useful when you are using packages from additional channels for which the official server does not have substitutes but another server provides them. Another situation where this is useful is when you would prefer to download from your organization’s substitute server, resorting to the official server only as a fallback or dismissing it altogether.
You can give Guix a list of substitute server URLs and it will check them in the specified order. You also need to explicitly authorize the public keys of substitute servers to instruct Guix to accept the substitutes they sign.
On Guix System, this is achieved by modifying the configuration of the
guix
service. Since the guix
service is part of the default
lists of services, %base-services
and %desktop-services
, you
can use modify-services
to change its configuration and add the URLs
and substitute keys that you want (veja modify-services
).
As an example, suppose you want to fetch substitutes from
guix.example.org
and to authorize the signing key of that server, in
addition to the default bordeaux.guix.gnu.org
and
ci.guix.gnu.org
. The resulting operating system
configuration will look something like:
(operating-system
;; …
(services
;; Assume we're starting from '%desktop-services'. Replace it
;; with the list of services you're actually using.
(modify-services %desktop-services
(guix-service-type config =>
(guix-configuration
(inherit config)
(substitute-urls
(append (list "https://guix.example.org")
%default-substitute-urls))
(authorized-keys
(append (list (local-file "./key.pub"))
%default-authorized-guix-keys)))))))
This assumes that the file key.pub contains the signing key of
guix.example.org
. With this change in place in your operating system
configuration file (say /etc/config.scm), you can reconfigure and
restart the guix-daemon
service or reboot so the changes take effect:
$ sudo guix system reconfigure /etc/config.scm $ sudo herd restart guix-daemon
If you’re running Guix on a “foreign distro”, you would instead take the following steps to get substitutes from additional servers:
guix-daemon
; when using
systemd, this is normally /etc/systemd/system/guix-daemon.service.
Add the --substitute-urls option on the guix-daemon
command line and list the URLs of interest (veja guix-daemon --substitute-urls
):
… --substitute-urls='https://guix.example.org https://bordeaux.guix.gnu.org https://ci.guix.gnu.org'
systemctl daemon-reload systemctl restart guix-daemon.service
guix archive
):
guix archive --authorize < key.pub
Again this assumes key.pub contains the public key that
guix.example.org
uses to sign substitutes.
Now you’re all set! Substitutes will be preferably taken from
https://guix.example.org
, using bordeaux.guix.gnu.org
then ci.guix.gnu.org
as fallback options. Of course you
can list as many substitute servers as you like, with the caveat that
substitute lookup can be slowed down if too many servers need to be
contacted.
Troubleshooting: To diagnose problems, you can run
guix weather
. For example, running:guix weather coreutilsnot only tells you which of the currently-configured servers has substitutes for the
coreutils
package, it also reports whether one of these servers is unauthorized. Veja Invocandoguix weather
, for more information.
Note that there are also situations where one may want to add the URL of a substitute server without authorizing its key. Veja Autenticação de substituto, to understand this fine point.
Próximo: Configurações de proxy, Anterior: Getting Substitutes from Other Servers, Acima: Substitutos [Conteúdo][Índice]
Guix detects and raises an error when attempting to use a substitute that has been tampered with. Likewise, it ignores substitutes that are not signed, or that are not signed by one of the keys listed in the ACL.
There is one exception though: if an unauthorized server provides substitutes that are bit-for-bit identical to those provided by an authorized server, then the unauthorized server becomes eligible for downloads. For example, assume we have chosen two substitute servers with this option:
--substitute-urls="https://a.example.org https://b.example.org"
If the ACL contains only the key for ‘b.example.org’, and if ‘a.example.org’ happens to serve the exact same substitutes, then Guix will download substitutes from ‘a.example.org’ because it comes first in the list and can be considered a mirror of ‘b.example.org’. In practice, independent build machines usually produce the same binaries, thanks to bit-reproducible builds (see below).
When using HTTPS, the server’s X.509 certificate is not validated (in other words, the server is not authenticated), contrary to what HTTPS clients such as Web browsers usually do. This is because Guix authenticates substitute information itself, as explained above, which is what we care about (whereas X.509 certificates are about authenticating bindings between domain names and public keys).
Próximo: Falha na substituição, Anterior: Autenticação de substituto, Acima: Substitutos [Conteúdo][Índice]
Substitutes are downloaded over HTTP or HTTPS. The http_proxy
and
https_proxy
environment variables can be set in the environment of
guix-daemon
and are honored for downloads of substitutes. Note
that the value of those environment variables in the environment where
guix build
, guix package
, and other client commands are
run has absolutely no effect.
Próximo: Confiança em binários, Anterior: Configurações de proxy, Acima: Substitutos [Conteúdo][Índice]
Even when a substitute for a derivation is available, sometimes the substitution attempt will fail. This can happen for a variety of reasons: the substitute server might be offline, the substitute may recently have been deleted, the connection might have been interrupted, etc.
When substitutes are enabled and a substitute for a derivation is available, but the substitution attempt fails, Guix will attempt to build the derivation locally depending on whether or not --fallback was given (veja common build option --fallback). Specifically, if --fallback was omitted, then no local build will be performed, and the derivation is considered to have failed. However, if --fallback was given, then Guix will attempt to build the derivation locally, and the success or failure of the derivation depends on the success or failure of the local build. Note that when substitutes are disabled or no substitute is available for the derivation in question, a local build will always be performed, regardless of whether or not --fallback was given.
To get an idea of how many substitutes are available right now, you can try
running the guix weather
command (veja Invocando guix weather
).
This command provides statistics on the substitutes provided by a server.
Anterior: Falha na substituição, Acima: Substitutos [Conteúdo][Índice]
Today, each individual’s control over their own computing is at the mercy of
institutions, corporations, and groups with enough power and determination
to subvert the computing infrastructure and exploit its weaknesses. While
using substitutes can be convenient, we encourage users to also build on
their own, or even run their own build farm, such that the project run
substitute servers are less of an interesting target. One way to help is by
publishing the software you build using guix publish
so that
others have one more choice of server to download substitutes from
(veja Invocando guix publish
).
Guix has the foundations to maximize build reproducibility
(veja Recursos). In most cases, independent builds of a given package or
derivation should yield bit-identical results. Thus, through a diverse set
of independent package builds, we can strengthen the integrity of our
systems. The guix challenge
command aims to help users assess
substitute servers, and to assist developers in finding out about
non-deterministic package builds (veja Invocando guix challenge
).
Similarly, the --check option of guix build
allows users
to check whether previously-installed substitutes are genuine by rebuilding
them locally (veja guix build --check
).
In the future, we want Guix to have support to publish and retrieve binaries to/from other users, in a peer-to-peer fashion. If you would like to discuss this project, join us on guix-devel@gnu.org.
Próximo: Invocando guix locate
, Anterior: Substitutos, Acima: Gerenciamento de pacote [Conteúdo][Índice]
Often, packages defined in Guix have a single output—i.e., the
source package leads to exactly one directory in the store. When running
guix install glibc
, one installs the default output of the GNU
libc package; the default output is called out
, but its name can be
omitted as shown in this command. In this particular case, the default
output of glibc
contains all the C header files, shared libraries,
static libraries, Info documentation, and other supporting files.
Sometimes it is more appropriate to separate the various types of files
produced from a single source package into separate outputs. For instance,
the GLib C library (used by GTK+ and related packages) installs more than
20 MiB of reference documentation as HTML pages. To save space for users
who do not need it, the documentation goes to a separate output, called
doc
. To install the main GLib output, which contains everything but
the documentation, one would run:
guix install glib
The command to install its documentation is:
guix install glib:doc
While the colon syntax works for command-line specification of package
outputs, it will not work when using a package variable in Scheme
code. For example, to add the documentation of glib
to the globally
installed packages of an operating-system
(see operating-system
Reference), a list of two items, the first one being the package
variable and the second one the name of the output to select (a
string), must be used instead:
(use-modules (gnu packages glib)) ;; glib-with-documentation is the Guile symbol for the glib package (operating-system ... (packages (append (list (list glib-with-documentation "doc")) %base-packages)))
Some packages install programs with different “dependency footprints”.
For instance, the WordNet package installs both command-line tools and
graphical user interfaces (GUIs). The former depend solely on the C
library, whereas the latter depend on Tcl/Tk and the underlying X
libraries. In this case, we leave the command-line tools in the default
output, whereas the GUIs are in a separate output. This allows users who do
not need the GUIs to save space. The guix size
command can help
find out about such situations (veja Invocando guix size
). guix
graph
can also be helpful (veja Invocando guix graph
).
There are several such multiple-output packages in the GNU distribution.
Other conventional output names include lib
for libraries and
possibly header files, bin
for stand-alone programs, and debug
for debugging information (veja Instalando arquivos de depuração). The outputs
of a package are listed in the third column of the output of guix
package --list-available
(veja Invocando guix package
).
Próximo: Invocando guix gc
, Anterior: Pacotes com múltiplas saídas, Acima: Gerenciamento de pacote [Conteúdo][Índice]
guix locate
There’s so much free software out there that sooner or later, you will need
to search for packages. The guix search
command that we’ve seen
before (veja Invocando guix package
) lets you search by keywords:
guix search video editor
Sometimes, you instead want to find which package provides a given file, and
this is where guix locate
comes in. Here is how you can find
which package provides the ls
command:
$ guix locate ls coreutils@9.1 /gnu/store/…-coreutils-9.1/bin/ls
Of course the command works for any file, not just commands:
$ guix locate unistr.h icu4c@71.1 /gnu/store/…/include/unicode/unistr.h libunistring@1.0 /gnu/store/…/include/unistr.h
You may also specify glob patterns with wildcards. For example, here is how you would search for packages providing .service files:
$ guix locate -g '*.service' man-db@2.11.1 …/lib/systemd/system/man-db.service wpa-supplicant@2.10 …/system-services/fi.w1.wpa_supplicant1.service
The guix locate
command relies on a database that maps file names
to package names. By default, it automatically creates that database if it
does not exist yet by traversing packages available locally, which
can take a few minutes (depending on the size of your store and the speed of
your storage device).
Nota: For now,
guix locate
builds its database based on purely local knowledge—meaning that you will not find packages that never reached your store. Eventually it will support downloading a pre-built database so you can potentially find more packages.
By default, guix locate
first tries to look for a system-wide
database, usually under /var/cache/guix/locate; if it does not exist
or is too old, it falls back to the per-user database, by default under
~/.cache/guix/locate. On a multi-user system, administrators may
want to periodically update the system-wide database so that all users can
benefit from it, for instance by setting up
package-database-service-type
(veja package-database-service-type
).
The general syntax is:
guix locate [options…] file…
... where file is the name of a file to search for (specifically, the “base name” of the file: files whose parent directories are called file are not matched).
The available options are as follows:
--glob
-g
Interpret file… as glob patterns—patterns that may include wildcards, such as ‘*.scm’ to denote all files ending in ‘.scm’.
--stats
Display database statistics.
--update
-u
Update the file database.
By default, the database is automatically updated when it is too old.
--clear
Clear the database and re-populate it.
This option lets you start anew, ensuring old data is removed from the
database, which also avoids having an endlessly growing database. By
default guix locate
automatically does that periodically, though
infrequently.
--database=file
Use file as the database, creating it if necessary.
By default, guix locate
picks the database under
~/.cache/guix or /var/cache/guix, whichever is the most recent
one.
--method=method
-m method
Use method to select the set of packages to index. Possible values are:
manifests
This is the default method: it works by traversing profiles on the machine and recording packages it encounters—packages you or other users of the machine installed, directly or indirectly. It is fast but it can miss other packages available in the store but not referred to by any profile.
armazém
This is a slower but more exhaustive method: it checks among all the existing packages those that are available in the store and records them.
Próximo: Invocando guix pull
, Anterior: Invocando guix locate
, Acima: Gerenciamento de pacote [Conteúdo][Índice]
guix gc
Packages that are installed, but not used, may be garbage-collected.
The guix gc
command allows users to explicitly run the garbage
collector to reclaim space from the /gnu/store directory. It is the
only way to remove files from /gnu/store—removing files or
directories manually may break it beyond repair!
The garbage collector has a set of known roots: any file under
/gnu/store reachable from a root is considered live and cannot
be deleted; any other file is considered dead and may be deleted. The
set of garbage collector roots (“GC roots” for short) includes default
user profiles; by default, the symlinks under /var/guix/gcroots
represent these GC roots. New GC roots can be added with guix
build --root
, for example (veja Invocando guix build
). The guix
gc --list-roots
command lists them.
Prior to running guix gc --collect-garbage
to make space, it is often
useful to remove old generations from user profiles; that way, old package
builds referenced by those generations can be reclaimed. This is achieved
by running guix package --delete-generations
(veja Invocando guix package
).
Our recommendation is to run a garbage collection periodically, or when you are short on disk space. For instance, to guarantee that at least 5 GB are available on your disk, simply run:
guix gc -F 5G
It is perfectly safe to run as a non-interactive periodic job
(veja Execução de trabalho agendado, for how to set up such a job). Running
guix gc
with no arguments will collect as much garbage as it can,
but that is often inconvenient: you may find yourself having to rebuild or
re-download software that is “dead” from the GC viewpoint but that is
necessary to build other pieces of software—e.g., the compiler tool chain.
The guix gc
command has three modes of operation: it can be used
to garbage-collect any dead files (the default), to delete specific files
(the --delete option), to print garbage-collector information, or
for more advanced queries. The garbage collection options are as follows:
--collect-garbage[=min]
-C [min]
Collect garbage—i.e., unreachable /gnu/store files and sub-directories. This is the default operation when no option is specified.
When min is given, stop once min bytes have been collected.
min may be a number of bytes, or it may include a unit as a suffix,
such as MiB
for mebibytes and GB
for gigabytes (veja size specifications em GNU Coreutils).
When min is omitted, collect all the garbage.
--free-space=free
-F free
Collect garbage until free space is available under /gnu/store,
if possible; free denotes storage space, such as 500MiB
, as
described above.
When free or more is already available in /gnu/store, do nothing and exit immediately.
--delete-generations[=duração]
-d [duration]
Before starting the garbage collection process, delete all the generations older than duration, for all the user profiles and home environment generations; when run as root, this applies to all the profiles of all the users.
For example, this command deletes all the generations of all your profiles that are older than 2 months (except generations that are current), and then proceeds to free space until at least 10 GiB are available:
guix gc -d 2m -F 10G
--delete
-D
Attempt to delete all the store files and directories specified as arguments. This fails if some of the files are not in the store, or if they are still live.
--list-failures
List store items corresponding to cached build failures.
This prints nothing unless the daemon was started with --cache-failures (veja --cache-failures).
--list-roots
List the GC roots owned by the user; when run as root, list all the GC roots.
--list-busy
List store items in use by currently running processes. These store items are effectively considered GC roots: they cannot be deleted.
--clear-failures
Remove the specified store items from the failed-build cache.
Again, this option only makes sense when the daemon is started with --cache-failures. Otherwise, it does nothing.
--list-dead
Show the list of dead files and directories still present in the store—i.e., files and directories no longer reachable from any root.
--list-live
Show the list of live store files and directories.
In addition, the references among existing store files can be queried:
--references
¶--referrers
List the references (respectively, the referrers) of store files given as arguments.
--requisites
¶-R
List the requisites of the store files passed as arguments. Requisites include the store files themselves, their references, and the references of these, recursively. In other words, the returned list is the transitive closure of the store files.
Veja Invocando guix size
, for a tool to profile the size of the closure of
an element. Veja Invocando guix graph
, for a tool to visualize the graph
of references.
--derivers
¶Return the derivation(s) leading to the given store items (veja Derivações).
For example, this command:
guix gc --derivers $(guix package -I ^emacs$ | cut -f4)
returns the .drv file(s) leading to the emacs
package
installed in your profile.
Note that there may be zero matching .drv files, for instance because these files have been garbage-collected. There can also be more than one matching .drv due to fixed-output derivations.
Lastly, the following options allow you to check the integrity of the store and to control disk usage.
Verify the integrity of the store.
By default, make sure that all the store items marked as valid in the database of the daemon actually exist in /gnu/store.
When provided, options must be a comma-separated list containing one
or more of contents
and repair
.
When passing --verify=contents, the daemon computes the content hash of each store item and compares it against its hash in the database. Hash mismatches are reported as data corruptions. Because it traverses all the files in the store, this command can take a long time, especially on systems with a slow disk drive.
Using --verify=repair or --verify=contents,repair causes
the daemon to try to repair corrupt store items by fetching substitutes for
them (veja Substitutos). Because repairing is not atomic, and thus
potentially dangerous, it is available only to the system administrator. A
lightweight alternative, when you know exactly which items in the store are
corrupt, is guix build --repair
(veja Invocando guix build
).
Optimize the store by hard-linking identical files—this is deduplication.
The daemon performs deduplication after each successful build or archive import, unless it was started with --disable-deduplication (veja --disable-deduplication). Thus, this option is primarily useful when the daemon was running with --disable-deduplication.
Guix uses an sqlite database to keep track of the items in (veja O armazém). Over time it is possible that the database may grow to a large
size and become fragmented. As a result, one may wish to clear the freed
space and join the partially used pages in the database left behind from
removed packages or after running the garbage collector. Running
sudo guix gc --vacuum-database
will lock the database and
VACUUM
the store, defragmenting the database and purging freed pages,
unlocking the database when it finishes.
Próximo: Invoking guix time-machine
, Anterior: Invocando guix gc
, Acima: Gerenciamento de pacote [Conteúdo][Índice]
guix pull
Packages are installed or upgraded to the latest version available in the
distribution currently available on your local machine. To update that
distribution, along with the Guix tools, you must run guix pull
:
the command downloads the latest Guix source code and package descriptions,
and deploys it. Source code is downloaded from a
Git repository, by default the official
GNU Guix repository, though this can be customized. guix
pull
ensures that the code it downloads is authentic by verifying
that commits are signed by Guix developers.
Specifically, guix pull
downloads code from the channels
(veja Canais) specified by one of the following, in this order:
channels
field of
guix-configuration
);
%default-channels
variable.
On completion, guix package
will use packages and package versions
from this just-retrieved copy of Guix. Not only that, but all the Guix
commands and Scheme modules will also be taken from that latest version.
New guix
sub-commands added by the update also become available.
Any user can update their Guix copy using guix pull
, and the
effect is limited to the user who ran guix pull
. For instance,
when user root
runs guix pull
, this has no effect on the
version of Guix that user alice
sees, and vice versa.
The result of running guix pull
is a profile available under
~/.config/guix/current containing the latest Guix.
The --list-generations or -l option lists past generations
produced by guix pull
, along with details about their provenance:
$ guix pull -l Generation 1 Jun 10 2018 00:18:18 guix 65956ad repository URL: https://git.savannah.gnu.org/git/guix.git branch: origin/master commit: 65956ad3526ba09e1f7a40722c96c6ef7c0936fe Generation 2 Jun 11 2018 11:02:49 guix e0cc7f6 repository URL: https://git.savannah.gnu.org/git/guix.git branch: origin/master commit: e0cc7f669bec22c37481dd03a7941c7d11a64f1d Generation 3 Jun 13 2018 23:31:07 (current) guix 844cc1c repository URL: https://git.savannah.gnu.org/git/guix.git branch: origin/master commit: 844cc1c8f394f03b404c5bb3aee086922373490c
Veja guix describe
, for other ways to
describe the current status of Guix.
This ~/.config/guix/current
profile works exactly like the profiles
created by guix package
(veja Invocando guix package
). That is,
you can list generations, roll back to the previous generation—i.e., the
previous Guix—and so on:
$ guix pull --roll-back switched from generation 3 to 2 $ guix pull --delete-generations=1 deleting /var/guix/profiles/per-user/charlie/current-guix-1-link
You can also use guix package
(veja Invocando guix package
) to
manage the profile by naming it explicitly:
$ guix package -p ~/.config/guix/current --roll-back switched from generation 3 to 2 $ guix package -p ~/.config/guix/current --delete-generations=1 deleting /var/guix/profiles/per-user/charlie/current-guix-1-link
The guix pull
command is usually invoked with no arguments, but it
supports the following options:
--url=url
--commit=commit
--branch=ramo
Download code for the guix
channel from the specified url, at
the given commit (a valid Git commit ID represented as a hexadecimal
string or the name of a tag), or branch.
These options are provided for convenience, but you can also specify your configuration in the ~/.config/guix/channels.scm file or using the --channels option (see below).
--channels=file
-C arquivo
Read the list of channels from file instead of ~/.config/guix/channels.scm or /etc/guix/channels.scm. file must contain Scheme code that evaluates to a list of channel objects. Veja Canais, for more information.
--no-channel-files
-q
Inhibit loading of the user and system channel files, ~/.config/guix/channels.scm and /etc/guix/channels.scm.
--news
-N
Display news written by channel authors for their users for changes made since the previous generation (veja Writing Channel News). When --details is passed, additionally display new and upgraded packages.
You can view that information for previous generations with guix
pull -l
.
--list-generations[=padrão]
-l [padrão]
List all the generations of ~/.config/guix/current or, if
pattern is provided, the subset of generations that match
pattern. The syntax of pattern is the same as with guix
package --list-generations
(veja Invocando guix package
).
By default, this prints information about the channels used in each revision as well as the corresponding news entries. If you pass --details, it will also print the list of packages added and upgraded in each generation compared to the previous one.
--details
Instruct --list-generations or --news to display more information about the differences between subsequent generations—see above.
--roll-back
¶Roll back to the previous generation of ~/.config/guix/current—i.e., undo the last transaction.
--switch-generation=padrão
¶-S padrão
Switch to a particular generation defined by pattern.
pattern may be either a generation number or a number prefixed with “+” or “-”. The latter means: move forward/backward by a specified number of generations. For example, if you want to return to the latest generation after --roll-back, use --switch-generation=+1.
--delete-generations[=pattern]
-d [pattern]
When pattern is omitted, delete all generations except the current one.
This command accepts the same patterns as --list-generations. When pattern is specified, delete the matching generations. When pattern specifies a duration, generations older than the specified duration match. For instance, --delete-generations=1m deletes generations that are more than one month old.
If the current generation matches, it is not deleted.
Note that deleting generations prevents rolling back to them. Consequently, this command must be used with care.
Veja Invocando guix describe
, for a way to display information about the
current generation only.
--profile=perfil
-p perfil
Use profile instead of ~/.config/guix/current.
--dry-run
-n
Show which channel commit(s) would be used and what would be built or substituted but do not actually do it.
--allow-downgrades
Allow pulling older or unrelated revisions of channels than those currently in use.
By default, guix pull
protects against so-called “downgrade
attacks” whereby the Git repository of a channel would be reset to an
earlier or unrelated revision of itself, potentially leading you to install
older, known-vulnerable versions of software packages.
Nota: Make sure you understand its security implications before using --allow-downgrades.
--disable-authentication
Allow pulling channel code without authenticating it.
By default, guix pull
authenticates code downloaded from channels
by verifying that its commits are signed by authorized developers, and
raises an error if this is not the case. This option instructs it to not
perform any such verification.
Nota: Make sure you understand its security implications before using --disable-authentication.
--system=system
-s sistema
Attempt to build for system—e.g., i686-linux
—instead of the
system type of the build host.
--bootstrap
Use the bootstrap Guile to build the latest Guix. This option is only useful to Guix developers.
The channel mechanism allows you to instruct guix pull
which
repository and branch to pull from, as well as additional
repositories containing package modules that should be deployed.
Veja Canais, for more information.
In addition, guix pull
supports all the common build options
(veja Opções de compilação comum).
Próximo: Inferiores, Anterior: Invocando guix pull
, Acima: Gerenciamento de pacote [Conteúdo][Índice]
guix time-machine
The guix time-machine
command provides access to other revisions
of Guix, for example to install older versions of packages, or to reproduce
a computation in an identical environment. The revision of Guix to be used
is defined by a commit or by a channel description file created by
guix describe
(veja Invocando guix describe
).
Let’s assume that you want to travel to those days of November 2020 when
version 1.2.0 of Guix was released and, once you’re there, run the
guile
of that time:
guix time-machine --commit=v1.2.0 -- \ environment -C --ad-hoc guile -- guile
The command above fetches Guix 1.2.0 (and possibly other channels
specified by your channels.scm configuration files—see below) and
runs its guix environment
command to spawn an environment in a
container running guile
(guix environment
has since been
subsumed by guix shell
; veja Invoking guix shell
). It’s like
driving a DeLorean12! The first guix time-machine
invocation can be expensive: it may have to download or even build a large
number of packages; the result is cached though and subsequent commands
targeting the same commit are almost instantaneous.
As for guix pull
, in the absence of any options,
time-machine
fetches the latest commits of the channels specified
in ~/.config/guix/channels.scm, /etc/guix/channels.scm, or the
default channels; the -q option lets you ignore these configuration
files. The command:
guix time-machine -q -- build hello
will thus build the package hello
as defined in the main branch of
Guix, without any additional channel, which is in general a newer revision
of Guix than you have installed. Time travel works in both directions!
Nota: The history of Guix is immutable and
guix time-machine
provides the exact same software as they are in a specific Guix revision. Naturally, no security fixes are provided for old versions of Guix or its channels. A careless use ofguix time-machine
opens the door to security vulnerabilities. Veja --allow-downgrades.
guix time-machine
raises an error when attempting to travel to
commits older than “v0.16.0” (commit ‘4a0b87f0’), dated Dec. 2018.
This is one of the oldest commits supporting the channel mechanism that
makes “time travel” possible.
Nota: Although it should technically be possible to travel to such an old commit, the ease to do so will largely depend on the availability of binary substitutes. When traveling to a distant past, some packages may not easily build from source anymore. One such example are old versions of OpenSSL whose tests would fail after a certain date. This particular problem can be worked around by running a virtual build machine with its clock set to the right time (veja Virtual Build Machines).
The general syntax is:
guix time-machine options… -- command arg…
where command and arg… are passed unmodified to the
guix
command of the specified revision. The options that
define this revision are the same as for guix pull
(veja Invocando guix pull
):
--url=url
--commit=commit
--branch=ramo
Use the guix
channel from the specified url, at the given
commit (a valid Git commit ID represented as a hexadecimal string or
the name of a tag), or branch.
--channels=file
-C arquivo
Read the list of channels from file. file must contain Scheme code that evaluates to a list of channel objects. Veja Canais for more information.
--no-channel-files
-q
Inhibit loading of the user and system channel files, ~/.config/guix/channels.scm and /etc/guix/channels.scm.
Thus, guix time-machine -q
is equivalent to the following Bash
command, using the “process substitution” syntax (veja Process
Substitution em The GNU Bash Reference Manual):
guix time-machine -C <(echo %default-channels) …
Note that guix time-machine
can trigger builds of channels and
their dependencies, and these are controlled by the standard build options
(veja Opções de compilação comum).
Próximo: Invocando guix describe
, Anterior: Invoking guix time-machine
, Acima: Gerenciamento de pacote [Conteúdo][Índice]
Nota: The functionality described here is a “technology preview” as of version 9356a8c. As such, the interface is subject to change.
Sometimes you might need to mix packages from the revision of Guix you’re currently running with packages available in a different revision of Guix. Guix inferiors allow you to achieve that by composing different Guix revisions in arbitrary ways.
Technically, an “inferior” is essentially a separate Guix process
connected to your main Guix process through a REPL (veja Invocando guix repl
). The (guix inferior)
module allows you to create inferiors
and to communicate with them. It also provides a high-level interface to
browse and manipulate the packages that an inferior provides—inferior
packages.
When combined with channels (veja Canais), inferiors provide a simple
way to interact with a separate revision of Guix. For example, let’s assume
you want to install in your profile the current guile
package, along
with the guile-json
as it existed in an older revision of
Guix—perhaps because the newer guile-json
has an incompatible API
and you want to run your code against the old API. To do that, you could
write a manifest for use by guix package --manifest
(veja Writing Manifests); in that manifest, you would create an inferior for that old
Guix revision you care about, and you would look up the guile-json
package in the inferior:
(use-modules (guix inferior) (guix channels) (srfi srfi-1)) ;for 'first' (define channels ;; This is the old revision from which we want to ;; extract guile-json. (list (channel (name 'guix) (url "https://git.savannah.gnu.org/git/guix.git") (commit "65956ad3526ba09e1f7a40722c96c6ef7c0936fe")))) (define inferior ;; An inferior representing the above revision. (inferior-for-channels channels)) ;; Now create a manifest with the current "guile" package ;; and the old "guile-json" package. (packages->manifest (list (first (lookup-inferior-packages inferior "guile-json")) (specification->package "guile")))
On its first run, guix package --manifest
might have to build the
channel you specified before it can create the inferior; subsequent runs
will be much faster because the Guix revision will be cached.
The (guix inferior)
module provides the following procedures to open
an inferior:
Return an inferior for channels, a list of channels. Use the cache at cache-directory, where entries can be reclaimed after ttl seconds. This procedure opens a new connection to the build daemon.
As a side effect, this procedure may build or substitute binaries for channels, which can take time.
Open the inferior Guix in directory, running
directory/command repl
or equivalent. Return #f
if the inferior could not be launched.
The procedures listed below allow you to obtain and manipulate inferior packages.
Return the list of packages known to inferior.
Return the sorted list of inferior packages matching name in inferior, with highest version numbers first. If version is true, return only packages with a version number prefixed by version.
Return true if obj is an inferior package.
These procedures are the counterpart of package record accessors
(veja package
Reference). Most of them work by querying the inferior
package comes from, so the inferior must still be live when you call
these procedures.
Inferior packages can be used transparently like any other package or
file-like object in G-expressions (veja Expressões-G). They are also
transparently handled by the packages->manifest
procedure, which is
commonly used in manifests (veja the
--manifest option of guix package
). Thus you can insert
an inferior package pretty much anywhere you would insert a regular package:
in manifests, in the packages
field of your operating-system
declaration, and so on.
Próximo: Invocando guix archive
, Anterior: Inferiores, Acima: Gerenciamento de pacote [Conteúdo][Índice]
guix describe
Often you may want to answer questions like: “Which revision of Guix am I
using?” or “Which channels am I using?” This is useful information in
many situations: if you want to replicate an environment on a
different machine or user account, if you want to report a bug or to
determine what change in the channels you are using caused it, or if you
want to record your system state for reproducibility purposes. The
guix describe
command answers these questions.
When run from a guix pull
ed guix
, guix
describe
displays the channel(s) that it was built from, including their
repository URL and commit IDs (veja Canais):
$ guix describe Generation 10 Sep 03 2018 17:32:44 (current) guix e0fa68c repository URL: https://git.savannah.gnu.org/git/guix.git branch: master commit: e0fa68c7718fffd33d81af415279d6ddb518f727
If you’re familiar with the Git version control system, this is similar in
spirit to git describe
; the output is also similar to that of
guix pull --list-generations
, but limited to the current
generation (veja the --list-generations
option). Because the Git commit ID shown above unambiguously refers to a
snapshot of Guix, this information is all it takes to describe the revision
of Guix you’re using, and also to replicate it.
To make it easier to replicate Guix, guix describe
can also be
asked to return a list of channels instead of the human-readable description
above:
$ guix describe -f channels (list (channel (name 'guix) (url "https://git.savannah.gnu.org/git/guix.git") (commit "e0fa68c7718fffd33d81af415279d6ddb518f727") (introduction (make-channel-introduction "9edb3f66fd807b096b48283debdcddccfea34bad" (openpgp-fingerprint "BBB0 2DDF 2CEA F6A8 0D1D E643 A2A0 6DF2 A33A 54FA")))))
You can save this to a file and feed it to guix pull -C
on some
other machine or at a later point in time, which will instantiate this
exact Guix revision (veja the -C option).
From there on, since you’re able to deploy the same revision of Guix, you
can just as well replicate a complete software environment. We
humbly think that this is awesome, and we hope you’ll like it too!
The details of the options supported by guix describe
are as
follows:
--format=format
-f format
Produce output in the specified format, one of:
human
produce human-readable output;
channels
produce a list of channel specifications that can be passed to guix
pull -C
or installed as ~/.config/guix/channels.scm (veja Invocando guix pull
);
channels-sans-intro
like channels
, but omit the introduction
field; use it to
produce a channel specification suitable for Guix version 1.1.0 or
earlier—the introduction
field has to do with channel
authentication (veja Channel Authentication) and is not
supported by these older versions;
json
¶produce a list of channel specifications in JSON format;
recutils
produce a list of channel specifications in Recutils format.
--list-formats
Display available formats for --format option.
--profile=perfil
-p perfil
Display information about profile.
Anterior: Invocando guix describe
, Acima: Gerenciamento de pacote [Conteúdo][Índice]
guix archive
The guix archive
command allows users to export files from
the store into a single archive, and to later import them on a machine
that runs Guix. In particular, it allows store files to be transferred from
one machine to the store on another machine.
Nota: If you’re looking for a way to produce archives in a format suitable for tools other than Guix, veja Invocando
guix pack
.
To export store files as an archive to standard output, run:
guix archive --export options specifications...
specifications may be either store file names or package
specifications, as for guix package
(veja Invocando guix package
). For instance, the following command creates an archive
containing the gui
output of the git
package and the main
output of emacs
:
guix archive --export git:gui /gnu/store/...-emacs-24.3 > great.nar
If the specified packages are not built yet, guix archive
automatically builds them. The build process may be controlled with the
common build options (veja Opções de compilação comum).
To transfer the emacs
package to a machine connected over SSH, one
would run:
guix archive --export -r emacs | ssh the-machine guix archive --import
Similarly, a complete user profile may be transferred from one machine to another like this:
guix archive --export -r $(readlink -f ~/.guix-profile) | \ ssh the-machine guix archive --import
However, note that, in both examples, all of emacs
and the profile as
well as all of their dependencies are transferred (due to -r),
regardless of what is already available in the store on the target machine.
The --missing option can help figure out which items are missing
from the target store. The guix copy
command simplifies and
optimizes this whole process, so this is probably what you should use in
this case (veja Invocando guix copy
).
Each store item is written in the normalized archive or nar
format (described below), and the output of guix archive --export
(and input of guix archive --import
) is a nar bundle.
The nar format is comparable in spirit to ‘tar’, but with differences that make it more appropriate for our purposes. First, rather than recording all Unix metadata for each file, the nar format only mentions the file type (regular, directory, or symbolic link); Unix permissions and owner/group are dismissed. Second, the order in which directory entries are stored always follows the order of file names according to the C locale collation order. This makes archive production fully deterministic.
That nar bundle format is essentially the concatenation of zero or more nars along with metadata for each store item it contains: its file name, references, corresponding derivation, and a digital signature.
When exporting, the daemon digitally signs the contents of the archive, and that digital signature is appended. When importing, the daemon verifies the signature and rejects the import in case of an invalid signature or if the signing key is not authorized.
The main options are:
--export
Export the specified store files or packages (see below). Write the resulting archive to the standard output.
Dependencies are not included in the output, unless --recursive is passed.
-r
--recursive
When combined with --export, this instructs guix archive
to include dependencies of the given items in the archive. Thus, the
resulting archive is self-contained: it contains the closure of the exported
store items.
--import
Read an archive from the standard input, and import the files listed therein into the store. Abort if the archive has an invalid digital signature, or if it is signed by a public key not among the authorized keys (see --authorize below).
--missing
Read a list of store file names from the standard input, one per line, and write on the standard output the subset of these files missing from the store.
--generate-key[=parameters]
¶Generate a new key pair for the daemon. This is a prerequisite before
archives can be exported with --export. This operation is usually
instantaneous but it can take time if the system’s entropy pool needs to be
refilled. On Guix System, guix-service-type
takes care of generating
this key pair the first boot.
The generated key pair is typically stored under /etc/guix, in
signing-key.pub (public key) and signing-key.sec (private key,
which must be kept secret). When parameters is omitted, an ECDSA key
using the Ed25519 curve is generated, or, for Libgcrypt versions before
1.6.0, it is a 4096-bit RSA key. Alternatively, parameters can
specify genkey
parameters suitable for Libgcrypt (veja gcry_pk_genkey
em The Libgcrypt
Reference Manual).
Authorize imports signed by the public key passed on standard input. The public key must be in “s-expression advanced format”—i.e., the same format as the signing-key.pub file.
The list of authorized keys is kept in the human-editable file /etc/guix/acl. The file contains “advanced-format s-expressions” and is structured as an access-control list in the Simple Public-Key Infrastructure (SPKI).
--extract=directory
-x directory
Read a single-item archive as served by substitute servers (veja Substitutos) and extract it to directory. This is a low-level operation needed in only very narrow use cases; see below.
For example, the following command extracts the substitute for Emacs served
by bordeaux.guix.gnu.org
to /tmp/emacs:
$ wget -O - \ https://bordeaux.guix.gnu.org/nar/gzip/…-emacs-24.5 \ | gunzip | guix archive -x /tmp/emacs
Single-item archives are different from multiple-item archives produced by
guix archive --export
; they contain a single store item, and they
do not embed a signature. Thus this operation does no
signature verification and its output should be considered unsafe.
The primary purpose of this operation is to facilitate inspection of archive
contents coming from possibly untrusted substitute servers (veja Invocando guix challenge
).
--list
-t
Read a single-item archive as served by substitute servers (veja Substitutos) and print the list of files it contains, as in this example:
$ wget -O - \ https://bordeaux.guix.gnu.org/nar/lzip/…-emacs-26.3 \ | lzip -d | guix archive -t
Próximo: Desenvolvimento, Anterior: Gerenciamento de pacote, Acima: GNU Guix [Conteúdo][Índice]
Guix and its package collection are updated by running guix pull
.
By default guix pull
downloads and deploys Guix itself from the
official GNU Guix repository. This can be customized by providing a
file specifying the set of channels to pull from (veja Invocando guix pull
). A channel specifies the URL and branch of a Git repository to be
deployed, and guix pull
can be instructed to pull from one or more
channels. In other words, channels can be used to customize and to
extend Guix, as we will see below. Guix is able to take into account
security concerns and deal with authenticated updates.
Próximo: Using a Custom Guix Channel, Acima: Canais [Conteúdo][Índice]
You can specify additional channels to pull from. To use a channel,
write ~/.config/guix/channels.scm
to instruct guix pull
to
pull from it in addition to the default Guix channel(s):
;; Add variant packages to those Guix provides. (cons (channel (name 'variant-packages) (url "https://example.org/variant-packages.git")) %default-channels)
Note that the snippet above is (as always!) Scheme code; we use
cons
to add a channel the list of channels that the variable
%default-channels
is bound to (veja cons
and lists em GNU Guile Reference Manual). With this file in place, guix
pull
builds not only Guix but also the package modules from your own
repository. The result in ~/.config/guix/current is the union of
Guix with your own package modules:
$ guix describe Generation 19 Aug 27 2018 16:20:48 guix d894ab8 repository URL: https://git.savannah.gnu.org/git/guix.git branch: master commit: d894ab8e9bfabcefa6c49d9ba2e834dd5a73a300 variant-packages dd3df5e repository URL: https://example.org/variant-packages.git branch: master commit: dd3df5e2c8818760a8fc0bd699e55d3b69fef2bb
The output of guix describe
above shows that we’re now running
Generation 19 and that it includes both Guix and packages from the
variant-packages
channel (veja Invocando guix describe
).
Próximo: Replicating Guix, Anterior: Specifying Additional Channels, Acima: Canais [Conteúdo][Índice]
The channel called guix
specifies where Guix itself—its
command-line tools as well as its package collection—should be
downloaded. For instance, suppose you want to update from another copy of
the Guix repository at example.org
, and specifically the
super-hacks
branch, you can write in
~/.config/guix/channels.scm
this specification:
;; Tell 'guix pull' to use another repo. (list (channel (name 'guix) (url "https://example.org/another-guix.git") (branch "super-hacks")))
From there on, guix pull
will fetch code from the
super-hacks
branch of the repository at example.org
. The
authentication concern is addressed below (veja Channel Authentication).
Note that you can specify a local directory on the url
field above if
the channel that you intend to use resides on a local file system. However,
in this case guix
checks said directory for ownership before any
further processing. This means that if the user is not the directory owner,
but wants to use it as their default, they will then need to set it as a
safe directory in their global git configuration file. Otherwise,
guix
will refuse to even read it. Supposing your system-wide
local directory is at /src/guix.git
, you would then create a git
configuration file at ~/.gitconfig
with the following contents:
[safe] directory = /src/guix.git
This also applies to the root user unless when called with sudo
by
the directory owner.
Próximo: Customizing the System-Wide Guix, Anterior: Using a Custom Guix Channel, Acima: Canais [Conteúdo][Índice]
The guix describe
command shows precisely which commits were used
to build the instance of Guix we’re using (veja Invocando guix describe
).
We can replicate this instance on another machine or at a different point in
time by providing a channel specification “pinned” to these commits that
looks like this:
;; Deploy specific commits of my channels of interest. (list (channel (name 'guix) (url "https://git.savannah.gnu.org/git/guix.git") (commit "6298c3ffd9654d3231a6f25390b056483e8f407c")) (channel (name 'variant-packages) (url "https://example.org/variant-packages.git") (commit "dd3df5e2c8818760a8fc0bd699e55d3b69fef2bb")))
To obtain this pinned channel specification, the easiest way is to run
guix describe
and to save its output in the channels
format
in a file, like so:
guix describe -f channels > channels.scm
The resulting channels.scm file can be passed to the -C
option of guix pull
(veja Invocando guix pull
) or guix
time-machine
(veja Invoking guix time-machine
), as in this example:
guix time-machine -C channels.scm -- shell python -- python3
Given the channels.scm file, the command above will always fetch the
exact same Guix instance, then use that instance to run the exact
same Python (veja Invoking guix shell
). On any machine, at any time, it
ends up running the exact same binaries, bit for bit.
Pinned channels address a problem similar to “lock files” as implemented by some deployment tools—they let you pin and reproduce a set of packages. In the case of Guix though, you are effectively pinning the entire package set as defined at the given channel commits; in fact, you are pinning all of Guix, including its core modules and command-line tools. You’re also getting strong guarantees that you are, indeed, obtaining the exact same software.
This gives you super powers, allowing you to track the provenance of binary artifacts with very fine grain, and to reproduce software environments at will—some sort of “meta reproducibility” capabilities, if you will. Veja Inferiores, for another way to take advantage of these super powers.
Próximo: Channel Authentication, Anterior: Replicating Guix, Acima: Canais [Conteúdo][Índice]
If you’re running Guix System or building system images with it, maybe you
will want to customize the system-wide guix
it
provides—specifically, /run/current-system/profile/bin/guix. For
example, you might want to provide additional channels or to pin its
revision.
This can be done using the guix-for-channels
procedure, which returns
a package for the given channels, and using it as part of your operating
system configuration, as in this example:
(use-modules (gnu packages package-management) (guix channels)) (define my-channels ;; Channels that should be available to ;; /run/current-system/profile/bin/guix. (append (list (channel (name 'guix-science) (url "https://github.com/guix-science/guix-science") (branch "master"))) %default-channels)) (operating-system ;; … (services ;; Change the package used by 'guix-service-type'. (modify-services %base-services (guix-service-type config => (guix-configuration (inherit config) (channels my-channels) (guix (guix-for-channels my-channels)))))))
The resulting operating system will have both the guix
and the
guix-science
channels visible by default. The channels
field
of guix-configuration
above further ensures that
/etc/guix/channels.scm, which is used by guix pull
,
specifies the same set of channels (veja channels
field of guix-configuration
).
The (gnu packages package-management)
module exports the
guix-for-channels
procedure, described below.
Return a package corresponding to channels.
The result is a “regular” package, which can be used in
guix-configuration
as shown above or in any other place that expects
a package.
Próximo: Channels with Substitutes, Anterior: Customizing the System-Wide Guix, Acima: Canais [Conteúdo][Índice]
The guix pull
and guix time-machine
commands
authenticate the code retrieved from channels: they make sure each
commit that is fetched is signed by an authorized developer. The goal is to
protect from unauthorized modifications to the channel that would lead users
to run malicious code.
As a user, you must provide a channel introduction in your channels file so that Guix knows how to authenticate its first commit. A channel specification, including its introduction, looks something along these lines:
(channel
(name 'some-channel)
(url "https://example.org/some-channel.git")
(introduction
(make-channel-introduction
"6f0d8cc0d88abb59c324b2990bfee2876016bb86"
(openpgp-fingerprint
"CABB A931 C0FF EEC6 900D 0CFB 090B 1199 3D9A EBB5"))))
The specification above shows the name and URL of the channel. The call to
make-channel-introduction
above specifies that authentication of this
channel starts at commit 6f0d8cc…
, which is signed by the
OpenPGP key with fingerprint CABB A931…
.
For the main channel, called guix
, you automatically get that
information from your Guix installation. For other channels, include the
channel introduction provided by the channel authors in your
channels.scm file. Make sure you retrieve the channel introduction
from a trusted source since that is the root of your trust.
If you’re curious about the authentication mechanics, read on!
Próximo: Creating a Channel, Anterior: Channel Authentication, Acima: Canais [Conteúdo][Índice]
When running guix pull
, Guix will first compile the definitions of
every available package. This is an expensive operation for which
substitutes (veja Substitutos) may be available. The following snippet
in channels.scm will ensure that guix pull
uses the latest
commit with available substitutes for the package definitions: this is done
by querying the continuous integration server at
https://ci.guix.gnu.org.
(use-modules (guix ci)) (list (channel-with-substitutes-available %default-guix-channel "https://ci.guix.gnu.org"))
Note that this does not mean that all the packages that you will install
after running guix pull
will have available substitutes. It only
ensures that guix pull
will not try to compile package
definitions. This is particularly useful when using machines with limited
resources.
Próximo: Package Modules in a Sub-directory, Anterior: Channels with Substitutes, Acima: Canais [Conteúdo][Índice]
Let’s say you have a bunch of custom package variants or personal packages that you think would make little sense to contribute to the Guix project, but would like to have these packages transparently available to you at the command line. By creating a channel, you can use and publish such a package collection. This involves the following steps:
mkdir my-channel cd my-channel git init
For example, Alice might want to provide a module called (alice
packages greetings)
that will provide her favorite “hello world”
implementations. To do that Alice will create a directory corresponding to
that module name.
mkdir -p alice/packages $EDITOR alice/packages/greetings.scm git add alice/packages/greetings.scm
You can name your package modules however you like; the main constraint to
keep in mind is to avoid name clashes with other package collections, which
is why our hypothetical Alice wisely chose the (alice packages
…)
name space.
Note that you can also place modules in a sub-directory of the repository; veja Package Modules in a Sub-directory, for more info on that.
guix build
, which needs to be
told to look for modules in the Git checkout. For example, assuming
(alice packages greetings)
provides a package called
hi-from-alice
, Alice will run this command from the Git checkout:
guix build -L. hi-from-alice
... where -L.
adds the current directory to Guile’s load path
(veja Load Paths em GNU Guile Reference Manual).
git commit
As a channel author, consider bundling authentication material with your channel so that users can authenticate it. Veja Channel Authentication, and Specifying Channel Authorizations, for info on how to do it.
guix pull
(veja Invocando guix pull
):
$EDITOR ~/.config/guix/channels.scm guix pull
Guix will now behave as if the root directory of that channel’s Git
repository had been permanently added to the Guile load path. In this
example, (alice packages greetings)
will automatically be found by
the guix
command.
Voilà!
Aviso: Before you publish your channel, we would like to share a few words of caution:
- Before publishing a channel, please consider contributing your package definitions to Guix proper (veja Contribuindo). Guix as a project is open to free software of all sorts, and packages in Guix proper are readily available to all Guix users and benefit from the project’s quality assurance process.
- Package modules and package definitions are Scheme code that uses various programming interfaces (APIs). We, Guix developers, never change APIs gratuitously, but we do not commit to freezing APIs either. When you maintain package definitions outside Guix, we consider that the compatibility burden is on you.
- Corollary: if you’re using an external channel and that channel breaks, please report the issue to the channel authors, not to the Guix project.
You’ve been warned! Having said this, we believe external channels are a practical way to exert your freedom to augment Guix’ package collection and to share your improvements, which are basic tenets of free software. Please email us at guix-devel@gnu.org if you’d like to discuss this.
Próximo: Declaring Channel Dependencies, Anterior: Creating a Channel, Acima: Canais [Conteúdo][Índice]
As a channel author, you may want to keep your channel modules in a sub-directory. If your modules are in the sub-directory guix, you must add a meta-data file .guix-channel that contains:
(channel
(version 0)
(directory "guix"))
The modules must be underneath the specified directory, as the
directory
changes Guile’s load-path
. For example, if
.guix-channel has (directory "base")
, then a module defined as
(define-module (gnu packages fun))
must be located at
base/gnu/packages/fun.scm
.
Doing this allows for only parts of a repository to be used as a channel, as
Guix expects valid Guile modules when pulling. For instance, guix
deploy
machine configuration files are not valid Guile modules, and
treating them as such would make guix pull
fail.
Próximo: Specifying Channel Authorizations, Anterior: Package Modules in a Sub-directory, Acima: Canais [Conteúdo][Índice]
Channel authors may decide to augment a package collection provided by other channels. They can declare their channel to be dependent on other channels in a meta-data file .guix-channel, which is to be placed in the root of the channel repository.
The meta-data file should contain a simple S-expression like this:
(channel
(version 0)
(dependencies
(channel
(name some-collection)
(url "https://example.org/first-collection.git")
;; The 'introduction' bit below is optional: you would
;; provide it for dependencies that can be authenticated.
(introduction
(channel-introduction
(version 0)
(commit "a8883b58dc82e167c96506cf05095f37c2c2c6cd")
(signer "CABB A931 C0FF EEC6 900D 0CFB 090B 1199 3D9A EBB5"))))
(channel
(name some-other-collection)
(url "https://example.org/second-collection.git")
(branch "testing"))))
In the above example this channel is declared to depend on two other channels, which will both be fetched automatically. The modules provided by the channel will be compiled in an environment where the modules of all these declared channels are available.
For the sake of reliability and maintainability, you should avoid dependencies on channels that you don’t control, and you should aim to keep the number of dependencies to a minimum.
Próximo: Primary URL, Anterior: Declaring Channel Dependencies, Acima: Canais [Conteúdo][Índice]
As we saw above, Guix ensures the source code it pulls from channels comes from authorized developers. As a channel author, you need to specify the list of authorized developers in the .guix-authorizations file in the channel’s Git repository. The authentication rule is simple: each commit must be signed by a key listed in the .guix-authorizations file of its parent commit(s)13 The .guix-authorizations file looks like this:
;; Example '.guix-authorizations' file. (authorizations (version 0) ;current file format version (("AD17 A21E F8AE D8F1 CC02 DBD9 F8AE D8F1 765C 61E3" (name "alice")) ("2A39 3FFF 68F4 EF7A 3D29 12AF 68F4 EF7A 22FB B2D5" (name "bob")) ("CABB A931 C0FF EEC6 900D 0CFB 090B 1199 3D9A EBB5" (name "charlie"))))
Each fingerprint is followed by optional key/value pairs, as in the example above. Currently these key/value pairs are ignored.
This authentication rule creates a chicken-and-egg issue: how do we authenticate the first commit? Related to that: how do we deal with channels whose repository history contains unsigned commits and lack .guix-authorizations? And how do we fork existing channels?
Channel introductions answer these questions by describing the first commit
of a channel that should be authenticated. The first time a channel is
fetched with guix pull
or guix time-machine
, the command
looks up the introductory commit and verifies that it is signed by the
specified OpenPGP key. From then on, it authenticates commits according to
the rule above. Authentication fails if the target commit is neither a
descendant nor an ancestor of the introductory commit.
Additionally, your channel must provide all the OpenPGP keys that were ever
mentioned in .guix-authorizations, stored as .key files, which
can be either binary or “ASCII-armored”. By default, those .key
files are searched for in the branch named keyring
but you can
specify a different branch name in .guix-channel
like so:
(channel
(version 0)
(keyring-reference "my-keyring-branch"))
To summarize, as the author of a channel, there are three things you have to do to allow users to authenticate your code:
gpg
--export
and store them in .key files, by default in a branch named
keyring
(we recommend making it an orphan branch).
Before pushing to your public Git repository, you can run guix git
authenticate
to verify that you did sign all the commits you are about to
push with an authorized key:
guix git authenticate commit signer
where commit and signer are your channel introduction.
Veja Invoking guix git authenticate
, for details.
Publishing a signed channel requires discipline: any mistake, such as an unsigned commit or a commit signed by an unauthorized key, will prevent users from pulling from your channel—well, that’s the whole point of authentication! Pay attention to merges in particular: merge commits are considered authentic if and only if they are signed by a key present in the .guix-authorizations file of both branches.
Próximo: Writing Channel News, Anterior: Specifying Channel Authorizations, Acima: Canais [Conteúdo][Índice]
Channel authors can indicate the primary URL of their channel’s Git repository in the .guix-channel file, like so:
(channel
(version 0)
(url "https://example.org/guix.git"))
This allows guix pull
to determine whether it is pulling code from
a mirror of the channel; when that is the case, it warns the user that the
mirror might be stale and displays the primary URL. That way, users cannot
be tricked into fetching code from a stale mirror that does not receive
security updates.
This feature only makes sense for authenticated repositories, such as the
official guix
channel, for which guix pull
ensures the code
it fetches is authentic.
Anterior: Primary URL, Acima: Canais [Conteúdo][Índice]
Channel authors may occasionally want to communicate to their users information about important changes in the channel. You’d send them all an email, but that’s not convenient.
Instead, channels can provide a news file; when the channel users run
guix pull
, that news file is automatically read and guix
pull --news
can display the announcements that correspond to the new
commits that have been pulled, if any.
To do that, channel authors must first declare the name of the news file in their .guix-channel file:
(channel
(version 0)
(news-file "etc/news.txt"))
The news file itself, etc/news.txt in this example, must look something like this:
(channel-news
(version 0)
(entry (tag "the-bug-fix")
(title (en "Fixed terrible bug")
(fr "Oh la la"))
(body (en "@emph{Good news}! It's fixed!")
(eo "Certe ĝi pli bone funkcias nun!")))
(entry (commit "bdcabe815cd28144a2d2b4bc3c5057b051fa9906")
(title (en "Added a great package")
(ca "Què vol dir guix?"))
(body (en "Don't miss the @code{hello} package!"))))
While the news file is using the Scheme syntax, avoid naming it with a .scm extension or else it will get picked up when building the channel and yield an error since it is not a valid module. Alternatively, you can move the channel module to a subdirectory and store the news file in another directory.
The file consists of a list of news entries. Each entry is associated with a commit or tag: it describes changes made in this commit, possibly in preceding commits as well. Users see entries only the first time they obtain the commit the entry refers to.
The title
field should be a one-line summary while body
can be
arbitrarily long, and both can contain Texinfo markup (veja Overview em GNU Texinfo). Both the title and body are a list of language
tag/message tuples, which allows guix pull
to display news in the
language that corresponds to the user’s locale.
If you want to translate news using a gettext-based workflow, you can
extract translatable strings with xgettext
(veja xgettext
Invocation em GNU Gettext Utilities). For example, assuming you
write news entries in English first, the command below creates a PO file
containing the strings to translate:
xgettext -o news.po -l scheme -ken etc/news.txt
To sum up, yes, you could use your channel as a blog. But beware, this is not quite what your users might expect.
Próximo: Interface de programação, Anterior: Canais, Acima: GNU Guix [Conteúdo][Índice]
If you are a software developer, Guix provides tools that you should find helpful—independently of the language you’re developing in. This is what this chapter is about.
The guix shell
command provides a convenient way to set up one-off
software environments, be it for development purposes or to run a command
without installing it in your profile. The guix pack
command
allows you to create application bundles that can be easily
distributed to users who do not run Guix.
guix shell
guix environment
guix pack
guix git authenticate
Próximo: Invocando guix environment
, Acima: Desenvolvimento [Conteúdo][Índice]
guix shell
The purpose of guix shell
is to make it easy to create one-off
software environments, without changing one’s profile. It is typically used
to create development environments; it is also a convenient way to run
applications without “polluting” your profile.
Nota: The
guix shell
command was recently introduced to supersedeguix environment
(veja Invocandoguix environment
). If you are familiar withguix environment
, you will notice that it is similar but also—we hope!—more convenient.
The general syntax is:
guix shell [options] [package…]
The following example creates an environment containing Python and NumPy,
building or downloading any missing package, and runs the python3
command in that environment:
guix shell python python-numpy -- python3
Note that it is necessary to include the main python
package in this
command even if it is already installed into your environment. This is so
that the shell environment knows to set PYTHONPATH
and other related
variables. The shell environment cannot check the previously installed
environment, because then it would be non-deterministic. This is true for
most libraries: their corresponding language package should be included in
the shell invocation.
Nota:
guix shell
can be also be used as a script interpreter, also known as shebang. Here is an example self-contained Python script making use of this feature:#!/usr/bin/env -S guix shell python python-numpy -- python3 import numpy print("This is numpy", numpy.version.version)You may pass any
guix shell
option, but there’s one caveat: the Linux kernel has a limit of 127 bytes on shebang length.
Development environments can be created as in the example below, which spawns an interactive shell containing all the dependencies and environment variables needed to work on Inkscape:
guix shell --development inkscape
Exiting the shell places the user back in the original environment before
guix shell
was invoked. The next garbage collection
(veja Invocando guix gc
) may clean up packages that were installed in the
environment and that are no longer used outside of it.
As an added convenience, guix shell
will try to do what you mean
when it is invoked interactively without any other arguments as in:
guix shell
If it finds a manifest.scm in the current working directory or any of
its parents, it uses this manifest as though it was given via
--manifest
. Likewise, if it finds a guix.scm in the same
directories, it uses it to build a development profile as though both
--development
and --file
were present. In either case, the
file will only be loaded if the directory it resides in is listed in
~/.config/guix/shell-authorized-directories. This provides an easy
way to define, share, and enter development environments.
By default, the shell session or command runs in an augmented
environment, where the new packages are added to search path environment
variables such as PATH
. You can, instead, choose to create an
isolated environment containing nothing but the packages you asked
for. Passing the --pure option clears environment variable
definitions found in the parent environment14; passing --container goes one step further by
spawning a container isolated from the rest of the system:
guix shell --container emacs gcc-toolchain
The command above spawns an interactive shell in a container where nothing
but emacs
, gcc-toolchain
, and their dependencies is
available. The container lacks network access and shares no files other
than the current working directory with the surrounding environment. This
is useful to prevent access to system-wide resources such as /usr/bin
on foreign distros.
This --container option can also prove useful if you wish to run a security-sensitive application, such as a web browser, in an isolated environment. For example, the command below launches Ungoogled-Chromium in an isolated environment, which:
DISPLAY
and XAUTHORITY
XAUTHORITY
file
guix shell --container --network --no-cwd ungoogled-chromium \ --preserve='^XAUTHORITY$' --expose="${XAUTHORITY}" \ --preserve='^DISPLAY$' -- chromium
guix shell
defines the GUIX_ENVIRONMENT
variable in the
shell it spawns; its value is the file name of the profile of this
environment. This allows users to, say, define a specific prompt for
development environments in their .bashrc (veja Bash Startup
Files em The GNU Bash Reference Manual):
if [ -n "$GUIX_ENVIRONMENT" ] then export PS1="\u@\h \w [dev]\$ " fi
... or to browse the profile:
$ ls "$GUIX_ENVIRONMENT/bin"
The available options are summarized below.
--check
Set up the environment and check whether the shell would clobber environment
variables. It’s a good idea to use this option the first time you run
guix shell
for an interactive session to make sure your setup is
correct.
For example, if the shell modifies the PATH
environment variable,
report it since you would get a different environment than what you asked
for.
Such problems usually indicate that the shell startup files are unexpectedly modifying those environment variables. For example, if you are using Bash, make sure that environment variables are set or modified in ~/.bash_profile and not in ~/.bashrc—the former is sourced only by log-in shells. Veja Bash Startup Files em The GNU Bash Reference Manual, for details on Bash start-up files.
--development
-D
Cause guix shell
to include in the environment the dependencies of
the following package rather than the package itself. This can be combined
with other packages. For instance, the command below starts an interactive
shell containing the build-time dependencies of GNU Guile, plus
Autoconf, Automake, and Libtool:
guix shell -D guile autoconf automake libtool
--expression=expr
-e expr
Create an environment for the package or list of packages that expr evaluates to.
For example, running:
guix shell -D -e '(@ (gnu packages maths) petsc-openmpi)'
starts a shell with the environment for this specific variant of the PETSc package.
Running:
guix shell -e '(@ (gnu) %base-packages)'
starts a shell with all the base system packages available.
The above commands only use the default output of the given packages. To select other outputs, two element tuples can be specified:
guix shell -e '(list (@ (gnu packages bash) bash) "include")'
Veja package->development-manifest
,
for information on how to write a manifest for the development environment
of a package.
--file=file
-f arquivo
Create an environment containing the package or list of packages that the code within file evaluates to.
As an example, file might contain a definition like this (veja Definindo pacotes):
(use-modules (guix) (gnu packages gdb) (gnu packages autotools) (gnu packages texinfo)) ;; Augment the package definition of GDB with the build tools ;; needed when developing GDB (and which are not needed when ;; simply installing it.) (package (inherit gdb) (native-inputs (modify-inputs (package-native-inputs gdb) (prepend autoconf-2.69 automake texinfo))))
With the file above, you can enter a development environment for GDB by running:
guix shell -D -f gdb-devel.scm
--manifest=arquivo
-m arquivo
Create an environment for the packages contained in the manifest object returned by the Scheme code in file. This option can be repeated several times, in which case the manifests are concatenated.
This is similar to the same-named option in guix package
(veja --manifest) and uses the same manifest
files.
Veja Writing Manifests, for information on how to write a manifest. See --export-manifest below on how to obtain a first manifest.
--export-manifest
Write to standard output a manifest suitable for --manifest corresponding to given command-line options.
This is a way to “convert” command-line arguments into a manifest. For example, imagine you are tired of typing long lines and would like to get a manifest equivalent to this command line:
guix shell -D guile git emacs emacs-geiser emacs-geiser-guile
Just add --export-manifest to the command line above:
guix shell --export-manifest \ -D guile git emacs emacs-geiser emacs-geiser-guile
... and you get a manifest along these lines:
(concatenate-manifests
(list (specifications->manifest
(list "git"
"emacs"
"emacs-geiser"
"emacs-geiser-guile"))
(package->development-manifest
(specification->package "guile"))))
You can store it into a file, say manifest.scm, and from there pass
it to guix shell
or indeed pretty much any guix
command:
guix shell -m manifest.scm
Voilà, you’ve converted a long command line into a manifest! That conversion process honors package transformation options (veja Opções de transformação de pacote) so it should be lossless.
--profile=perfil
-p perfil
Create an environment containing the packages installed in profile.
Use guix package
(veja Invocando guix package
) to create and
manage profiles.
--pure
Unset existing environment variables when building the new environment, except those specified with --preserve (see below). This has the effect of creating an environment in which search paths only contain package inputs.
--preserve=regexp
-E regexp
When used alongside --pure, preserve the environment variables matching regexp—in other words, put them on a “white list” of environment variables that must be preserved. This option can be repeated several times.
guix shell --pure --preserve=^SLURM openmpi … \ -- mpirun …
This example runs mpirun
in a context where the only environment
variables defined are PATH
, environment variables whose name starts
with ‘SLURM’, as well as the usual “precious” variables (HOME
,
USER
, etc.).
--search-paths
Display the environment variable definitions that make up the environment.
--system=system
-s sistema
Attempt to build for system—e.g., i686-linux
.
--container
¶-C
Run command within an isolated container. The current working directory outside the container is mapped inside the container. Additionally, unless overridden with --user, a dummy home directory is created that matches the current user’s home directory, and /etc/passwd is configured accordingly.
The spawned process runs as the current user outside the container. Inside the container, it has the same UID and GID as the current user, unless --user is passed (see below).
--network
-N
For containers, share the network namespace with the host system. Containers created without this flag only have access to the loopback device.
--link-profile
-P
For containers, link the environment profile to ~/.guix-profile
within the container and set GUIX_ENVIRONMENT
to that. This is
equivalent to making ~/.guix-profile a symlink to the actual profile
within the container. Linking will fail and abort the environment if the
directory already exists, which will certainly be the case if guix
shell
was invoked in the user’s home directory.
Certain packages are configured to look in ~/.guix-profile for configuration files and data;15 --link-profile allows these programs to behave as expected within the environment.
--user=user
-u usuário
For containers, use the username user in place of the current user. The generated /etc/passwd entry within the container will contain the name user, the home directory will be /home/user, and no user GECOS data will be copied. Furthermore, the UID and GID inside the container are 1000. user need not exist on the system.
Additionally, any shared or exposed path (see --share and --expose respectively) whose target is within the current user’s home directory will be remapped relative to /home/USER; this includes the automatic mapping of the current working directory.
# will expose paths as /home/foo/wd, /home/foo/test, and /home/foo/target cd $HOME/wd guix shell --container --user=foo \ --expose=$HOME/test \ --expose=/tmp/target=$HOME/target
While this will limit the leaking of user identity through home paths and each of the user fields, this is only one useful component of a broader privacy/anonymity solution—not one in and of itself.
--no-cwd
For containers, the default behavior is to share the current working directory with the isolated container and immediately change to that directory within the container. If this is undesirable, --no-cwd will cause the current working directory to not be automatically shared and will change to the user’s home directory within the container instead. See also --user.
--expose=fonte[=alvo]
--share=fonte[=alvo]
For containers, --expose (resp. --share) exposes the file system source from the host system as the read-only (resp. writable) file system target within the container. If target is not specified, source is used as the target mount point in the container.
The example below spawns a Guile REPL in a container in which the user’s home directory is accessible read-only via the /exchange directory:
guix shell --container --expose=$HOME=/exchange guile -- guile
--symlink=spec
-S spec
For containers, create the symbolic links specified by spec, as documented in pack-symlink-option.
--emulate-fhs
-F
When used with --container, emulate a Filesystem Hierarchy Standard (FHS) configuration within the container, providing /bin, /lib, and other directories and files specified by the FHS.
As Guix deviates from the FHS specification, this option sets up the container to more closely mimic that of other GNU/Linux distributions. This is useful for reproducing other development environments, testing, and using programs which expect the FHS specification to be followed. With this option, the container will include a version of glibc that will read /etc/ld.so.cache within the container for the shared library cache (contrary to glibc in regular Guix usage) and set up the expected FHS directories: /bin, /etc, /lib, and /usr from the container’s profile.
--nesting
-W
When used with --container, provide Guix inside the container and arrange so that it can interact with the build daemon that runs outside the container. This is useful if you want, within your isolated container, to create other containers, as in this sample session:
$ guix shell -CW coreutils [env]$ guix shell -C guile -- guile -c '(display "hello!\n")' hello! [env]$ exit
The session above starts a container with coreutils
programs
available in PATH
. From there, we spawn guix shell
to
create a nested container that provides nothing but Guile.
Another example is evaluating a guix.scm file that is untrusted, as shown here:
guix shell -CW -- guix build -f guix.scm
The guix build
command as executed above can only access the
current directory.
Under the hood, the -W option does several things:
guix
invocations are
visible;
guix
command to the profile in the
container, such that guix describe
returns the same state inside
and outside the container;
guix time-machine
and guix shell
.
--rebuild-cache
¶In most cases, guix shell
caches the environment so that
subsequent uses are instantaneous. Least-recently used cache entries are
periodically removed. The cache is also invalidated, when using
--file or --manifest, anytime the corresponding file is
modified.
The --rebuild-cache forces the cached environment to be refreshed.
This is useful when using --file or --manifest and the
guix.scm
or manifest.scm
file has external dependencies,
or if its behavior depends, say, on environment variables.
--root=arquivo
¶-r arquivo
Make file a symlink to the profile for this environment, and register it as a garbage collector root.
This is useful if you want to protect your environment from garbage collection, to make it “persistent”.
When this option is omitted, guix shell
caches profiles so that
subsequent uses of the same environment are instantaneous—this is
comparable to using --root except that guix shell
takes
care of periodically removing the least-recently used garbage collector
roots.
In some cases, guix shell
does not cache profiles—e.g., if
transformation options such as --with-latest are used. In those
cases, the environment is protected from garbage collection only for the
duration of the guix shell
session. This means that next time you
recreate the same environment, you could have to rebuild or re-download
packages.
Veja Invocando guix gc
, for more on GC roots.
guix shell
also supports all of the common build options that
guix build
supports (veja Opções de compilação comum) as well as
package transformation options (veja Opções de transformação de pacote).
Próximo: Invocando guix pack
, Anterior: Invoking guix shell
, Acima: Desenvolvimento [Conteúdo][Índice]
guix environment
The purpose of guix environment
is to assist in creating
development environments.
Deprecation warning: The
guix environment
command is deprecated in favor ofguix shell
, which performs similar functions but is more convenient to use. Veja Invokingguix shell
.Being deprecated,
guix environment
is slated for eventual removal, but the Guix project is committed to keeping it until May 1st, 2023. Please get in touch with us at guix-devel@gnu.org if you would like to discuss it.
The general syntax is:
guix environment options package…
The following example spawns a new shell set up for the development of GNU Guile:
guix environment guile
If the needed dependencies are not built yet, guix environment
automatically builds them. The environment of the new shell is an augmented
version of the environment that guix environment
was run in. It
contains the necessary search paths for building the given package added to
the existing environment variables. To create a “pure” environment, in
which the original environment variables have been unset, use the
--pure option16.
Exiting from a Guix environment is the same as exiting from the shell, and
will place the user back in the old environment before guix
environment
was invoked. The next garbage collection (veja Invocando guix gc
) will clean up packages that were installed from within the environment
and are no longer used outside of it.
guix environment
defines the GUIX_ENVIRONMENT
variable in
the shell it spawns; its value is the file name of the profile of this
environment. This allows users to, say, define a specific prompt for
development environments in their .bashrc (veja Bash Startup
Files em The GNU Bash Reference Manual):
if [ -n "$GUIX_ENVIRONMENT" ] then export PS1="\u@\h \w [dev]\$ " fi
... or to browse the profile:
$ ls "$GUIX_ENVIRONMENT/bin"
Additionally, more than one package may be specified, in which case the union of the inputs for the given packages are used. For example, the command below spawns a shell where all of the dependencies of both Guile and Emacs are available:
guix environment guile emacs
Sometimes an interactive shell session is not desired. An arbitrary command
may be invoked by placing the --
token to separate the command from
the rest of the arguments:
guix environment guile -- make -j4
In other situations, it is more convenient to specify the list of packages
needed in the environment. For example, the following command runs
python
from an environment containing Python 3 and NumPy:
guix environment --ad-hoc python-numpy python -- python3
Furthermore, one might want the dependencies of a package and also some additional packages that are not build-time or runtime dependencies, but are useful when developing nonetheless. Because of this, the --ad-hoc flag is positional. Packages appearing before --ad-hoc are interpreted as packages whose dependencies will be added to the environment. Packages appearing after are interpreted as packages that will be added to the environment directly. For example, the following command creates a Guix development environment that additionally includes Git and strace:
guix environment --pure guix --ad-hoc git strace
Sometimes it is desirable to isolate the environment as much as possible, for maximal purity and reproducibility. In particular, when using Guix on a host distro that is not Guix System, it is desirable to prevent access to /usr/bin and other system-wide resources from the development environment. For example, the following command spawns a Guile REPL in a “container” where only the store and the current working directory are mounted:
guix environment --ad-hoc --container guile -- guile
Nota: The --container option requires Linux-libre 3.19 or newer.
Another typical use case for containers is to run security-sensitive
applications such as a web browser. To run Eolie, we must expose and share
some files and directories; we include nss-certs
and expose
/etc/ssl/certs/ for HTTPS authentication; finally we preserve the
DISPLAY
environment variable since containerized graphical
applications won’t display without it.
guix environment --preserve='^DISPLAY$' --container --network \ --expose=/etc/machine-id \ --expose=/etc/ssl/certs/ \ --share=$HOME/.local/share/eolie/=$HOME/.local/share/eolie/ \ --ad-hoc eolie nss-certs dbus -- eolie
The available options are summarized below.
--check
Set up the environment and check whether the shell would clobber environment variables. Veja --check, for more info.
--root=arquivo
¶-r arquivo
Make file a symlink to the profile for this environment, and register it as a garbage collector root.
This is useful if you want to protect your environment from garbage collection, to make it “persistent”.
When this option is omitted, the environment is protected from garbage
collection only for the duration of the guix environment
session.
This means that next time you recreate the same environment, you could have
to rebuild or re-download packages. Veja Invocando guix gc
, for more on GC
roots.
--expression=expr
-e expr
Create an environment for the package or list of packages that expr evaluates to.
For example, running:
guix environment -e '(@ (gnu packages maths) petsc-openmpi)'
starts a shell with the environment for this specific variant of the PETSc package.
Running:
guix environment --ad-hoc -e '(@ (gnu) %base-packages)'
starts a shell with all the base system packages available.
The above commands only use the default output of the given packages. To select other outputs, two element tuples can be specified:
guix environment --ad-hoc -e '(list (@ (gnu packages bash) bash) "include")'
--load=arquivo
-l arquivo
Create an environment for the package or list of packages that the code within file evaluates to.
As an example, file might contain a definition like this (veja Definindo pacotes):
(use-modules (guix) (gnu packages gdb) (gnu packages autotools) (gnu packages texinfo)) ;; Augment the package definition of GDB with the build tools ;; needed when developing GDB (and which are not needed when ;; simply installing it.) (package (inherit gdb) (native-inputs (modify-inputs (package-native-inputs gdb) (prepend autoconf-2.69 automake texinfo))))
--manifest=arquivo
-m arquivo
Create an environment for the packages contained in the manifest object returned by the Scheme code in file. This option can be repeated several times, in which case the manifests are concatenated.
This is similar to the same-named option in guix package
(veja --manifest) and uses the same manifest
files.
Veja guix shell --export-manifest
, for
information on how to “convert” command-line options into a manifest.
--ad-hoc
Include all specified packages in the resulting environment, as if an ad hoc package were defined with them as inputs. This option is useful for quickly creating an environment without having to write a package expression to contain the desired inputs.
For instance, the command:
guix environment --ad-hoc guile guile-sdl -- guile
runs guile
in an environment where Guile and Guile-SDL are
available.
Note that this example implicitly asks for the default output of
guile
and guile-sdl
, but it is possible to ask for a specific
output—e.g., glib:bin
asks for the bin
output of glib
(veja Pacotes com múltiplas saídas).
This option may be composed with the default behavior of guix
environment
. Packages appearing before --ad-hoc are interpreted
as packages whose dependencies will be added to the environment, the default
behavior. Packages appearing after are interpreted as packages that will be
added to the environment directly.
--profile=perfil
-p perfil
Create an environment containing the packages installed in profile.
Use guix package
(veja Invocando guix package
) to create and
manage profiles.
--pure
Unset existing environment variables when building the new environment, except those specified with --preserve (see below). This has the effect of creating an environment in which search paths only contain package inputs.
--preserve=regexp
-E regexp
When used alongside --pure, preserve the environment variables matching regexp—in other words, put them on a “white list” of environment variables that must be preserved. This option can be repeated several times.
guix environment --pure --preserve=^SLURM --ad-hoc openmpi … \ -- mpirun …
This example runs mpirun
in a context where the only environment
variables defined are PATH
, environment variables whose name starts
with ‘SLURM’, as well as the usual “precious” variables (HOME
,
USER
, etc.).
--search-paths
Display the environment variable definitions that make up the environment.
--system=system
-s sistema
Attempt to build for system—e.g., i686-linux
.
--container
¶-C
Run command within an isolated container. The current working directory outside the container is mapped inside the container. Additionally, unless overridden with --user, a dummy home directory is created that matches the current user’s home directory, and /etc/passwd is configured accordingly.
The spawned process runs as the current user outside the container. Inside the container, it has the same UID and GID as the current user, unless --user is passed (see below).
--network
-N
For containers, share the network namespace with the host system. Containers created without this flag only have access to the loopback device.
--link-profile
-P
For containers, link the environment profile to ~/.guix-profile
within the container and set GUIX_ENVIRONMENT
to that. This is
equivalent to making ~/.guix-profile a symlink to the actual profile
within the container. Linking will fail and abort the environment if the
directory already exists, which will certainly be the case if guix
environment
was invoked in the user’s home directory.
Certain packages are configured to look in ~/.guix-profile for configuration files and data;17 --link-profile allows these programs to behave as expected within the environment.
--user=user
-u usuário
For containers, use the username user in place of the current user. The generated /etc/passwd entry within the container will contain the name user, the home directory will be /home/user, and no user GECOS data will be copied. Furthermore, the UID and GID inside the container are 1000. user need not exist on the system.
Additionally, any shared or exposed path (see --share and --expose respectively) whose target is within the current user’s home directory will be remapped relative to /home/USER; this includes the automatic mapping of the current working directory.
# will expose paths as /home/foo/wd, /home/foo/test, and /home/foo/target cd $HOME/wd guix environment --container --user=foo \ --expose=$HOME/test \ --expose=/tmp/target=$HOME/target
While this will limit the leaking of user identity through home paths and each of the user fields, this is only one useful component of a broader privacy/anonymity solution—not one in and of itself.
--no-cwd
For containers, the default behavior is to share the current working directory with the isolated container and immediately change to that directory within the container. If this is undesirable, --no-cwd will cause the current working directory to not be automatically shared and will change to the user’s home directory within the container instead. See also --user.
--expose=fonte[=alvo]
--share=fonte[=alvo]
For containers, --expose (resp. --share) exposes the file system source from the host system as the read-only (resp. writable) file system target within the container. If target is not specified, source is used as the target mount point in the container.
The example below spawns a Guile REPL in a container in which the user’s home directory is accessible read-only via the /exchange directory:
guix environment --container --expose=$HOME=/exchange --ad-hoc guile -- guile
--emulate-fhs
-F
For containers, emulate a Filesystem Hierarchy Standard (FHS) configuration
within the container, see
the official
specification. As Guix deviates from the FHS specification, this option
sets up the container to more closely mimic that of other GNU/Linux
distributions. This is useful for reproducing other development
environments, testing, and using programs which expect the FHS specification
to be followed. With this option, the container will include a version of
glibc
which will read /etc/ld.so.cache
within the container
for the shared library cache (contrary to glibc
in regular Guix
usage) and set up the expected FHS directories: /bin
, /etc
,
/lib
, and /usr
from the container’s profile.
guix environment
also supports all of the common build options
that guix build
supports (veja Opções de compilação comum) as well as
package transformation options (veja Opções de transformação de pacote).
Próximo: The GCC toolchain, Anterior: Invocando guix environment
, Acima: Desenvolvimento [Conteúdo][Índice]
guix pack
Occasionally you want to pass software to people who are not (yet!) lucky
enough to be using Guix. You’d tell them to run guix package -i
something
, but that’s not possible in this case. This is where
guix pack
comes in.
Nota: If you are looking for ways to exchange binaries among machines that already run Guix, veja Invocando
guix copy
, Invocandoguix publish
, and Invocandoguix archive
.
The guix pack
command creates a shrink-wrapped pack or
software bundle: it creates a tarball or some other archive containing
the binaries of the software you’re interested in, and all its
dependencies. The resulting archive can be used on any machine that does
not have Guix, and people can run the exact same binaries as those you have
with Guix. The pack itself is created in a bit-reproducible fashion, so
anyone can verify that it really contains the build results that you pretend
to be shipping.
For example, to create a bundle containing Guile, Emacs, Geiser, and all their dependencies, you can run:
$ guix pack guile emacs emacs-geiser … /gnu/store/…-pack.tar.gz
The result here is a tarball containing a /gnu/store directory with
all the relevant packages. The resulting tarball contains a profile
with the three packages of interest; the profile is the same as would be
created by guix package -i
. It is this mechanism that is used to
create Guix’s own standalone binary tarball (veja Instalação de binários).
Users of this pack would have to run /gnu/store/…-profile/bin/guile to run Guile, which you may find inconvenient. To work around it, you can create, say, a /opt/gnu/bin symlink to the profile:
guix pack -S /opt/gnu/bin=bin guile emacs emacs-geiser
That way, users can happily type /opt/gnu/bin/guile and enjoy.
What if the recipient of your pack does not have root privileges on their machine, and thus cannot unpack it in the root file system? In that case, you will want to use the --relocatable option (see below). This option produces relocatable binaries, meaning they can be placed anywhere in the file system hierarchy: in the example above, users can unpack your tarball in their home directory and directly run ./opt/gnu/bin/guile.
Alternatively, you can produce a pack in the Docker image format using the following command:
guix pack -f docker -S /bin=bin guile guile-readline
The result is a tarball that can be passed to the docker load
command, followed by docker run
:
docker load < file docker run -ti guile-guile-readline /bin/guile
where file is the image returned by guix pack
, and
guile-guile-readline
is its “image tag”. See the
Docker
documentation for more information.
Yet another option is to produce a SquashFS image with the following command:
guix pack -f squashfs bash guile emacs emacs-geiser
The result is a SquashFS file system image that can either be mounted or
directly be used as a file system container image with the
Singularity container execution
environment, using commands like singularity shell
or
singularity exec
.
Several command-line options allow you to customize your pack:
--format=format
-f format
Produce a pack in the given format.
The available formats are:
tarball
This is the default format. It produces a tarball containing all the specified binaries and symlinks.
docker
This produces a tarball that follows the
Docker Image Specification. By default, the “repository name” as it
appears in the output of the docker images
command is computed
from package names passed on the command line or in the manifest file.
Alternatively, the “repository name” can also be configured via the
--image-tag option. Refer to --help-docker-format for
more information on such advanced options.
squashfs
This produces a SquashFS image containing all the specified binaries and symlinks, as well as empty mount points for virtual file systems like procfs.
Nota: Singularity requires you to provide /bin/sh in the image. For that reason,
guix pack -f squashfs
always implies-S /bin=bin
. Thus, yourguix pack
invocation must always start with something like:guix pack -f squashfs bash …If you forget the
bash
(or similar) package,singularity run
andsingularity exec
will fail with an unhelpful “no such file or directory” message.
deb
¶This produces a Debian archive (a package with the ‘.deb’ file extension) containing all the specified binaries and symbolic links, that can be installed on top of any dpkg-based GNU(/Linux) distribution. Advanced options can be revealed via the --help-deb-format option. They allow embedding control files for more fine-grained control, such as activating specific triggers or providing a maintainer configure script to run arbitrary setup code upon installation.
guix pack -f deb -C xz -S /usr/bin/hello=bin/hello hello
Nota: Because archives produced with
guix pack
contain a collection of store items and because eachdpkg
package must not have conflicting files, in practice that means you likely won’t be able to install more than one such archive on a given system. You can nonetheless pack as many Guix packages as you want in one such archive.
Aviso:
dpkg
will assume ownership of any files contained in the pack that it does not know about. It is unwise to install Guix-produced ‘.deb’ files on a system where /gnu/store is shared by other software, such as a Guix installation or other, non-deb packs.
rpm
¶This produces an RPM archive (a package with the ‘.rpm’ file extension)
containing all the specified binaries and symbolic links, that can be
installed on top of any RPM-based GNU/Linux distribution. The RPM format
embeds checksums for every file it contains, which the rpm
command
uses to validate the integrity of the archive.
Advanced RPM-related options are revealed via the --help-rpm-format option. These options allow embedding maintainer scripts that can run before or after the installation of the RPM archive, for example.
The RPM format supports relocatable packages via the --prefix
option of the rpm
command, which can be handy to install an RPM
package to a specific prefix.
guix pack -f rpm -R -C xz -S /usr/bin/hello=bin/hello hello
sudo rpm --install --prefix=/opt /gnu/store/...-hello.rpm
Nota: Contrary to Debian packages, conflicting but identical files in RPM packages can be installed simultaneously, which means multiple
guix pack
-produced RPM packages can usually be installed side by side without any problem.
Aviso:
rpm
assumes ownership of any files contained in the pack, which means it will remove /gnu/store upon uninstalling a Guix-generated RPM package, unless the RPM package was installed with the --prefix option of therpm
command. It is unwise to install Guix-produced ‘.rpm’ packages on a system where /gnu/store is shared by other software, such as a Guix installation or other, non-rpm packs.
--relocatable
-R
Produce relocatable binaries—i.e., binaries that can be placed anywhere in the file system hierarchy and run from there.
When this option is passed once, the resulting binaries require support for user namespaces in the kernel Linux; when passed twice18, relocatable binaries fall to back to other techniques if user namespaces are unavailable, and essentially work anywhere—see below for the implications.
For example, if you create a pack containing Bash with:
guix pack -RR -S /mybin=bin bash
... you can copy that pack to a machine that lacks Guix, and from your home directory as a normal user, run:
tar xf pack.tar.gz ./mybin/sh
In that shell, if you type ls /gnu/store
, you’ll notice that
/gnu/store shows up and contains all the dependencies of bash
,
even though the machine actually lacks /gnu/store altogether! That is
probably the simplest way to deploy Guix-built software on a non-Guix
machine.
Nota: By default, relocatable binaries rely on the user namespace feature of the kernel Linux, which allows unprivileged users to mount or change root. Old versions of Linux did not support it, and some GNU/Linux distributions turn it off.
To produce relocatable binaries that work even in the absence of user namespaces, pass --relocatable or -R twice. In that case, binaries will try user namespace support and fall back to another execution engine if user namespaces are not supported. The following execution engines are supported:
default
Try user namespaces and fall back to PRoot if user namespaces are not supported (see below).
performance
Try user namespaces and fall back to Fakechroot if user namespaces are not supported (see below).
userns
Run the program through user namespaces and abort if they are not supported.
proot
Run through PRoot. The PRoot program provides the necessary support for file system virtualization. It achieves that by using the
ptrace
system call on the running program. This approach has the advantage to work without requiring special kernel support, but it incurs run-time overhead every time a system call is made.fakechroot
Run through Fakechroot. Fakechroot virtualizes file system accesses by intercepting calls to C library functions such as
open
,stat
,exec
, and so on. Unlike PRoot, it incurs very little overhead. However, it does not always work: for example, some file system accesses made from within the C library are not intercepted, and file system accesses made via direct syscalls are not intercepted either, leading to erratic behavior.When running a wrapped program, you can explicitly request one of the execution engines listed above by setting the
GUIX_EXECUTION_ENGINE
environment variable accordingly.
--entry-point=command
Use command as the entry point of the resulting pack, if the
pack format supports it—currently docker
and squashfs
(Singularity) support it. command must be relative to the profile
contained in the pack.
The entry point specifies the command that tools like docker run
or
singularity run
automatically start by default. For example, you can
do:
guix pack -f docker --entry-point=bin/guile guile
The resulting pack can easily be loaded and docker run
with no extra
arguments will spawn bin/guile
:
docker load -i pack.tar.gz docker run image-id
--entry-point-argument=command
-A command
Use command as an argument to entry point of the resulting
pack. This option is only valid in conjunction with --entry-point
and can appear multiple times on the command line.
guix pack -f docker --entry-point=bin/guile --entry-point-argument="--help" guile
--max-layers=n
Specifies the maximum number of Docker image layers allowed when building an image.
guix pack -f docker --max-layers=100 guile
This option allows you to limit the number of layers in a Docker image. Docker images are comprised of multiple layers, and each layer adds to the overall size and complexity of the image. By setting a maximum number of layers, you can control the following effects:
--expression=expr
-e expr
Consider the package expr evaluates to.
This has the same purpose as the same-named option in guix build
(veja --expression in guix
build
).
--manifest=arquivo
-m arquivo
Use the packages contained in the manifest object returned by the Scheme code in file. This option can be repeated several times, in which case the manifests are concatenated.
This has a similar purpose as the same-named option in guix
package
(veja --manifest) and uses the same
manifest files. It allows you to define a collection of packages once and
use it both for creating profiles and for creating archives for use on
machines that do not have Guix installed. Note that you can specify
either a manifest file or a list of packages, but not both.
Veja Writing Manifests, for information on how to write a manifest.
Veja guix shell --export-manifest
, for
information on how to “convert” command-line options into a manifest.
--system=system
-s sistema
Attempt to build for system—e.g., i686-linux
—instead of the
system type of the build host.
--target=triplet
¶Cross-build for triplet, which must be a valid GNU triplet, such as
"aarch64-linux-gnu"
(veja GNU
configuration triplets em Autoconf).
--compression=tool
-C tool
Compress the resulting tarball using tool—one of gzip
,
zstd
, bzip2
, xz
, lzip
, or none
for no
compression.
--symlink=spec
-S spec
Add the symlinks specified by spec to the pack. This option can appear several times.
spec has the form source=target
, where source
is the symlink that will be created and target is the symlink target.
For instance, -S /opt/gnu/bin=bin
creates a /opt/gnu/bin
symlink pointing to the bin sub-directory of the profile.
--save-provenance
Save provenance information for the packages passed on the command line. Provenance information includes the URL and commit of the channels in use (veja Canais).
Provenance information is saved in the /gnu/store/…-profile/manifest file in the pack, along with the usual package metadata—the name and version of each package, their propagated inputs, and so on. It is useful information to the recipient of the pack, who then knows how the pack was (supposedly) obtained.
This option is not enabled by default because, like timestamps, provenance information contributes nothing to the build process. In other words, there is an infinity of channel URLs and commit IDs that can lead to the same pack. Recording such “silent” metadata in the output thus potentially breaks the source-to-binary bitwise reproducibility property.
--root=arquivo
¶-r arquivo
Make file a symlink to the resulting pack, and register it as a garbage collector root.
--localstatedir
--profile-name=name
Include the “local state directory”, /var/guix, in the resulting
pack, and notably the /var/guix/profiles/per-user/root/name
profile—by default name is guix-profile
, which corresponds to
~root/.guix-profile.
/var/guix contains the store database (veja O armazém) as well as
garbage-collector roots (veja Invocando guix gc
). Providing it in the
pack means that the store is “complete” and manageable by Guix; not
providing it pack means that the store is “dead”: items cannot be added to
it or removed from it after extraction of the pack.
One use case for this is the Guix self-contained binary tarball (veja Instalação de binários).
--derivation
-d
Print the name of the derivation that builds the pack.
--bootstrap
Use the bootstrap binaries to build the pack. This option is only useful to Guix developers.
In addition, guix pack
supports all the common build options
(veja Opções de compilação comum) and all the package transformation options
(veja Opções de transformação de pacote).
Próximo: Invoking guix git authenticate
, Anterior: Invocando guix pack
, Acima: Desenvolvimento [Conteúdo][Índice]
If you need a complete toolchain for compiling and linking C or C++ source
code, use the gcc-toolchain
package. This package provides a
complete GCC toolchain for C/C++ development, including GCC itself, the GNU
C Library (headers and binaries, plus debugging symbols in the debug
output), Binutils, and a linker wrapper.
The wrapper’s purpose is to inspect the -L
and -l
switches
passed to the linker, add corresponding -rpath
arguments, and invoke
the actual linker with this new set of arguments. You can instruct the
wrapper to refuse to link against libraries not in the store by setting the
GUIX_LD_WRAPPER_ALLOW_IMPURITIES
environment variable to no
.
The package gfortran-toolchain
provides a complete GCC toolchain for
Fortran development. For other languages, please use ‘guix search gcc
toolchain’ (veja Invoking guix package).
Anterior: The GCC toolchain, Acima: Desenvolvimento [Conteúdo][Índice]
guix git authenticate
The guix git authenticate
command authenticates a Git checkout
following the same rule as for channels (veja channel authentication). That is, starting from a given commit, it ensures
that all subsequent commits are signed by an OpenPGP key whose fingerprint
appears in the .guix-authorizations file of its parent commit(s).
You will find this command useful if you maintain a channel. But in fact, this authentication mechanism is useful in a broader context, so you might want to use it for Git repositories that have nothing to do with Guix.
The general syntax is:
guix git authenticate commit signer [options…]
By default, this command authenticates the Git checkout in the current directory; it outputs nothing and exits with exit code zero on success and non-zero on failure. commit above denotes the first commit where authentication takes place, and signer is the OpenPGP fingerprint of public key used to sign commit. Together, they form a channel introduction (veja channel introduction). On your first successful run, the introduction is recorded in the .git/config file of your checkout, allowing you to omit them from subsequent invocations:
guix git authenticate [options…]
Should you have branches that require different introductions, you can
specify them directly in .git/config. For example, if the branch
called personal-fork
has a different introduction than other
branches, you can extend .git/config along these lines:
[guix "authentication-personal-fork"] introduction-commit = cabba936fd807b096b48283debdcddccfea3900d introduction-signer = C0FF EECA BBA9 E6A8 0D1D E643 A2A0 6DF2 A33A 54FA keyring = keyring
The first run also attempts to install pre-push and post-merge hooks, such
that guix git authenticate
is invoked as soon as you run
git push
, git pull
, and related commands; it does not
overwrite preexisting hooks though.
The command-line options described below allow you to fine-tune the process.
--repository=directory
-r directory
Open the Git repository in directory instead of the current directory.
--keyring=reference
-k reference
Load OpenPGP keyring from reference, the reference of a branch such as
origin/keyring
or my-keyring
. The branch must contain OpenPGP
public keys in .key files, either in binary form or
“ASCII-armored”. By default the keyring is loaded from the branch named
keyring
.
--end=commit
Authenticate revisions up to commit.
--stats
Display commit signing statistics upon completion.
--cache-key=key
Previously-authenticated commits are cached in a file under ~/.cache/guix/authentication. This option forces the cache to be stored in file key in that directory.
--historical-authorizations=file
By default, any commit whose parent commit(s) lack the .guix-authorizations file is considered inauthentic. In contrast, this option considers the authorizations in file for any commit that lacks .guix-authorizations. The format of file is the same as that of .guix-authorizations (veja .guix-authorizations format).
Próximo: Utilitários, Anterior: Desenvolvimento, Acima: GNU Guix [Conteúdo][Índice]
GNU Guix provides several Scheme programming interfaces (APIs) to define, build, and query packages. The first interface allows users to write high-level package definitions. These definitions refer to familiar packaging concepts, such as the name and version of a package, its build system, and its dependencies. These definitions can then be turned into concrete build actions.
Build actions are performed by the Guix daemon, on behalf of users. In a standard setup, the daemon has write access to the store—the /gnu/store directory—whereas users do not. The recommended setup also has the daemon perform builds in chroots, under specific build users, to minimize interference with the rest of the system.
Lower-level APIs are available to interact with the daemon and the store. To instruct the daemon to perform a build action, users actually provide it with a derivation. A derivation is a low-level representation of the build actions to be taken, and the environment in which they should occur—derivations are to package definitions what assembly is to C programs. The term “derivation” comes from the fact that build results derive from them.
This chapter describes all these APIs in turn, starting from high-level package definitions. Veja Source Tree Structure, for a more general overview of the source code.
guix repl
Próximo: Definindo pacotes, Acima: Interface de programação [Conteúdo][Índice]
From a programming viewpoint, the package definitions of the GNU
distribution are provided by Guile modules in the (gnu packages
…)
name space19
(veja Guile modules em GNU Guile Reference Manual). For
instance, the (gnu packages emacs)
module exports a variable named
emacs
, which is bound to a <package>
object (veja Definindo pacotes).
The (gnu packages …)
module name space is automatically scanned
for packages by the command-line tools. For instance, when running
guix install emacs
, all the (gnu packages …)
modules are
scanned until one that exports a package object whose name is emacs
is found. This package search facility is implemented in the (gnu
packages)
module.
Users can store package definitions in modules with different names—e.g.,
(my-packages emacs)
20. There are two ways to make these package definitions visible to
the user interfaces:
-L
flag of guix package
and other commands
(veja Opções de compilação comum), or by setting the GUIX_PACKAGE_PATH
environment variable described below.
guix pull
so that it
pulls from it. A channel is essentially a Git repository containing package
modules. Veja Canais, for more information on how to define and use
channels.
GUIX_PACKAGE_PATH
works similarly to other search path variables:
This is a colon-separated list of directories to search for additional package modules. Directories listed in this variable take precedence over the own modules of the distribution.
The distribution is fully bootstrapped and self-contained: each
package is built based solely on other packages in the distribution. The
root of this dependency graph is a small set of bootstrap binaries,
provided by the (gnu packages bootstrap)
module. For more
information on bootstrapping, veja Inicializando.
Próximo: Defining Package Variants, Anterior: Módulos de pacote, Acima: Interface de programação [Conteúdo][Índice]
The high-level interface to package definitions is implemented in the
(guix packages)
and (guix build-system)
modules. As an
example, the package definition, or recipe, for the GNU Hello package
looks like this:
(define-module (gnu packages hello) #:use-module (guix packages) #:use-module (guix download) #:use-module (guix build-system gnu) #:use-module (guix licenses) #:use-module (gnu packages gawk)) (define-public hello (package (name "hello") (version "2.10") (source (origin (method url-fetch) (uri (string-append "mirror://gnu/hello/hello-" version ".tar.gz")) (sha256 (base32 "0ssi1wpaf7plaswqqjwigppsg5fyh99vdlb9kzl7c9lng89ndq1i")))) (build-system gnu-build-system) (arguments '(#:configure-flags '("--enable-silent-rules"))) (inputs (list gawk)) (synopsis "Hello, GNU world: An example GNU package") (description "Guess what GNU Hello prints!") (home-page "https://www.gnu.org/software/hello/") (license gpl3+)))
Without being a Scheme expert, the reader may have guessed the meaning of
the various fields here. This expression binds the variable hello
to
a <package>
object, which is essentially a record (veja Scheme records em GNU Guile Reference Manual). This package object
can be inspected using procedures found in the (guix packages)
module; for instance, (package-name hello)
returns—surprise!—"hello"
.
With luck, you may be able to import part or all of the definition of the
package you are interested in from another repository, using the guix
import
command (veja Invoking guix import
).
In the example above, hello
is defined in a module of its own,
(gnu packages hello)
. Technically, this is not strictly necessary,
but it is convenient to do so: all the packages defined in modules under
(gnu packages …)
are automatically known to the command-line
tools (veja Módulos de pacote).
There are a few points worth noting in the above package definition:
source
field of the package is an <origin>
object
(veja origin
Reference, for the complete reference). Here, the
url-fetch
method from (guix download)
is used, meaning that
the source is a file to be downloaded over FTP or HTTP.
The mirror://gnu
prefix instructs url-fetch
to use one of the
GNU mirrors defined in (guix download)
.
The sha256
field specifies the expected SHA256 hash of the file being
downloaded. It is mandatory, and allows Guix to check the integrity of the
file. The (base32 …)
form introduces the base32 representation
of the hash. You can obtain this information with guix download
(veja Invocando guix download
) and guix hash
(veja Invocando guix hash
).
When needed, the origin
form can also have a patches
field
listing patches to be applied, and a snippet
field giving a Scheme
expression to modify the source code.
build-system
field specifies the procedure to build the package
(veja Sistemas de compilação). Here, gnu-build-system
represents the
familiar GNU Build System, where packages may be configured, built, and
installed with the usual ./configure && make && make check && make
install
command sequence.
When you start packaging non-trivial software, you may need tools to manipulate those build phases, manipulate files, and so on. Veja Build Utilities, for more on this.
arguments
field specifies options for the build system
(veja Sistemas de compilação). Here it is interpreted by gnu-build-system
as a request run configure with the --enable-silent-rules
flag.
What about these quote ('
) characters? They are Scheme syntax to
introduce a literal list; '
is synonymous with quote
.
Sometimes you’ll also see `
(a backquote, synonymous with
quasiquote
) and ,
(a comma, synonymous with unquote
).
Veja quoting em GNU Guile Reference Manual, for
details. Here the value of the arguments
field is a list of
arguments passed to the build system down the road, as with apply
(veja apply
em GNU Guile Reference Manual).
The hash-colon (#:
) sequence defines a Scheme keyword
(veja Keywords em GNU Guile Reference Manual), and
#:configure-flags
is a keyword used to pass a keyword argument to the
build system (veja Coding With Keywords em GNU Guile Reference
Manual).
inputs
field specifies inputs to the build process—i.e.,
build-time or run-time dependencies of the package. Here, we add an input,
a reference to the gawk
variable; gawk
is itself bound to a
<package>
object.
Note that GCC, Coreutils, Bash, and other essential tools do not need to be
specified as inputs here. Instead, gnu-build-system
takes care of
ensuring that they are present (veja Sistemas de compilação).
However, any other dependencies need to be specified in the inputs
field. Any dependency not specified here will simply be unavailable to the
build process, possibly leading to a build failure.
Veja package
Reference, for a full description of possible fields.
Indo além: Intimidated by the Scheme language or curious about it? The Cookbook has a short section to get started that recaps some of the things shown above and explains the fundamentals. Veja A Scheme Crash Course em GNU Guix Cookbook, for more information.
Once a package definition is in place, the package may actually be built
using the guix build
command-line tool (veja Invocando guix build
),
troubleshooting any build failures you encounter (veja Depurando falhas de compilação). You can easily jump back to the package definition using the
guix edit
command (veja Invocando guix edit
). Veja Diretrizes de empacotamento, for more information on how to test package definitions, and
Invocando guix lint
, for information on how to check a definition for
style conformance.
Lastly, veja Canais, for information on how to extend the distribution
by adding your own package definitions in a “channel”.
Finally, updating the package definition to a new upstream version can be
partly automated by the guix refresh
command (veja Invocando guix refresh
).
Behind the scenes, a derivation corresponding to the <package>
object
is first computed by the package-derivation
procedure. That
derivation is stored in a .drv file under /gnu/store. The
build actions it prescribes may then be realized by using the
build-derivations
procedure (veja O armazém).
Return the <derivation>
object of package for system
(veja Derivações).
package must be a valid <package>
object, and system must
be a string denoting the target system type—e.g., "x86_64-linux"
for an x86_64 Linux-based GNU system. store must be a connection to
the daemon, which operates on the store (veja O armazém).
Similarly, it is possible to compute a derivation that cross-builds a package for some other system:
Return the <derivation>
object of package cross-built from
system to target.
target must be a valid GNU triplet denoting the target hardware and
operating system, such as "aarch64-linux-gnu"
(veja Specifying
Target Triplets em Autoconf).
Once you have package definitions, you can easily define variants of those packages. Veja Defining Package Variants, for more on that.
Próximo: origin
Reference, Acima: Definindo pacotes [Conteúdo][Índice]
package
ReferenceThis section summarizes all the options available in package
declarations (veja Definindo pacotes).
This is the data type representing a package recipe.
name
The name of the package, as a string.
version
The version of the package, as a string. Veja Números de versão, for guidelines.
source
An object telling how the source code for the package should be acquired.
Most of the time, this is an origin
object, which denotes a file
fetched from the Internet (veja origin
Reference). It can also be any
other “file-like” object such as a local-file
, which denotes a file
from the local file system (veja local-file
).
build-system
The build system that should be used to build the package (veja Sistemas de compilação).
arguments
(default: '()
)The arguments that should be passed to the build system (veja Sistemas de compilação). This is a list, typically containing sequential keyword-value pairs, as in this example:
(package
(name "example")
;; several fields omitted
(arguments
(list #:tests? #f ;skip tests
#:make-flags #~'("VERBOSE=1") ;pass flags to 'make'
#:configure-flags #~'("--enable-frobbing"))))
The exact set of supported keywords depends on the build system
(veja Sistemas de compilação), but you will find that almost all of them honor
#:configure-flags
, #:make-flags
, #:tests?
, and
#:phases
. The #:phases
keyword in particular lets you modify
the set of build phases for your package (veja Build Phases).
The REPL has dedicated commands to interactively inspect values of some of these arguments, as a convenient debugging aid (veja Using Guix Interactively).
Compatibility Note: Until version 1.3.0, the
arguments
field would typically usequote
('
) orquasiquote
(`
) and no G-expressions, like so:(package ;; several fields omitted (arguments ;old-style quoted arguments '(#:tests? #f #:configure-flags '("--enable-frobbing"))))
To convert from that style to the one shown above, you can run
guix style -S arguments package
(veja Invokingguix style
).
inputs
(default: '()
) ¶native-inputs
(default: '()
)propagated-inputs
(default: '()
)These fields list dependencies of the package. Each element of these lists is either a package, origin, or other “file-like object” (veja Expressões-G); to specify the output of that file-like object that should be used, pass a two-element list where the second element is the output (veja Pacotes com múltiplas saídas, for more on package outputs). For example, the list below specifies three inputs:
(list libffi libunistring `(,glib "bin")) ;the "bin" output of GLib
In the example above, the "out"
output of libffi
and
libunistring
is used.
Compatibility Note: Until version 1.3.0, input lists were a list of tuples, where each tuple has a label for the input (a string) as its first element, a package, origin, or derivation as its second element, and optionally the name of the output thereof that should be used, which defaults to
"out"
. For example, the list below is equivalent to the one above, but using the old input style:;; Old input style (deprecated). `(("libffi" ,libffi) ("libunistring" ,libunistring) ("glib:bin" ,glib "bin")) ;the "bin" output of GLibThis style is now deprecated; it is still supported but support will be removed in a future version. It should not be used for new package definitions. Veja Invoking
guix style
, on how to migrate to the new style.
The distinction between native-inputs
and inputs
is necessary
when considering cross-compilation. When cross-compiling, dependencies
listed in inputs
are built for the target architecture;
conversely, dependencies listed in native-inputs
are built for the
architecture of the build machine.
native-inputs
is typically used to list tools needed at build time,
but not at run time, such as Autoconf, Automake, pkg-config, Gettext, or
Bison. guix lint
can report likely mistakes in this area
(veja Invocando guix lint
).
Lastly, propagated-inputs
is similar to inputs
, but the
specified packages will be automatically installed to profiles
(veja the role of profiles in Guix) alongside the package they
belong to (veja guix package
,
for information on how guix package
deals with propagated inputs).
For example this is necessary when packaging a C/C++ library that needs
headers of another library to compile, or when a pkg-config file refers to
another one via its Requires
field.
Another example where propagated-inputs
is useful is for languages
that lack a facility to record the run-time search path akin to the
RUNPATH
of ELF files; this includes Guile, Python, Perl, and more.
When packaging libraries written in those languages, ensure they can find
library code they depend on at run time by listing run-time dependencies in
propagated-inputs
rather than inputs
.
outputs
(default: '("out")
)The list of output names of the package. Veja Pacotes com múltiplas saídas, for typical uses of additional outputs.
native-search-paths
(default: '()
)search-paths
(default: '()
)A list of search-path-specification
objects describing search-path
environment variables honored by the package. Veja Search Paths, for more
on search path specifications.
As for inputs, the distinction between native-search-paths
and
search-paths
only matters when cross-compiling. In a
cross-compilation context, native-search-paths
applies exclusively to
native inputs whereas search-paths
applies only to host inputs.
Packages such as cross-compilers care about target inputs—for instance,
our (modified) GCC cross-compiler has CROSS_C_INCLUDE_PATH
in
search-paths
, which allows it to pick .h files for the target
system and not those of native inputs. For the majority of packages
though, only native-search-paths
makes sense.
replacement
(default: #f
)This must be either #f
or a package object that will be used as a
replacement for this package. Veja grafts, for
details.
synopsis
A one-line description of the package.
description
A more elaborate description of the package, as a string in Texinfo syntax.
license
¶The license of the package; a value from (guix licenses)
, or a list
of such values.
página inicial
The URL to the home-page of the package, as a string.
supported-systems
(default: %supported-systems
)The list of systems supported by the package, as strings of the form
architecture-kernel
, for example "x86_64-linux"
.
location
(default: source location of the package
form)The source location of the package. It is useful to override this when inheriting from another package, in which case this field is not automatically corrected.
When used in the lexical scope of a package field definition, this identifier resolves to the package being defined.
The example below shows how to add a package as a native input of itself when cross-compiling:
(package
(name "guile")
;; ...
;; When cross-compiled, Guile, for example, depends on
;; a native version of itself. Add it here.
(native-inputs (if (%current-target-system)
(list this-package)
'())))
It is an error to refer to this-package
outside a package definition.
The following helper procedures are provided to help deal with package inputs.
Look up name among package’s inputs (or native, propagated, or
direct inputs). Return it if found, #f
otherwise.
name is the name of a package depended on. Here’s how you might use it:
(use-modules (guix packages) (gnu packages base)) (lookup-package-direct-input coreutils "gmp") ⇒ #<package gmp@6.2.1 …>
In this example we obtain the gmp
package that is among the direct
inputs of coreutils
.
Sometimes you will want to obtain the list of inputs needed to
develop a package—all the inputs that are visible when the package
is compiled. This is what the package-development-inputs
procedure
returns.
Return the list of inputs required by package for development purposes
on system. When target is true, return the inputs needed to
cross-compile package from system to target, where
target is a triplet such as "aarch64-linux-gnu"
.
Note that the result includes both explicit inputs and implicit
inputs—inputs automatically added by the build system (veja Sistemas de compilação). Let us take the hello
package to illustrate that:
(use-modules (gnu packages base) (guix packages)) hello ⇒ #<package hello@2.10 gnu/packages/base.scm:79 7f585d4f6790> (package-direct-inputs hello) ⇒ () (package-development-inputs hello) ⇒ (("source" …) ("tar" #<package tar@1.32 …>) …)
In this example, package-direct-inputs
returns the empty list,
because hello
has zero explicit dependencies. Conversely,
package-development-inputs
includes inputs implicitly added by
gnu-build-system
that are required to build hello
: tar, gzip,
GCC, libc, Bash, and more. To visualize it, guix graph hello
would show you explicit inputs, whereas guix graph -t bag hello
would include implicit inputs (veja Invocando guix graph
).
Because packages are regular Scheme objects that capture a complete dependency graph and associated build procedures, it is often useful to write procedures that take a package and return a modified version thereof according to some parameters. Below are a few examples.
Return a variant of package that uses toolchain instead of the
default GNU C/C++ toolchain. toolchain must be a list of inputs
(label/package tuples) providing equivalent functionality, such as the
gcc-toolchain
package.
The example below returns a variant of the hello
package built with
GCC 10.x and the rest of the GNU tool chain (Binutils and the GNU C
Library) instead of the default tool chain:
(let ((toolchain (specification->package "gcc-toolchain@10")))
(package-with-c-toolchain hello `(("toolchain" ,toolchain))))
The build tool chain is part of the implicit inputs of packages—it’s usually not listed as part of the various “inputs” fields and is instead pulled in by the build system. Consequently, this procedure works by changing the build system of package so that it pulls in toolchain instead of the defaults. Sistemas de compilação, for more on build systems.
Anterior: package
Reference, Acima: Definindo pacotes [Conteúdo][Índice]
origin
ReferenceThis section documents origins. An origin
declaration
specifies data that must be “produced”—downloaded, usually—and whose
content hash is known in advance. Origins are primarily used to represent
the source code of packages (veja Definindo pacotes). For that reason,
the origin
form allows you to declare patches to apply to the
original source code as well as code snippets to modify it.
This is the data type representing a source code origin.
uri
An object containing the URI of the source. The object type depends on the
method
(see below). For example, when using the url-fetch
method of (guix download)
, the valid uri
values are: a URL
represented as a string, or a list thereof.
method
A monadic procedure that handles the given URI. The procedure must accept
at least three arguments: the value of the uri
field and the hash
algorithm and hash value specified by the hash
field. It must return
a store item or a derivation in the store monad (veja A mônada do armazém);
most methods return a fixed-output derivation (veja Derivações).
Commonly used methods include url-fetch
, which fetches data from a
URL, and git-fetch
, which fetches data from a Git repository (see
below).
sha256
A bytevector containing the SHA-256 hash of the source. This is equivalent
to providing a content-hash
SHA256 object in the hash
field
described below.
hash (masc.)
The content-hash
object of the source—see below for how to use
content-hash
.
You can obtain this information using guix download
(veja Invocando guix download
) or guix hash
(veja Invocando guix hash
).
file-name
(default: #f
)The file name under which the source code should be saved. When this is
#f
, a sensible default value will be used in most cases. In case the
source is fetched from a URL, the file name from the URL will be used. For
version control checkouts, it is recommended to provide the file name
explicitly because the default is not very descriptive.
patches
(default: '()
)A list of file names, origins, or file-like objects (veja file-like objects) pointing to patches to be applied to the source.
This list of patches must be unconditional. In particular, it cannot depend
on the value of %current-system
or %current-target-system
.
snippet
(default: #f
)A G-expression (veja Expressões-G) or S-expression that will be run in the source directory. This is a convenient way to modify the source, sometimes more convenient than a patch.
patch-flags
(default: '("-p1")
)A list of command-line flags that should be passed to the patch
command.
patch-inputs
(default: #f
)Input packages or derivations to the patching process. When this is
#f
, the usual set of inputs necessary for patching are provided, such
as GNU Patch.
modules
(default: '()
)A list of Guile modules that should be loaded during the patching process
and while running the code in the snippet
field.
patch-guile
(default: #f
)The Guile package that should be used in the patching process. When this is
#f
, a sensible default is used.
Construct a content hash object for the given algorithm, and with
value as its hash value. When algorithm is omitted, assume it
is sha256
.
value can be a literal string, in which case it is base32-decoded, or it can be a bytevector.
The following forms are all equivalent:
(content-hash "05zxkyz9bv3j9h0xyid1rhvh3klhsmrpkf3bcs6frvlgyr2gwilj") (content-hash "05zxkyz9bv3j9h0xyid1rhvh3klhsmrpkf3bcs6frvlgyr2gwilj" sha256) (content-hash (base32 "05zxkyz9bv3j9h0xyid1rhvh3klhsmrpkf3bcs6frvlgyr2gwilj")) (content-hash (base64 "kkb+RPaP7uyMZmu4eXPVkM4BN8yhRd8BTHLslb6f/Rc=") sha256)
Technically, content-hash
is currently implemented as a macro. It
performs sanity checks at macro-expansion time, when possible, such as
ensuring that value has the right size for algorithm.
As we have seen above, how exactly the data an origin refers to is retrieved
is determined by its method
field. The (guix download)
module
provides the most common method, url-fetch
, described below.
Return a fixed-output derivation that fetches data from url (a string, or a list of strings denoting alternate URLs), which is expected to have hash hash of type hash-algo (a symbol). By default, the file name is the base name of URL; optionally, name can specify a different file name. When executable? is true, make the downloaded file executable.
When one of the URL starts with mirror://
, then its host part is
interpreted as the name of a mirror scheme, taken from %mirror-file.
Alternatively, when URL starts with file://
, return the corresponding
file name in the store.
Likewise, the (guix git-download)
module defines the git-fetch
origin method, which fetches data from a Git version control repository, and
the git-reference
data type to describe the repository and revision
to fetch.
Return a fixed-output derivation that fetches ref, a
<git-reference>
object. The output is expected to have recursive
hash hash of type hash-algo (a symbol). Use name as the
file name, or a generic name if #f
.
This is a variant of the git-fetch
procedure that supports the Git
LFS (Large File Storage) extension. This may be useful to pull
some binary test data to run the test suite of a package, for example.
This data type represents a Git reference for git-fetch
to retrieve.
url
The URL of the Git repository to clone.
commit
This string denotes either the commit to fetch (a hexadecimal string), or
the tag to fetch. You can also use a “short” commit ID or a git
describe
style identifier such as v1.0.1-10-g58d7909c97
.
recursive?
(default: #f
)This Boolean indicates whether to recursively fetch Git sub-modules.
The example below denotes the v2.10
tag of the GNU Hello
repository:
(git-reference
(url "https://git.savannah.gnu.org/git/hello.git")
(commit "v2.10"))
This is equivalent to the reference below, which explicitly names the commit:
(git-reference
(url "https://git.savannah.gnu.org/git/hello.git")
(commit "dc7dc56a00e48fe6f231a58f6537139fe2908fb9"))
For Mercurial repositories, the module (guix hg-download)
defines the
hg-fetch
origin method and hg-reference
data type for support
of the Mercurial version control system.
Return a fixed-output derivation that fetches ref, a
<hg-reference>
object. The output is expected to have recursive hash
hash of type hash-algo (a symbol). Use name as the file
name, or a generic name if #f
.
This data type represents a Mercurial reference for hg-fetch
to
retrieve.
url
The URL of the Mercurial repository to clone.
changeset
This string denotes changeset to fetch.
For Subversion repositories, the module (guix svn-download)
defines
the svn-fetch
origin method and svn-reference
data type for
support of the Subversion version control system.
Return a fixed-output derivation that fetches ref, a
<svn-reference>
object. The output is expected to have recursive
hash hash of type hash-algo (a symbol). Use name as the
file name, or a generic name if #f
.
This data type represents a Subversion reference for svn-fetch
to
retrieve.
url
The URL of the Subversion repository to clone.
revision
This string denotes revision to fetch specified as a number.
recursive?
(default: #f
)This Boolean indicates whether to recursively fetch Subversion “externals”.
user-name
(default: #f
)The name of an account that has read-access to the repository, if the repository isn’t public.
password
(default: #f
)Password to access the Subversion repository, if required.
For Bazaar repositories, the module (guix bzr-download)
defines the
bzr-fetch
origin method and bzr-reference
data type for
support of the Bazaar version control system.
Return a fixed-output derivation that fetches ref, a
<bzr-reference>
object. The output is expected to have recursive
hash hash of type hash-algo (a symbol). Use name as the
file name, or a generic name if #f
.
This data type represents a Bazaar reference for bzr-fetch
to
retrieve.
url
The URL of the Bazaar repository to clone.
revision
This string denotes revision to fetch specified as a number.
For CVS repositories, the module (guix cvs-download)
defines the
cvs-fetch
origin method and cvs-reference
data type for
support of the Concurrent Versions System (CVS).
Return a fixed-output derivation that fetches ref, a
<cvs-reference>
object. The output is expected to have recursive
hash hash of type hash-algo (a symbol). Use name as the
file name, or a generic name if #f
.
This data type represents a CVS reference for cvs-fetch
to retrieve.
root-directory
The CVS root directory.
modulo
Module to fetch.
revision
Revision to fetch.
The example below denotes a version of gnu-standards to fetch:
(cvs-reference
(root-directory ":pserver:anonymous@cvs.savannah.gnu.org:/sources/gnustandards")
(module "gnustandards")
(revision "2020-11-25"))
Próximo: Writing Manifests, Anterior: Definindo pacotes, Acima: Interface de programação [Conteúdo][Índice]
One of the nice things with Guix is that, given a package definition, you can easily derive variants of that package—for a different upstream version, with different dependencies, different compilation options, and so on. Some of these custom packages can be defined straight from the command line (veja Opções de transformação de pacote). This section describes how to define package variants in code. This can be useful in “manifests” (veja Writing Manifests) and in your own package collection (veja Creating a Channel), among others!
As discussed earlier, packages are first-class objects in the Scheme
language. The (guix packages)
module provides the package
construct to define new package objects (veja package
Reference). The
easiest way to define a package variant is using the inherit
keyword
together with package
. This allows you to inherit from a package
definition while overriding the fields you want.
For example, given the hello
variable, which contains a definition
for the current version of GNU Hello, here’s how you would define a
variant for version 2.2 (released in 2006, it’s vintage!):
(use-modules (gnu packages base)) ;for 'hello' (define hello-2.2 (package (inherit hello) (version "2.2") (source (origin (method url-fetch) (uri (string-append "mirror://gnu/hello/hello-" version ".tar.gz")) (sha256 (base32 "0lappv4slgb5spyqbh6yl5r013zv72yqg2pcl30mginf3wdqd8k9"))))))
The example above corresponds to what the --with-version or
--with-source package transformations option do. Essentially
hello-2.2
preserves all the fields of hello
, except
version
and source
, which it overrides. Note that the
original hello
variable is still there, in the (gnu packages
base)
module, unchanged. When you define a custom package like this, you
are really adding a new package definition; the original one remains
available.
You can just as well define variants with a different set of dependencies
than the original package. For example, the default gdb
package
depends on guile
, but since that is an optional dependency, you can
define a variant that removes that dependency like so:
(use-modules (gnu packages gdb)) ;for 'gdb' (define gdb-sans-guile (package (inherit gdb) (inputs (modify-inputs (package-inputs gdb) (delete "guile")))))
The modify-inputs
form above removes the "guile"
package from
the inputs
field of gdb
. The modify-inputs
macro is a
helper that can prove useful anytime you want to remove, add, or replace
package inputs.
Modify the given package inputs, as returned by package-inputs
& co.,
according to the given clauses. Each clause must have one of the following
forms:
(delete name…)
Delete from the inputs packages with the given names (strings).
(prepend package…)
Add packages to the front of the input list.
(append package…)
Add packages to the end of the input list.
(replace name replacement)
Replace the package called name with replacement.
The example below removes the GMP and ACL inputs of Coreutils and adds libcap to the front of the input list:
(modify-inputs (package-inputs coreutils)
(delete "gmp" "acl")
(prepend libcap))
The example below replaces the guile
package from the inputs of
guile-redis
with guile-2.2
:
(modify-inputs (package-inputs guile-redis)
(replace "guile" guile-2.2))
The last type of clause is append
, to add inputs at the back of the
list.
In some cases, you may find it useful to write functions (“procedures”, in
Scheme parlance) that return a package based on some parameters. For
example, consider the luasocket
library for the Lua programming
language. We want to create luasocket
packages for major versions of
Lua. One way to do that is to define a procedure that takes a Lua package
and returns a luasocket
package that depends on it:
(define (make-lua-socket name lua) ;; Return a luasocket package built with LUA. (package (name name) (version "3.0") ;; several fields omitted (inputs (list lua)) (synopsis "Socket library for Lua"))) (define-public lua5.1-socket (make-lua-socket "lua5.1-socket" lua-5.1)) (define-public lua5.2-socket (make-lua-socket "lua5.2-socket" lua-5.2))
Here we have defined packages lua5.1-socket
and lua5.2-socket
by calling make-lua-socket
with different arguments.
Veja Procedures em GNU Guile Reference Manual, for more info on
procedures. Having top-level public definitions for these two packages
means that they can be referred to from the command line (veja Módulos de pacote).
These are pretty simple package variants. As a convenience, the (guix
transformations)
module provides a high-level interface that directly maps
to the more sophisticated package transformation options (veja Opções de transformação de pacote):
Return a procedure that, when passed an object to build (package, derivation, etc.), applies the transformations specified by opts and returns the resulting objects. opts must be a list of symbol/string pairs such as:
((with-branch . "guile-gcrypt=master")
(without-tests . "libgcrypt"))
Each symbol names a transformation and the corresponding string is an argument to that transformation.
For instance, a manifest equivalent to this command:
guix build guix \ --with-branch=guile-gcrypt=master \ --with-debug-info=zlib
... would look like this:
(use-modules (guix transformations)) (define transform ;; The package transformation procedure. (options->transformation '((with-branch . "guile-gcrypt=master") (with-debug-info . "zlib")))) (packages->manifest (list (transform (specification->package "guix"))))
The options->transformation
procedure is convenient, but it’s perhaps
also not as flexible as you may like. How is it implemented? The astute
reader probably noticed that most package transformation options go beyond
the superficial changes shown in the first examples of this section: they
involve input rewriting, whereby the dependency graph of a package is
rewritten by replacing specific inputs by others.
Dependency graph rewriting, for the purposes of swapping packages in the
graph, is what the package-input-rewriting
procedure in (guix
packages)
implements.
Return a procedure that, when passed a package, replaces its direct and indirect dependencies, including implicit inputs when deep? is true, according to replacements. replacements is a list of package pairs; the first element of each pair is the package to replace, and the second one is the replacement.
Optionally, rewrite-name is a one-argument procedure that takes the name of a package and returns its new name after rewrite.
Consider this example:
(define libressl-instead-of-openssl ;; This is a procedure to replace OPENSSL by LIBRESSL, ;; recursively. (package-input-rewriting `((,openssl . ,libressl)))) (define git-with-libressl (libressl-instead-of-openssl git))
Here we first define a rewriting procedure that replaces openssl with libressl. Then we use it to define a variant of the git package that uses libressl instead of openssl. This is exactly what the --with-input command-line option does (veja --with-input).
The following variant of package-input-rewriting
can match packages
to be replaced by name rather than by identity.
Return a procedure that, given a package, applies the given replacements to all the package graph, including implicit inputs unless deep? is false.
replacements is a list of spec/procedures pair; each spec is a package
specification such as "gcc"
or "guile@2"
, and each procedure
takes a matching package and returns a replacement for that package.
Matching packages that have the hidden?
property set are not
replaced.
The example above could be rewritten this way:
(define libressl-instead-of-openssl
;; Replace all the packages called "openssl" with LibreSSL.
(package-input-rewriting/spec `(("openssl" . ,(const libressl)))))
The key difference here is that, this time, packages are matched by spec and
not by identity. In other words, any package in the graph that is called
openssl
will be replaced.
A more generic procedure to rewrite a package dependency graph is
package-mapping
: it supports arbitrary changes to nodes in the graph.
Return a procedure that, given a package, applies proc to all the packages depended on and returns the resulting package. The procedure stops recursion when cut? returns true for a given package. When deep? is true, proc is applied to implicit inputs as well.
Tips: Understanding what a variant really looks like can be difficult as one starts combining the tools shown above. There are several ways to inspect a package before attempting to build it that can prove handy:
- You can inspect the package interactively at the REPL, for instance to view its inputs, the code of its build phases, or its configure flags (veja Using Guix Interactively).
- When rewriting dependencies,
guix graph
can often help visualize the changes that are made (veja Invocandoguix graph
).
Próximo: Sistemas de compilação, Anterior: Defining Package Variants, Acima: Interface de programação [Conteúdo][Índice]
guix
commands let you specify package lists on the command line.
This is convenient, but as the command line becomes longer and less trivial,
it quickly becomes more convenient to have that package list in what we call
a manifest. A manifest is some sort of a “bill of materials” that
defines a package set. You would typically come up with a code snippet that
builds the manifest, store it in a file, say manifest.scm, and then
pass that file to the -m (or --manifest) option that many
guix
commands support. For example, here’s what a manifest for a
simple package set might look like:
;; Manifest for three packages. (specifications->manifest '("gcc-toolchain" "make" "git"))
Once you have that manifest, you can pass it, for example, to guix
package
to install just those three packages to your profile
(veja -m option of guix package
):
guix package -m manifest.scm
... or you can pass it to guix shell
(veja -m
option of guix shell
) to spawn an ephemeral
environment:
guix shell -m manifest.scm
... or you can pass it to guix pack
in pretty much the same way
(veja -m option of guix pack
). You can
store the manifest under version control, share it with others so they can
easily get set up, etc.
But how do you write your first manifest? To get started, maybe you’ll want
to write a manifest that mirrors what you already have in a profile. Rather
than start from a blank page, guix package
can generate a manifest
for you (veja guix package --export-manifest
):
# Write to 'manifest.scm' a manifest corresponding to the # default profile, ~/.guix-profile. guix package --export-manifest > manifest.scm
Or maybe you’ll want to “translate” command-line arguments into a
manifest. In that case, guix shell
can help
(veja guix shell --export-manifest
):
# Write a manifest for the packages specified on the command line. guix shell --export-manifest gcc-toolchain make git > manifest.scm
In both cases, the --export-manifest option tries hard to generate a faithful manifest; in particular, it takes package transformation options into account (veja Opções de transformação de pacote).
Nota: Manifests are symbolic: they refer to packages of the channels currently in use (veja Canais). In the example above,
gcc-toolchain
might refer to version 11 today, but it might refer to version 13 two years from now.If you want to “pin” your software environment to specific package versions and variants, you need an additional piece of information: the list of channel revisions in use, as returned by
guix describe
. Veja Replicating Guix, for more information.
Once you’ve obtained your first manifest, perhaps you’ll want to customize it. Since your manifest is code, you now have access to all the Guix programming interfaces!
Let’s assume you want a manifest to deploy a custom variant of GDB, the GNU Debugger, that does not depend on Guile, together with another package. Building on the example seen in the previous section (veja Defining Package Variants), you can write a manifest along these lines:
(use-modules (guix packages) (gnu packages gdb) ;for 'gdb' (gnu packages version-control)) ;for 'git' ;; Define a variant of GDB without a dependency on Guile. (define gdb-sans-guile (package (inherit gdb) (inputs (modify-inputs (package-inputs gdb) (delete "guile"))))) ;; Return a manifest containing that one package plus Git. (packages->manifest (list gdb-sans-guile git))
Note that in this example, the manifest directly refers to the gdb
and git
variables, which are bound to a package
object
(veja package
Reference), instead of calling
specifications->manifest
to look up packages by name as we did
before. The use-modules
form at the top lets us access the core
package interface (veja Definindo pacotes) and the modules that define
gdb
and git
(veja Módulos de pacote). Seamlessly, we’re
weaving all this together—the possibilities are endless, unleash your
creativity!
The data type for manifests as well as supporting procedures are defined in
the (guix profiles)
module, which is automatically available to code
passed to -m. The reference follows.
Data type representing a manifest.
It currently has one field:
entries
This must be a list of manifest-entry
records—see below.
Data type representing a manifest entry. A manifest entry contains essential metadata: a name and version string, the object (usually a package) for that entry, the desired output (veja Pacotes com múltiplas saídas), and a number of optional pieces of information detailed below.
Most of the time, you won’t build a manifest entry directly; instead, you
will pass a package to package->manifest-entry
, described below. In
some unusual cases though, you might want to create manifest entries for
things that are not packages, as in this example:
;; Manually build a single manifest entry for a non-package object. (let ((hello (program-file "hello" #~(display "Hi!")))) (manifest-entry (name "foo") (version "42") (item (computed-file "hello-directory" #~(let ((bin (string-append #$output "/bin"))) (mkdir #$output) (mkdir bin) (symlink #$hello (string-append bin "/hello")))))))
The available fields are the following:
name
version
Name and version string for this entry.
item
A package or other file-like object (veja file-like objects).
output
(default: "out"
)Output of item
to use, in case item
has multiple outputs
(veja Pacotes com múltiplas saídas).
dependencies
(default: '()
)List of manifest entries this entry depends on. When building a profile, dependencies are added to the profile.
Typically, the propagated inputs of a package (veja propagated-inputs
) end up having a corresponding manifest entry in
among the dependencies of the package’s own manifest entry.
search-paths
(default: '()
)The list of search path specifications honored by this entry (veja Search Paths).
properties
(default: '()
)List of symbol/value pairs. When building a profile, those properties get serialized.
This can be used to piggyback additional metadata—e.g., the transformations applied to a package (veja Opções de transformação de pacote).
parent
(default: (delay #f)
)A promise pointing to the “parent” manifest entry.
This is used as a hint to provide context when reporting an error related to
a manifest entry coming from a dependencies
field.
Concatenate the manifests listed in lst and return the resulting manifest.
Return a manifest entry for the output of package package, where
output defaults to "out"
, and with the given properties.
By default properties is the empty list or, if one or more package
transformations were applied to package, it is an association list
representing those transformations, suitable as an argument to
options->transformation
(veja options->transformation
).
The code snippet below builds a manifest with an entry for the default
output and the send-email
output of the git
package:
(use-modules (gnu packages version-control)) (manifest (list (package->manifest-entry git) (package->manifest-entry git "send-email")))
Return a list of manifest entries, one for each item listed in packages. Elements of packages can be either package objects or package/string tuples denoting a specific output of a package.
Using this procedure, the manifest above may be rewritten more concisely:
(use-modules (gnu packages version-control)) (packages->manifest (list git `(,git "send-email")))
Return a manifest for the development inputs of package for system, optionally when cross-compiling to target. Development inputs include both explicit and implicit inputs of package.
Like the -D option of guix shell
(veja guix shell -D
), the resulting
manifest describes the environment in which one can develop package.
For example, suppose you’re willing to set up a development environment for
Inkscape, with the addition of Git for version control; you can describe
that “bill of materials” with the following manifest:
(use-modules (gnu packages inkscape) ;for 'inkscape' (gnu packages version-control)) ;for 'git' (concatenate-manifests (list (package->development-manifest inkscape) (packages->manifest (list git))))
In this example, the development manifest that
package->development-manifest
returns includes the compiler (GCC),
the many supporting libraries (Boost, GLib, GTK, etc.), and a couple of
additional development tools—these are the dependencies guix show
inkscape
lists.
Last, the (gnu packages)
module provides higher-level facilities to
build manifests. In particular, it lets you look up packages by name—see
below.
Given specs, a list of specifications such as "emacs@25.2"
or
"guile:debug"
, return a manifest. Specs have the format that
command-line tools such as guix install
and guix package
understand (veja Invocando guix package
).
As an example, it lets you rewrite the Git manifest that we saw earlier like this:
(specifications->manifest '("git" "git:send-email"))
Notice that we do not need to worry about use-modules
, importing the
right set of modules, and referring to the right variables. Instead, we
directly refer to packages in the same way as on the command line, which can
often be more convenient.
Próximo: Build Phases, Anterior: Writing Manifests, Acima: Interface de programação [Conteúdo][Índice]
Each package definition specifies a build system and arguments for
that build system (veja Definindo pacotes). This build-system
field represents the build procedure of the package, as well as implicit
dependencies of that build procedure.
Build systems are <build-system>
objects. The interface to create
and manipulate them is provided by the (guix build-system)
module,
and actual build systems are exported by specific modules.
Under the hood, build systems first compile package objects to bags.
A bag is like a package, but with less ornamentation—in other words,
a bag is a lower-level representation of a package, which includes all the
inputs of that package, including some that were implicitly added by the
build system. This intermediate representation is then compiled to a
derivation (veja Derivações). The package-with-c-toolchain
is an
example of a way to change the implicit inputs that a package’s build system
pulls in (veja package-with-c-toolchain
).
Build systems accept an optional list of arguments. In package
definitions, these are passed via the arguments
field
(veja Definindo pacotes). They are typically keyword arguments
(veja keyword arguments in Guile em GNU Guile
Reference Manual). The value of these arguments is usually evaluated in
the build stratum—i.e., by a Guile process launched by the daemon
(veja Derivações).
The main build system is gnu-build-system
, which implements the
standard build procedure for GNU and many other packages. It is provided by
the (guix build-system gnu)
module.
gnu-build-system
represents the GNU Build System, and variants
thereof (veja configuration and makefile conventions em GNU Coding Standards).
In a nutshell, packages using it are configured, built, and installed with
the usual ./configure && make && make check && make install
command
sequence. In practice, a few additional steps are often needed. All these
steps are split up in separate phases. Veja Build Phases, for more
info on build phases and ways to customize them.
In addition, this build system ensures that the “standard” environment for
GNU packages is available. This includes tools such as GCC, libc,
Coreutils, Bash, Make, Diffutils, grep, and sed (see the (guix
build-system gnu)
module for a complete list). We call these the
implicit inputs of a package, because package definitions do not have
to mention them.
This build system supports a number of keyword arguments, which can be
passed via the arguments
field of a package. Here are some of
the main parameters:
#:phases
This argument specifies build-side code that evaluates to an alist of build phases. Veja Build Phases, for more information.
#:configure-flags
This is a list of flags (strings) passed to the configure
script.
Veja Definindo pacotes, for an example.
#:make-flags
This list of strings contains flags passed as arguments to make
invocations in the build
, check
, and install
phases.
#:out-of-source?
This Boolean, #f
by default, indicates whether to run builds in a
build directory separate from the source tree.
When it is true, the configure
phase creates a separate build
directory, changes to that directory, and runs the configure
script
from there. This is useful for packages that require it, such as
glibc
.
#:tests?
This Boolean, #t
by default, indicates whether the check
phase
should run the package’s test suite.
#:test-target
This string, "check"
by default, gives the name of the makefile
target used by the check
phase.
#:parallel-build?
#:parallel-tests?
These Boolean values specify whether to build, respectively run the test
suite, in parallel, with the -j
flag of make
. When they
are true, make
is passed -jn
, where n is the
number specified as the --cores option of guix-daemon
or
that of the guix
client command (veja --cores).
#:validate-runpath?
This Boolean, #t
by default, determines whether to “validate” the
RUNPATH
of ELF binaries (.so
shared libraries as well as
executables) previously installed by the install
phase.
Veja the validate-runpath
phase, for
details.
#:substituível?
This Boolean, #t
by default, tells whether the package outputs should
be substitutable—i.e., whether users should be able to obtain substitutes
for them instead of building locally (veja Substitutos).
#:allowed-references
#:disallowed-references
When true, these arguments must be a list of dependencies that must not appear among the references of the build results. If, upon build completion, some of these references are retained, the build process fails.
This is useful to ensure that a package does not erroneously keep a
reference to some of it build-time inputs, in cases where doing so would,
for example, unnecessarily increase its size (veja Invocando guix size
).
Most other build systems support these keyword arguments.
Other <build-system>
objects are defined to support other conventions
and tools used by free software packages. They inherit most of
gnu-build-system
, and differ mainly in the set of inputs implicitly
added to the build process, and in the list of phases executed. Some of
these build systems are listed below.
This variable is exported by (guix build-system agda)
. It implements
a build procedure for Agda libraries.
It adds agda
to the set of inputs. A different Agda can be specified
with the #:agda
key.
The #:plan
key is a list of cons cells (regexp
. parameters)
, where regexp is a regexp that should match the
.agda
files to build, and parameters is an optional list of
parameters that will be passed to agda
when type-checking it.
When the library uses Haskell to generate a file containing all imports, the
convenience #:gnu-and-haskell?
can be set to #t
to add
ghc
and the standard inputs of gnu-build-system
to the input
list. You will still need to manually add a phase or tweak the
'build
phase, as in the definition of agda-stdlib
.
This variable is exported by (guix build-system ant)
. It implements
the build procedure for Java packages that can be built with
Ant build tool.
It adds both ant
and the Java Development Kit (JDK) as provided
by the icedtea
package to the set of inputs. Different packages can
be specified with the #:ant
and #:jdk
parameters,
respectively.
When the original package does not provide a suitable Ant build file, the
parameter #:jar-name
can be used to generate a minimal Ant build file
build.xml with tasks to build the specified jar archive. In this
case the parameter #:source-dir
can be used to specify the source
sub-directory, defaulting to “src”.
The #:main-class
parameter can be used with the minimal ant buildfile
to specify the main class of the resulting jar. This makes the jar file
executable. The #:test-include
parameter can be used to specify the
list of junit tests to run. It defaults to (list "**/*Test.java")
.
The #:test-exclude
can be used to disable some tests. It defaults to
(list "**/Abstract*.java")
, because abstract classes cannot be run as
tests.
The parameter #:build-target
can be used to specify the Ant task that
should be run during the build
phase. By default the “jar” task
will be run.
This variable is exported by (guix build-system android-ndk)
. It
implements a build procedure for Android NDK (native development kit)
packages using a Guix-specific build process.
The build system assumes that packages install their public interface
(header) files to the subdirectory include of the out
output
and their libraries to the subdirectory lib the out
output.
It’s also assumed that the union of all the dependencies of a package has no conflicting files.
For the time being, cross-compilation is not supported - so right now the libraries and header files are assumed to be host tools.
These variables, exported by (guix build-system asdf)
, implement
build procedures for Common Lisp packages using
“ASDF”. ASDF is a system
definition facility for Common Lisp programs and libraries.
The asdf-build-system/source
system installs the packages in source
form, and can be loaded using any common lisp implementation, via ASDF.
The others, such as asdf-build-system/sbcl
, install binary systems in
the format which a particular implementation understands. These build
systems can also be used to produce executable programs, or lisp images
which contain a set of packages pre-loaded.
The build system uses naming conventions. For binary packages, the package
name should be prefixed with the lisp implementation, such as sbcl-
for asdf-build-system/sbcl
.
Additionally, the corresponding source package should be labeled using the
same convention as Python packages (veja Módulos Python), using the
cl-
prefix.
In order to create executable programs and images, the build-side procedures
build-program
and build-image
can be used. They should be
called in a build phase after the create-asdf-configuration
phase, so
that the system which was just built can be used within the resulting
image. build-program
requires a list of Common Lisp expressions to
be passed as the #:entry-program
argument.
By default, all the .asd files present in the sources are read to
find system definitions. The #:asd-files
parameter can be used to
specify the list of .asd files to read. Furthermore, if the package
defines a system for its tests in a separate file, it will be loaded before
the tests are run if it is specified by the #:test-asd-file
parameter. If it is not set, the files <system>-tests.asd
,
<system>-test.asd
, tests.asd
, and test.asd
will be
tried if they exist.
If for some reason the package must be named in a different way than the
naming conventions suggest, or if several systems must be compiled, the
#:asd-systems
parameter can be used to specify the list of system
names.
This variable is exported by (guix build-system cargo)
. It supports
builds of packages using Cargo, the build tool of the
Rust programming language.
It adds rustc
and cargo
to the set of inputs. A different
Rust package can be specified with the #:rust
parameter.
Regular cargo dependencies should be added to the package definition
similarly to other packages; those needed only at build time to
native-inputs, others to inputs. If you need to add source-only crates then
you should add them to via the #:cargo-inputs
parameter as a list of
name and spec pairs, where the spec can be a package or a source
definition. Note that the spec must evaluate to a path to a gzipped tarball
which includes a Cargo.toml
file at its root, or it will be ignored.
Similarly, cargo dev-dependencies should be added to the package definition
via the #:cargo-development-inputs
parameter.
In its configure
phase, this build system will make any source inputs
specified in the #:cargo-inputs
and #:cargo-development-inputs
parameters available to cargo. It will also remove an included
Cargo.lock
file to be recreated by cargo
during the
build
phase. The package
phase will run cargo package
to create a source crate for future use. The install
phase installs
the binaries defined by the crate. Unless install-source? #f
is
defined it will also install a source crate repository of itself and
unpacked sources, to ease in future hacking on rust packages.
This variable is exported by (guix build-system chicken)
. It builds
CHICKEN Scheme modules, also called “eggs” or
“extensions”. CHICKEN generates C source code, which then gets compiled
by a C compiler, in this case GCC.
This build system adds chicken
to the package inputs, as well as the
packages of gnu-build-system
.
The build system can’t (yet) deduce the egg’s name automatically, so just
like with go-build-system
and its #:import-path
, you should
define #:egg-name
in the package’s arguments
field.
For example, if you are packaging the srfi-1
egg:
(arguments '(#:egg-name "srfi-1"))
Egg dependencies must be defined in propagated-inputs
, not
inputs
because CHICKEN doesn’t embed absolute references in compiled
eggs. Test dependencies should go to native-inputs
, as usual.
This variable is exported by (guix build-system copy)
. It supports
builds of simple packages that don’t require much compiling, mostly just
moving files around.
It adds much of the gnu-build-system
packages to the set of inputs.
Because of this, the copy-build-system
does not require all the
boilerplate code often needed for the trivial-build-system
.
To further simplify the file installation process, an #:install-plan
argument is exposed to let the packager specify which files go where. The
install plan is a list of (source target
[filters])
. filters are optional.
#:include
, #:include-regexp
, #:exclude
,
#:exclude-regexp
, only select files are installed depending on the
filters. Each filters is specified by a list of strings.
#:include
, install all the files which the path suffix matches
at least one of the elements in the given list.
#:include-regexp
, install all the files which the
subpaths match at least one of the regular expressions in the given list.
#:exclude
and #:exclude-regexp
filters
are the complement of their inclusion counterpart. Without #:include
flags, install all files but those matching the exclusion filters. If both
inclusions and exclusions are specified, the exclusions are done on top of
the inclusions.
#:output
argument
can be used to specify which output label the files should be installed to.
In all cases, the paths relative to source are preserved within target.
Examples:
("foo/bar" "share/my-app/")
: Install bar to share/my-app/bar.
("foo/bar" "share/my-app/baz")
: Install bar to share/my-app/baz.
("foo/" "share/my-app")
: Install the content of foo inside share/my-app,
e.g., install foo/sub/file to share/my-app/sub/file.
("foo/" "share/my-app" #:include ("sub/file"))
: Install only foo/sub/file to
share/my-app/sub/file.
("foo/sub" "share/my-app" #:include ("file"))
: Install foo/sub/file to
share/my-app/file.
("foo/doc" "share/my-app/doc" #:output "doc")
: Install
"foo/doc" to "share/my-app/doc" within the "doc"
output.
This variable is exported by (guix build-system vim)
. It is an
extension of the copy-build-system
, installing Vim and Neovim plugins
into locations where these two text editors know to find their plugins,
using their packpaths.
Packages which are prefixed with vim-
will be installed in Vim’s
packpath, while those prefixed with neovim-
will be installed in
Neovim’s packpath. If there is a doc
directory with the plugin then
helptags will be generated automatically.
There are a couple of keywords added with the vim-build-system
:
plugin-name
it is possible to set the name of the plugin.
While by default this is set to the name and version of the package, it is
often more helpful to set this to name which the upstream author calls their
plugin. This is the name used for :packadd
from inside Vim.
install-plan
it is possible to augment the built-in
install-plan of the vim-build-system
. This is particularly helpful
if you have files which should be installed in other locations. For more
information about using the install-plan
, see the
copy-build-system
(veja copy-build-system
).
#:vim
it is possible to add this package to Vim’s packpath,
in addition to if it is added automatically because of the vim-
prefix in the package’s name.
#:neovim
it is possible to add this package to Neovim’s
packpath, in addition to if it is added automatically because of the
neovim-
prefix in the package’s name.
#:mode
it is possible to adjust the path which the plugin is
installed into. By default the plugin is installed into start
and
other options are available, including opt
. Adding a plugin into
opt
will mean you will need to run, for example, :packadd
foo
to load the foo
plugin from inside of Vim.
This variable is exported by (guix build-system clojure)
. It
implements a simple build procedure for Clojure
packages using plain old compile
in Clojure. Cross-compilation is
not supported yet.
It adds clojure
, icedtea
and zip
to the set of inputs.
Different packages can be specified with the #:clojure
, #:jdk
and #:zip
parameters, respectively.
A list of source directories, test directories and jar names can be
specified with the #:source-dirs
, #:test-dirs
and
#:jar-names
parameters, respectively. Compile directory and main
class can be specified with the #:compile-dir
and #:main-class
parameters, respectively. Other parameters are documented below.
This build system is an extension of ant-build-system
, but with the
following phases changed:
build
This phase calls compile
in Clojure to compile source files and runs
jar
to create jars from both source files and compiled files
according to the include list and exclude list specified in
#:aot-include
and #:aot-exclude
, respectively. The exclude
list has priority over the include list. These lists consist of symbols
representing Clojure libraries or the special keyword #:all
representing all Clojure libraries found under the source directories. The
parameter #:omit-source?
decides if source should be included into
the jars.
marcar
This phase runs tests according to the include list and exclude list
specified in #:test-include
and #:test-exclude
, respectively.
Their meanings are analogous to that of #:aot-include
and
#:aot-exclude
, except that the special keyword #:all
now
stands for all Clojure libraries found under the test directories. The
parameter #:tests?
decides if tests should be run.
instalar
This phase installs all jars built previously.
Apart from the above, this build system also contains an additional phase:
install-doc
This phase installs all top-level files with base name matching
%doc-regex
. A different regex can be specified with the
#:doc-regex
parameter. All files (recursively) inside the
documentation directories specified in #:doc-dirs
are installed as
well.
This variable is exported by (guix build-system cmake)
. It
implements the build procedure for packages using the
CMake build tool.
It automatically adds the cmake
package to the set of inputs. Which
package is used can be specified with the #:cmake
parameter.
The #:configure-flags
parameter is taken as a list of flags passed to
the cmake
command. The #:build-type
parameter specifies in
abstract terms the flags passed to the compiler; it defaults to
"RelWithDebInfo"
(short for “release mode with debugging
information”), which roughly means that code is compiled with -O2
-g
, as is the case for Autoconf-based packages by default.
This variable is exported by (guix build-system composer)
. It
implements the build procedure for packages using
Composer, the PHP package manager.
It automatically adds the php
package to the set of inputs. Which
package is used can be specified with the #:php
parameter.
The #:test-target
parameter is used to control which script is run
for the tests. By default, the test
script is run if it exists. If
the script does not exist, the build system will run phpunit
from the
source directory, assuming there is a phpunit.xml file.
This variable is exported by (guix build-system dune)
. It supports
builds of packages using Dune, a build tool for
the OCaml programming language. It is implemented as an extension of the
ocaml-build-system
which is described below. As such, the
#:ocaml
and #:findlib
parameters can be passed to this build
system.
It automatically adds the dune
package to the set of inputs. Which
package is used can be specified with the #:dune
parameter.
There is no configure
phase because dune packages typically don’t
need to be configured. The #:build-flags
parameter is taken as a
list of flags passed to the dune
command during the build.
The #:jbuild?
parameter can be passed to use the jbuild
command instead of the more recent dune
command while building a
package. Its default value is #f
.
The #:package
parameter can be passed to specify a package name,
which is useful when a package contains multiple packages and you want to
build only one of them. This is equivalent to passing the -p
argument to dune
.
This variable is exported by (guix build-system elm)
. It implements
a build procedure for Elm packages similar to
‘elm install’.
The build system adds an Elm compiler package to the set of inputs. The
default compiler package (currently elm-sans-reactor
) can be
overridden using the #:elm
argument. Additionally, Elm packages
needed by the build system itself are added as implicit inputs if they are
not already present: to suppress this behavior, use the
#:implicit-elm-package-inputs?
argument, which is primarily useful
for bootstrapping.
The "dependencies"
and "test-dependencies"
in an Elm package’s
elm.json file correspond to propagated-inputs
and
inputs
, respectively.
Elm requires a particular structure for package names: veja Elm Packages
for more details, including utilities provided by (guix build-system
elm)
.
There are currently a few noteworthy limitations to elm-build-system
:
{ "type": "package" }
in their
elm.json files. Using elm-build-system
to build Elm
applications (which declare { "type": "application" }
) is
possible, but requires ad-hoc modifications to the build phases. For
examples, see the definitions of the elm-todomvc
example application
and the elm
package itself (because the front-end for the ‘elm
reactor’ command is an Elm application).
ELM_HOME
, but this does not yet work well with
elm-build-system
. This limitation primarily affects Elm
applications, because they specify exact versions for their dependencies,
whereas Elm packages specify supported version ranges. As a workaround, the
example applications mentioned above use the
patch-application-dependencies
procedure provided by (guix
build elm-build-system)
to rewrite their elm.json files to refer to
the package versions actually present in the build environment.
Alternatively, Guix package transformations (veja Defining Package Variants) could be used to rewrite an application’s entire dependency
graph.
elm-test-rs
nor
the Node.js-based elm-test
runner has been packaged for Guix yet.
This variable is exported by (guix build-system go)
. It implements a
build procedure for Go packages using the standard
Go
build mechanisms.
The user is expected to provide a value for the key #:import-path
and, in some cases, #:unpack-path
. The
import path corresponds
to the file system path expected by the package’s build scripts and any
referring packages, and provides a unique way to refer to a Go package. It
is typically based on a combination of the package source code’s remote URI
and file system hierarchy structure. In some cases, you will need to unpack
the package’s source code to a different directory structure than the one
indicated by the import path, and #:unpack-path
should be used in
such cases.
Packages that provide Go libraries should install their source code into the
built output. The key #:install-source?
, which defaults to
#t
, controls whether or not the source code is installed. It can be
set to #f
for packages that only provide executable files.
Packages can be cross-built, and if a specific architecture or operating
system is desired then the keywords #:goarch
and #:goos
can be
used to force the package to be built for that architecture and operating
system. The combinations known to Go can be found
in their
documentation.
The key #:go
can be used to specify the Go compiler package with
which to build the package.
This variable is exported by (guix build-system glib-or-gtk)
. It is
intended for use with packages making use of GLib or GTK+.
This build system adds the following two phases to the ones defined by
gnu-build-system
:
glib-or-gtk-wrap
The phase glib-or-gtk-wrap
ensures that programs in bin/ are
able to find GLib “schemas” and
GTK+
modules. This is achieved by wrapping the programs in launch scripts that
appropriately set the XDG_DATA_DIRS
and GTK_PATH
environment
variables.
It is possible to exclude specific package outputs from that wrapping
process by listing their names in the
#:glib-or-gtk-wrap-excluded-outputs
parameter. This is useful when
an output is known not to contain any GLib or GTK+ binaries, and where
wrapping would gratuitously add a dependency of that output on GLib and
GTK+.
glib-or-gtk-compile-schemas
The phase glib-or-gtk-compile-schemas
makes sure that all
GSettings schemas of GLib are compiled. Compilation is performed by the
glib-compile-schemas
program. It is provided by the package
glib:bin
which is automatically imported by the build system. The
glib
package providing glib-compile-schemas
can be
specified with the #:glib
parameter.
Both phases are executed after the install
phase.
This build system is for Guile packages that consist exclusively of Scheme
code and that are so lean that they don’t even have a makefile, let alone a
configure script. It compiles Scheme code using guild
compile
(veja Compilation em GNU Guile Reference Manual) and
installs the .scm and .go files in the right place. It also
installs documentation.
This build system supports cross-compilation by using the --target option of ‘guild compile’.
Packages built with guile-build-system
must provide a Guile package
in their native-inputs
field.
This variable is exported by (guix build-system julia)
. It
implements the build procedure used by julia
packages, which essentially is similar to running ‘julia -e 'using Pkg;
Pkg.add(package)'’ in an environment where JULIA_LOAD_PATH
contains
the paths to all Julia package inputs. Tests are run by calling
/test/runtests.jl
.
The Julia package name and uuid is read from the file Project.toml.
These values can be overridden by passing the argument
#:julia-package-name
(which must be correctly capitalized) or
#:julia-package-uuid
.
Julia packages usually manage their binary dependencies via
JLLWrappers.jl
, a Julia package that creates a module (named after
the wrapped library followed by _jll.jl
.
To add the binary path _jll.jl
packages, you need to patch the files
under src/wrappers/, replacing the call to the macro
JLLWrappers.@generate_wrapper_header
, adding as a second argument
containing the store path the binary.
As an example, in the MbedTLS Julia package, we add a build phase (veja Build Phases) to insert the absolute file name of the wrapped MbedTLS package:
(add-after 'unpack 'override-binary-path
(lambda* (#:key inputs #:allow-other-keys)
(for-each (lambda (wrapper)
(substitute* wrapper
(("generate_wrapper_header.*")
(string-append
"generate_wrapper_header(\"MbedTLS\", \""
(assoc-ref inputs "mbedtls") "\")\n"))))
;; There's a Julia file for each platform, override them all.
(find-files "src/wrappers/" "\\.jl$"))))
Some older packages that aren’t using Project.toml yet, will require
this file to be created, too. It is internally done if the arguments
#:julia-package-name
and #:julia-package-uuid
are provided.
This variable is exported by (guix build-system maven)
. It
implements a build procedure for Maven
packages. Maven is a dependency and lifecycle management tool for Java. A
user of Maven specifies dependencies and plugins in a pom.xml file
that Maven reads. When Maven does not have one of the dependencies or
plugins in its repository, it will download them and use them to build the
package.
The maven build system ensures that maven will not try to download any dependency by running in offline mode. Maven will fail if a dependency is missing. Before running Maven, the pom.xml (and subprojects) are modified to specify the version of dependencies and plugins that match the versions available in the guix build environment. Dependencies and plugins must be installed in the fake maven repository at lib/m2, and are symlinked into a proper repository before maven is run. Maven is instructed to use that repository for the build and installs built artifacts there. Changed files are copied to the lib/m2 directory of the package output.
You can specify a pom.xml file with the #:pom-file
argument,
or let the build system use the default pom.xml file in the sources.
In case you need to specify a dependency’s version manually, you can use the
#:local-packages
argument. It takes an association list where the
key is the groupId of the package and its value is an association list where
the key is the artifactId of the package and its value is the version you
want to override in the pom.xml.
Some packages use dependencies or plugins that are not useful at runtime nor
at build time in Guix. You can alter the pom.xml file to remove them
using the #:exclude
argument. Its value is an association list where
the key is the groupId of the plugin or dependency you want to remove, and
the value is a list of artifactId you want to remove.
You can override the default jdk
and maven
packages with the
corresponding argument, #:jdk
and #:maven
.
The #:maven-plugins
argument is a list of maven plugins used during
the build, with the same format as the inputs
fields of the package
declaration. Its default value is (default-maven-plugins)
which is
also exported.
This variable is exported by (guix build-system minetest)
. It
implements a build procedure for Minetest
mods, which consists of copying Lua code, images and other resources to the
location Minetest searches for mods. The build system also minimises PNG
images and verifies that Minetest can load the mod without errors.
This variable is exported by (guix build-system minify)
. It
implements a minification procedure for simple JavaScript packages.
It adds uglify-js
to the set of inputs and uses it to compress all
JavaScript files in the src directory. A different minifier package
can be specified with the #:uglify-js
parameter, but it is expected
that the package writes the minified code to the standard output.
When the input JavaScript files are not all located in the src
directory, the parameter #:javascript-files
can be used to specify a
list of file names to feed to the minifier.
This variable is exported by (guix build-system mozilla)
. It sets
the --target
and --host
configuration flags to what software
developed by Mozilla expects – due to historical reasons, Mozilla software
expects --host
to be the system that is cross-compiled from and
--target
to be the system that is cross-compiled to, contrary to the
standard Autotools conventions.
This variable is exported by (guix build-system ocaml)
. It
implements a build procedure for OCaml packages,
which consists of choosing the correct set of commands to run for each
package. OCaml packages can expect many different commands to be run. This
build system will try some of them.
When the package has a setup.ml file present at the top-level, it
will run ocaml setup.ml -configure
, ocaml setup.ml -build
and
ocaml setup.ml -install
. The build system will assume that this file
was generated by OASIS and will
take care of setting the prefix and enabling tests if they are not
disabled. You can pass configure and build flags with the
#:configure-flags
and #:build-flags
. The #:test-flags
key can be passed to change the set of flags used to enable tests. The
#:use-make?
key can be used to bypass this system in the build and
install phases.
When the package has a configure file, it is assumed that it is a
hand-made configure script that requires a different argument format than in
the gnu-build-system
. You can add more flags with the
#:configure-flags
key.
When the package has a Makefile file (or #:use-make?
is
#t
), it will be used and more flags can be passed to the build and
install phases with the #:make-flags
key.
Finally, some packages do not have these files and use a somewhat standard
location for its build system. In that case, the build system will run
ocaml pkg/pkg.ml
or ocaml pkg/build.ml
and take care of
providing the path to the required findlib module. Additional flags can be
passed via the #:build-flags
key. Install is taken care of by
opam-installer
. In this case, the opam
package must be
added to the native-inputs
field of the package definition.
Note that most OCaml packages assume they will be installed in the same
directory as OCaml, which is not what we want in guix. In particular, they
will install .so files in their module’s directory, which is usually
fine because it is in the OCaml compiler directory. In guix though, these
libraries cannot be found and we use CAML_LD_LIBRARY_PATH
. This
variable points to lib/ocaml/site-lib/stubslibs and this is where
.so libraries should be installed.
This variable is exported by (guix build-system python)
. It
implements the more or less standard build procedure used by Python
packages, which consists in running python setup.py build
and then
python setup.py install --prefix=/gnu/store/…
.
For packages that install stand-alone Python programs under bin/
, it
takes care of wrapping these programs so that their GUIX_PYTHONPATH
environment variable points to all the Python libraries they depend on.
Which Python package is used to perform the build can be specified with the
#:python
parameter. This is a useful way to force a package to be
built for a specific version of the Python interpreter, which might be
necessary if the package is only compatible with a single interpreter
version.
By default guix calls setup.py
under control of setuptools
,
much like pip
does. Some packages are not compatible with
setuptools (and pip), thus you can disable this by setting the
#:use-setuptools?
parameter to #f
.
If a "python"
output is available, the package is installed into it
instead of the default "out"
output. This is useful for packages that
include a Python package as only a part of the software, and thus want to
combine the phases of python-build-system
with another build system.
Python bindings are a common usecase.
This is a variable exported by guix build-system pyproject
. It is
based on python-build-system, and adds support for
pyproject.toml and PEP 517.
It also supports a variety of build backends and test frameworks.
The API is slightly different from python-build-system:
#:use-setuptools?
and #:test-target
is removed.
#:build-backend
is added. It defaults to #false
and will try
to guess the appropriate backend based on pyproject.toml.
#:test-backend
is added. It defaults to #false
and will guess
an appropriate test backend based on what is available in package inputs.
#:test-flags
is added. The default is '()
. These flags are
passed as arguments to the test command. Note that flags for verbose output
is always enabled on supported backends.
It is considered “experimental” in that the implementation details are not set in stone yet, however users are encouraged to try it for new Python projects (even those using setup.py). The API is subject to change, but any breaking changes in the Guix channel will be dealt with.
Eventually this build system will be deprecated and merged back into python-build-system, probably some time in 2024.
This variable is exported by (guix build-system perl)
. It implements
the standard build procedure for Perl packages, which either consists in
running perl Build.PL --prefix=/gnu/store/…
, followed by
Build
and Build install
; or in running perl Makefile.PL
PREFIX=/gnu/store/…
, followed by make
and make install
,
depending on which of Build.PL
or Makefile.PL
is present in
the package distribution. Preference is given to the former if both
Build.PL
and Makefile.PL
exist in the package distribution.
This preference can be reversed by specifying #t
for the
#:make-maker?
parameter.
The initial perl Makefile.PL
or perl Build.PL
invocation
passes flags specified by the #:make-maker-flags
or
#:module-build-flags
parameter, respectively.
Which Perl package is used can be specified with #:perl
.
This variable is exported by (guix build-system renpy)
. It
implements the more or less standard build procedure used by Ren’py games,
which consists of loading #:game
once, thereby creating bytecode for
it.
It further creates a wrapper script in bin/
and a desktop entry in
share/applications
, both of which can be used to launch the game.
Which Ren’py package is used can be specified with #:renpy
. Games
can also be installed in outputs other than “out” by using
#:output
.
This variable is exported by (guix build-system qt)
. It is intended
for use with applications using Qt or KDE.
This build system adds the following two phases to the ones defined by
cmake-build-system
:
check-setup
The phase check-setup
prepares the environment for running the checks
as commonly used by Qt test programs. For now this only sets some
environment variables: QT_QPA_PLATFORM=offscreen
,
DBUS_FATAL_WARNINGS=0
and CTEST_OUTPUT_ON_FAILURE=1
.
This phase is added before the check
phase. It’s a separate phase to
ease adjusting if necessary.
qt-wrap
The phase qt-wrap
searches for Qt5 plugin paths, QML paths and some
XDG in the inputs and output. In case some path is found, all programs in
the output’s bin/, sbin/, libexec/ and
lib/libexec/ directories are wrapped in scripts defining the
necessary environment variables.
It is possible to exclude specific package outputs from that wrapping
process by listing their names in the #:qt-wrap-excluded-outputs
parameter. This is useful when an output is known not to contain any Qt
binaries, and where wrapping would gratuitously add a dependency of that
output on Qt, KDE, or such.
This phase is added after the install
phase.
This variable is exported by (guix build-system r)
. It implements
the build procedure used by R packages, which
essentially is little more than running ‘R CMD INSTALL
--library=/gnu/store/…’ in an environment where R_LIBS_SITE
contains the paths to all R package inputs. Tests are run after
installation using the R function tools::testInstalledPackage
.
This variable is exported by (guix build-system rakudo)
. It
implements the build procedure used by Rakudo
for Perl6 packages. It installs the package to
/gnu/store/…/NAME-VERSION/share/perl6
and installs the
binaries, library files and the resources, as well as wrap the files under
the bin/
directory. Tests can be skipped by passing #f
to the
tests?
parameter.
Which rakudo package is used can be specified with rakudo
. Which
perl6-tap-harness package used for the tests can be specified with
#:prove6
or removed by passing #f
to the with-prove6?
parameter. Which perl6-zef package used for tests and installing can be
specified with #:zef
or removed by passing #f
to the
with-zef?
parameter.
This variable is exported by (guix build-system rebar)
. It
implements a build procedure around rebar3, a
build system for programs written in the Erlang language.
It adds both rebar3
and the erlang
to the set of inputs.
Different packages can be specified with the #:rebar
and
#:erlang
parameters, respectively.
This build system is based on gnu-build-system
, but with the
following phases changed:
unpack
This phase, after unpacking the source like the gnu-build-system
does, checks for a file contents.tar.gz
at the top-level of the
source. If this file exists, it will be unpacked, too. This eases handling
of package hosted at https://hex.pm/, the Erlang and Elixir package
repository.
bootstrap
configure
There are no bootstrap
and configure
phase because erlang
packages typically don’t need to be configured.
build
This phase runs rebar3 compile
with the flags listed in
#:rebar-flags
.
marcar
Unless #:tests? #f
is passed, this phase runs rebar3 eunit
, or
some other target specified with #:test-target
, with the flags listed
in #:rebar-flags
,
instalar
This installs the files created in the default profile, or some other
profile specified with #:install-profile
.
This variable is exported by (guix build-system texlive)
. It is used
to build TeX packages in batch mode with a specified engine. The build
system sets the TEXINPUTS
variable to find all TeX source files in the
inputs.
By default it tries to run luatex
on all .ins files, and if it
fails to find any, on all .dtx files. A different engine and format
can be specified with, respectively, the #:tex-engine
and
#:tex-format
arguments. Different build targets can be specified
with the #:build-targets
argument, which expects a list of file
names.
It also generates font metrics (i.e., .tfm files) out of Metafont
files whenever possible. Likewise, it can also create TeX formats (i.e.,
.fmt files) listed in the #:create-formats
argument, and
generate a symbolic link from bin/ directory to any script located in
texmf-dist/scripts/, provided its file name is listed in
#:link-scripts
argument.
The build system adds texlive-bin
from (gnu packages tex)
to
the native inputs. It can be overridden with the #:texlive-bin
argument.
The package texlive-latex-bin
, from the same module, contains most of
the tools for building TeX Live packages; for convenience, it is also added
by default to the native inputs. However, this can be troublesome when
building a dependency of texlive-latex-bin
itself. In this
particular situation, the #:texlive-latex-bin?
argument should be set
to #f
.
This variable is exported by (guix build-system ruby)
. It implements
the RubyGems build procedure used by Ruby packages, which involves running
gem build
followed by gem install
.
The source
field of a package that uses this build system typically
references a gem archive, since this is the format that Ruby developers use
when releasing their software. The build system unpacks the gem archive,
potentially patches the source, runs the test suite, repackages the gem, and
installs it. Additionally, directories and tarballs may be referenced to
allow building unreleased gems from Git or a traditional source release
tarball.
Which Ruby package is used can be specified with the #:ruby
parameter. A list of additional flags to be passed to the gem
command can be specified with the #:gem-flags
parameter.
This variable is exported by (guix build-system waf)
. It implements
a build procedure around the waf
script. The common
phases—configure
, build
, and install
—are
implemented by passing their names as arguments to the waf
script.
The waf
script is executed by the Python interpreter. Which Python
package is used to run the script can be specified with the #:python
parameter.
This variable is exported by (guix build-system zig)
. It implements
the build procedures for the Zig build system
(zig build
command).
Selecting this build system adds zig
to the package inputs, in
addition to the packages of gnu-build-system
.
There is no configure
phase because Zig packages typically do not
need to be configured. The #:zig-build-flags
parameter is a list of
flags that are passed to the zig
command during the build. The
#:zig-test-flags
parameter is a list of flags that are passed to the
zig test
command during the check
phase. The default compiler
package can be overridden with the #:zig
argument.
The optional zig-release-type
parameter declares the type of
release. Possible values are: safe
, fast
, or
small
. The default value is #f
, which causes the release flag
to be omitted from the zig
command. That results in a debug
build.
This variable is exported by (guix build-system scons)
. It
implements the build procedure used by the SCons software construction
tool. This build system runs scons
to build the package, scons
test
to run tests, and then scons install
to install the package.
Additional flags to be passed to scons
can be specified with the
#:scons-flags
parameter. The default build and install targets can
be overridden with #:build-targets
and #:install-targets
respectively. The version of Python used to run SCons can be specified by
selecting the appropriate SCons package with the #:scons
parameter.
This variable is exported by (guix build-system haskell)
. It
implements the Cabal build procedure used by Haskell packages, which
involves running runhaskell Setup.hs configure
--prefix=/gnu/store/…
and runhaskell Setup.hs build
. Instead
of installing the package by running runhaskell Setup.hs install
, to
avoid trying to register libraries in the read-only compiler store
directory, the build system uses runhaskell Setup.hs copy
, followed
by runhaskell Setup.hs register
. In addition, the build system
generates the package documentation by running runhaskell Setup.hs
haddock
, unless #:haddock? #f
is passed. Optional Haddock
parameters can be passed with the help of the #:haddock-flags
parameter. If the file Setup.hs
is not found, the build system looks
for Setup.lhs
instead.
Which Haskell compiler is used can be specified with the #:haskell
parameter which defaults to ghc
.
This variable is exported by (guix build-system dub)
. It implements
the Dub build procedure used by D packages, which involves running dub
build
and dub run
. Installation is done by copying the files
manually.
Which D compiler is used can be specified with the #:ldc
parameter
which defaults to ldc
.
This variable is exported by (guix build-system emacs)
. It
implements an installation procedure similar to the packaging system of
Emacs itself (veja Packages em The GNU Emacs Manual).
It first creates the
file, then it byte
compiles all Emacs Lisp files. Differently from the Emacs packaging system,
the Info documentation files are moved to the standard documentation
directory and the dir file is deleted. The Elisp package files are
installed directly under share/emacs/site-lisp.
package
-autoloads.el
This variable is exported by (guix build-system font)
. It implements
an installation procedure for font packages where upstream provides
pre-compiled TrueType, OpenType, etc. font files that merely need to be
copied into place. It copies font files to standard locations in the output
directory.
This variable is exported by (guix build-system meson)
. It
implements the build procedure for packages that use
Meson as their build system.
It adds both Meson and Ninja to the set of
inputs, and they can be changed with the parameters #:meson
and
#:ninja
if needed.
This build system is an extension of gnu-build-system
, but with the
following phases changed to some specific for Meson:
configure
The phase runs meson
with the flags specified in
#:configure-flags
. The flag --buildtype is always set to
debugoptimized
unless something else is specified in
#:build-type
.
build
The phase runs ninja
to build the package in parallel by default, but
this can be changed with #:parallel-build?
.
marcar
The phase runs ‘meson test’ with a base set of options that cannot be
overridden. This base set of options can be extended via the
#:test-options
argument, for example to select or skip a specific
test suite.
instalar
The phase runs ninja install
and can not be changed.
Apart from that, the build system also adds the following phases:
fix-runpath
This phase ensures that all binaries can find the libraries they need. It
searches for required libraries in subdirectories of the package being
built, and adds those to RUNPATH
where needed. It also removes
references to libraries left over from the build phase by meson
, such
as test dependencies, that aren’t actually required for the program to run.
glib-or-gtk-wrap
This phase is the phase provided by glib-or-gtk-build-system
, and it
is not enabled by default. It can be enabled with #:glib-or-gtk?
.
glib-or-gtk-compile-schemas
This phase is the phase provided by glib-or-gtk-build-system
, and it
is not enabled by default. It can be enabled with #:glib-or-gtk?
.
linux-module-build-system
allows building Linux kernel modules.
This build system is an extension of gnu-build-system
, but with the
following phases changed:
configure
This phase configures the environment so that the Linux kernel’s Makefile can be used to build the external kernel module.
build
This phase uses the Linux kernel’s Makefile in order to build the external kernel module.
instalar
This phase uses the Linux kernel’s Makefile in order to install the external kernel module.
It is possible and useful to specify the Linux kernel to use for building
the module (in the arguments
form of a package using the
linux-module-build-system
, use the key #:linux
to specify it).
This variable is exported by (guix build-system node)
. It implements
the build procedure used by Node.js, which
implements an approximation of the npm install
command, followed by
an npm test
command.
Which Node.js package is used to interpret the npm
commands can be
specified with the #:node
parameter which defaults to node
.
This variable is exported by (guix build-system tree-sitter)
. It
implements procedures to compile grammars for the
Tree-sitter parsing
library. It essentially runs tree-sitter generate
to translate
grammar.js
grammars to JSON and then to C. Which it then compiles to
native code.
Tree-sitter packages may support multiple grammars, so this build system
supports a #:grammar-directories
keyword to specify a list of
locations where a grammar.js
file may be found.
Grammars sometimes depend on each other, such as C++ depending on C and TypeScript depending on JavaScript. You may use inputs to declare such dependencies.
Lastly, for packages that do not need anything as sophisticated, a “trivial” build system is provided. It is trivial in the sense that it provides basically no support: it does not pull any implicit inputs, and does not have a notion of build phases.
This variable is exported by (guix build-system trivial)
.
This build system requires a #:builder
argument. This argument must
be a Scheme expression that builds the package output(s)—as with
build-expression->derivation
(veja build-expression->derivation
).
This variable is exported by (guix build-system channel)
.
This build system is meant primarily for internal use. A package using this
build system must have a channel specification as its source
field
(veja Canais); alternatively, its source can be a directory name, in
which case an additional #:commit
argument must be supplied to
specify the commit being built (a hexadecimal string).
Optionally, a #:channels
argument specifying additional channels can
be provided.
The resulting package is a Guix instance of the given channel(s), similar to
how guix time-machine
would build it.
Próximo: Build Utilities, Anterior: Sistemas de compilação, Acima: Interface de programação [Conteúdo][Índice]
Almost all package build systems implement a notion build phases: a
sequence of actions that the build system executes, when you build the
package, leading to the installed byproducts in the store. A notable
exception is the “bare-bones” trivial-build-system
(veja Sistemas de compilação).
As discussed in the previous section, those build systems provide a standard
list of phases. For gnu-build-system
, the main build phases are the
following:
set-paths
Define search path environment variables for all the input packages,
including PATH
(veja Search Paths).
unpack
Unpack the source tarball, and change the current directory to the extracted source tree. If the source is actually a directory, copy it to the build tree, and enter that directory.
patch-source-shebangs
Patch shebangs encountered in source files so they refer to the right store
file names. For instance, this changes #!/bin/sh
to
#!/gnu/store/…-bash-4.3/bin/sh
.
configure
Run the configure script with a number of default options, such as
--prefix=/gnu/store/…, as well as the options specified by
the #:configure-flags
argument.
build
Run make
with the list of flags specified with #:make-flags
.
If the #:parallel-build?
argument is true (the default), build with
make -j
.
marcar
Run make check
, or some other target specified with
#:test-target
, unless #:tests? #f
is passed. If the
#:parallel-tests?
argument is true (the default), run make
check -j
.
instalar
Run make install
with the flags listed in #:make-flags
.
patch-shebangs
Patch shebangs on the installed executable files.
strip
Strip debugging symbols from ELF files (unless #:strip-binaries?
is
false), copying them to the debug
output when available
(veja Instalando arquivos de depuração).
validate-runpath
Validate the RUNPATH
of ELF binaries, unless
#:validate-runpath?
is false (veja Sistemas de compilação).
This validation step consists in making sure that all the shared libraries
needed by an ELF binary, which are listed as DT_NEEDED
entries in its
PT_DYNAMIC
segment, appear in the DT_RUNPATH
entry of that
binary. In other words, it ensures that running or using those binaries
will not result in a “file not found” error at run time. Veja -rpath em The GNU Linker, for more information on
RUNPATH
.
Other build systems have similar phases, with some variations. For example,
cmake-build-system
has same-named phases but its configure
phases runs cmake
instead of ./configure
. Others, such as
python-build-system
, have a wholly different list of standard
phases. All this code runs on the build side: it is evaluated when
you actually build the package, in a dedicated build process spawned by the
build daemon (veja Invocando guix-daemon
).
Build phases are represented as association lists or “alists” (veja Association Lists em GNU Guile Reference Manual) where each key is a symbol for the name of the phase and the associated value is a procedure that accepts an arbitrary number of arguments. By convention, those procedures receive information about the build in the form of keyword parameters, which they can use or ignore.
For example, here is how (guix build gnu-build-system)
defines
%standard-phases
, the variable holding its alist of build
phases21:
;; The build phases of 'gnu-build-system'. (define* (unpack #:key source #:allow-other-keys) ;; Extract the source tarball. (invoke "tar" "xvf" source)) (define* (configure #:key outputs #:allow-other-keys) ;; Run the 'configure' script. Install to output "out". (let ((out (assoc-ref outputs "out"))) (invoke "./configure" (string-append "--prefix=" out)))) (define* (build #:allow-other-keys) ;; Compile. (invoke "make")) (define* (check #:key (test-target "check") (tests? #true) #:allow-other-keys) ;; Run the test suite. (if tests? (invoke "make" test-target) (display "test suite not run\n"))) (define* (install #:allow-other-keys) ;; Install files to the prefix 'configure' specified. (invoke "make" "install")) (define %standard-phases ;; The list of standard phases (quite a few are omitted ;; for brevity). Each element is a symbol/procedure pair. (list (cons 'unpack unpack) (cons 'configure configure) (cons 'build build) (cons 'check check) (cons 'install install)))
This shows how %standard-phases
is defined as a list of
symbol/procedure pairs (veja Pairs em GNU Guile Reference
Manual). The first pair associates the unpack
procedure with the
unpack
symbol—a name; the second pair defines the configure
phase similarly, and so on. When building a package that uses
gnu-build-system
with its default list of phases, those phases are
executed sequentially. You can see the name of each phase started and
completed in the build log of packages that you build.
Let’s now look at the procedures themselves. Each one is defined with
define*
: #:key
lists keyword parameters the procedure accepts,
possibly with a default value, and #:allow-other-keys
specifies that
other keyword parameters are ignored (veja Optional Arguments em GNU Guile Reference Manual).
The unpack
procedure honors the source
parameter, which the
build system uses to pass the file name of the source tarball (or version
control checkout), and it ignores other parameters. The configure
phase only cares about the outputs
parameter, an alist mapping
package output names to their store file name (veja Pacotes com múltiplas saídas). It extracts the file name of for out
, the default output,
and passes it to ./configure
as the installation prefix, meaning
that make install
will eventually copy all the files in that
directory (veja configuration and makefile conventions em GNU Coding Standards). build
and install
ignore
all their arguments. check
honors the test-target
argument,
which specifies the name of the Makefile target to run tests; it prints a
message and skips tests when tests?
is false.
The list of phases used for a particular package can be changed with the
#:phases
parameter of the build system. Changing the set of build
phases boils down to building a new alist of phases based on the
%standard-phases
alist described above. This can be done with
standard alist procedures such as alist-delete
(veja SRFI-1
Association Lists em GNU Guile Reference Manual); however, it is
more convenient to do so with modify-phases
(veja modify-phases
).
Here is an example of a package definition that removes the configure
phase of %standard-phases
and inserts a new phase before the
build
phase, called set-prefix-in-makefile
:
(define-public example
(package
(name "example")
;; other fields omitted
(build-system gnu-build-system)
(arguments
(list
#:phases
#~(modify-phases %standard-phases
(delete 'configure)
(add-before 'build 'set-prefix-in-makefile
(lambda* (#:key inputs #:allow-other-keys)
;; Modify the makefile so that its
;; 'PREFIX' variable points to #$output and
;; 'XMLLINT' points to the correct path.
(substitute* "Makefile"
(("PREFIX =.*")
(string-append "PREFIX = " #$output "\n"))
(("XMLLINT =.*")
(string-append "XMLLINT = "
(search-input-file inputs "/bin/xmllint")
"\n"))))))))))
The new phase that is inserted is written as an anonymous procedure,
introduced with lambda*
; it looks for the xmllint executable
under a /bin directory among the package’s inputs (veja package
Reference). It also honors the outputs
parameter we have seen
before. Veja Build Utilities, for more about the helpers used by this
phase, and for more examples of modify-phases
.
Tip: You can inspect the code associated with a package’s
#:phases
argument interactively, at the REPL (veja Using Guix Interactively).
Keep in mind that build phases are code evaluated at the time the package is
actually built. This explains why the whole modify-phases
expression
above is quoted (it comes after the '
or apostrophe): it is
staged for later execution. Veja Expressões-G, for an explanation
of code staging and the code strata involved.
Próximo: Search Paths, Anterior: Build Phases, Acima: Interface de programação [Conteúdo][Índice]
As soon as you start writing non-trivial package definitions
(veja Definindo pacotes) or other build actions (veja Expressões-G),
you will likely start looking for helpers for “shell-like”
actions—creating directories, copying and deleting files recursively,
manipulating build phases, and so on. The (guix build utils)
module
provides such utility procedures.
Most build systems load (guix build utils)
(veja Sistemas de compilação).
Thus, when writing custom build phases for your package definitions, you can
usually assume those procedures are in scope.
When writing G-expressions, you can import (guix build utils)
on the
“build side” using with-imported-modules
and then put it in scope
with the use-modules
form (veja Using Guile Modules em GNU
Guile Reference Manual):
(with-imported-modules '((guix build utils)) ;import it
(computed-file "empty-tree"
#~(begin
;; Put it in scope.
(use-modules (guix build utils))
;; Happily use its 'mkdir-p' procedure.
(mkdir-p (string-append #$output "/a/b/c")))))
The remainder of this section is the reference for most of the utility
procedures provided by (guix build utils)
.
This section documents procedures that deal with store file names.
Return the directory name of the store.
Return true if file is in the store.
Strip the /gnu/store and hash from file, a store file name.
The result is typically a "package-version"
string.
Given name, a package name like "foo-0.9.1b"
, return two
values: "foo"
and "0.9.1b"
. When the version part is
unavailable, name and #f
are returned. The first hyphen
followed by a digit is considered to introduce the version part.
The procedures below deal with files and file types.
Return #t
if dir exists and is a directory.
Return #t
if file exists and is executable.
Return #t
if file is a symbolic link (aka. a “symlink”).
Return #t
if file is, respectively, an ELF file, an ar
archive (such as a .a static library), or a gzip file.
If file is a gzip file, reset its embedded timestamp (as with
gzip --no-name
) and return true. Otherwise return #f
.
When keep-mtime? is true, preserve file’s modification time.
The following procedures and macros help create, modify, and delete files.
They provide functionality comparable to common shell utilities such as
mkdir -p
, cp -r
, rm -r
, and sed
.
They complement Guile’s extensive, but low-level, file system interface
(veja POSIX em GNU Guile Reference Manual).
Run body with directory as the process’s current directory.
Essentially, this macro changes the current directory to directory
before evaluating body, using chdir
(veja Processes em GNU Guile Reference Manual). It changes back to the initial directory when
the dynamic extent of body is left, be it via normal procedure
return or via a non-local exit such as an exception.
Create directory dir and all its ancestors.
Create directory if it does not exist and copy file in there under the same name.
Make file writable for its owner.
copy-file] [#:keep-mtime? #f] [#:keep-permissions? #t] [#:select? (const
#t)] Copy source directory to destination. Follow symlinks if
follow-symlinks? is true; otherwise, just preserve them. Call
copy-file to copy regular files. Call select?, taking two
arguments, file and stat, for each entry in source, where
file is the entry’s absolute file name and stat is the result of
lstat
(or stat
if follow-symlinks? is true); exclude
entries for which select? does not return true. When
keep-mtime? is true, keep the modification time of the files in
source on those of destination. When keep-permissions? is
true, preserve file permissions. Write verbose output to the log
port.
Delete dir recursively, like rm -rf
, without following
symlinks. Don’t follow mount points either, unless follow-mounts? is
true. Report but ignore errors.
file by the string returned by body. body is evaluated with each match-var bound to the corresponding positional regexp sub-expression. For example:
(substitute* file
(("hello")
"good morning\n")
(("foo([a-z]+)bar(.*)$" all letters end)
(string-append "baz" letters end)))
Here, anytime a line of file contains hello
, it is replaced by
good morning
. Anytime a line of file matches the second
regexp, all
is bound to the complete match, letters
is bound
to the first sub-expression, and end
is bound to the last one.
When one of the match-var is _
, no variable is bound to the
corresponding match substring.
Alternatively, file may be a list of file names, in which case they are all subject to the substitutions.
Be careful about using $
to match the end of a line; by itself it
won’t match the terminating newline of a line. For example, to match a
whole line ending with a backslash, one needs a regex like
"(.*)\\\\\n$"
.
This section documents procedures to search and filter files.
Return a predicate that returns true when passed a file name whose base name matches regexp.
lexicographically sorted list of files under dir for which pred
returns true. pred is passed two arguments: the absolute file name,
and its stat buffer; the default predicate always returns true. pred
can also be a regular expression, in which case it is equivalent to
(file-name-predicate pred)
. stat is used to obtain file
information; using lstat
means that symlinks are not followed. If
directories? is true, then directories will also be included. If
fail-on-error? is true, raise an exception upon error.
Here are a few examples where we assume that the current directory is the root of the Guix source tree:
;; List all the regular files in the current directory. (find-files ".") ⇒ ("./.dir-locals.el" "./.gitignore" …) ;; List all the .scm files under gnu/services. (find-files "gnu/services" "\\.scm$") ⇒ ("gnu/services/admin.scm" "gnu/services/audio.scm" …) ;; List ar files in the current directory. (find-files "." (lambda (file stat) (ar-file? file))) ⇒ ("./libformat.a" "./libstore.a" …)
Return the complete file name for program as found in $PATH
, or
#f
if program could not be found.
Return the complete file name for name as found in inputs;
search-input-file
searches for a regular file and
search-input-directory
searches for a directory. If name could
not be found, an exception is raised.
Here, inputs must be an association list like inputs
and
native-inputs
as available to build phases (veja Build Phases).
Here is a (simplified) example of how search-input-file
is used in a
build phase of the wireguard-tools
package:
(add-after 'install 'wrap-wg-quick
(lambda* (#:key inputs outputs #:allow-other-keys)
(let ((coreutils (string-append (assoc-ref inputs "coreutils")
"/bin")))
(wrap-program (search-input-file outputs "bin/wg-quick")
#:sh (search-input-file inputs "bin/bash")
`("PATH" ":" prefix ,(list coreutils))))))
You’ll find handy procedures to spawn processes in this module, essentially
convenient wrappers around Guile’s system*
(veja system*
em GNU Guile Reference Manual).
Invoke program with the given args. Raise an
&invoke-error
exception if the exit code is non-zero; otherwise
return #t
.
The advantage compared to system*
is that you do not need to check
the return value. This reduces boilerplate in shell-script-like snippets
for instance in package build phases.
Return true if c is an &invoke-error
condition.
Access specific fields of c, an &invoke-error
condition.
Report to port (by default the current error port) about c, an
&invoke-error
condition, in a human-friendly way.
Typical usage would look like this:
(use-modules (srfi srfi-34) ;for 'guard' (guix build utils)) (guard (c ((invoke-error? c) (report-invoke-error c))) (invoke "date" "--imaginary-option")) -| command "date" "--imaginary-option" failed with status 1
Invoke program with args and capture program’s standard
output and standard error. If program succeeds, print nothing and
return the unspecified value; otherwise, raise a &message
error
condition that includes the status code and the output of program.
Here’s an example:
(use-modules (srfi srfi-34) ;for 'guard' (srfi srfi-35) ;for 'message-condition?' (guix build utils)) (guard (c ((message-condition? c) (display (condition-message c)))) (invoke/quiet "date") ;all is fine (invoke/quiet "date" "--imaginary-option")) -| 'date --imaginary-option' exited with status 1; output follows: date: unrecognized option '--imaginary-option' Try 'date --help' for more information.
The (guix build utils)
also contains tools to manipulate build phases
as used by build systems (veja Sistemas de compilação). Build phases are
represented as association lists or “alists” (veja Association Lists em GNU Guile Reference Manual) where each key is a symbol naming the
phase and the associated value is a procedure (veja Build Phases).
Guile core and the (srfi srfi-1)
module both provide tools to
manipulate alists. The (guix build utils)
module complements those
with tools written with build phases in mind.
Modify phases sequentially as per each clause, which may have one of the following forms:
(delete old-phase-name) (replace old-phase-name new-phase) (add-before old-phase-name new-phase-name new-phase) (add-after old-phase-name new-phase-name new-phase)
Where every phase-name above is an expression evaluating to a symbol, and new-phase an expression evaluating to a procedure.
The example below is taken from the definition of the grep
package.
It adds a phase to run after the install
phase, called
fix-egrep-and-fgrep
. That phase is a procedure (lambda*
is
for anonymous procedures) that takes a #:outputs
keyword argument and
ignores extra keyword arguments (veja Optional Arguments em GNU
Guile Reference Manual, for more on lambda*
and optional and keyword
arguments.) The phase uses substitute*
to modify the installed
egrep and fgrep scripts so that they refer to grep
by
its absolute file name:
(modify-phases %standard-phases
(add-after 'install 'fix-egrep-and-fgrep
;; Patch 'egrep' and 'fgrep' to execute 'grep' via its
;; absolute file name instead of searching for it in $PATH.
(lambda* (#:key outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(bin (string-append out "/bin")))
(substitute* (list (string-append bin "/egrep")
(string-append bin "/fgrep"))
(("^exec grep")
(string-append "exec " bin "/grep")))))))
In the example below, phases are modified in two ways: the standard
configure
phase is deleted, presumably because the package does not
have a configure script or anything similar, and the default
install
phase is replaced by one that manually copies the executable
files to be installed:
(modify-phases %standard-phases
(delete 'configure) ;no 'configure' script
(replace 'install
(lambda* (#:key outputs #:allow-other-keys)
;; The package's Makefile doesn't provide an "install"
;; rule so do it by ourselves.
(let ((bin (string-append (assoc-ref outputs "out")
"/bin")))
(install-file "footswitch" bin)
(install-file "scythe" bin)))))
It is not unusual for a command to require certain environment variables to be set for proper functioning, typically search paths (veja Search Paths). Failing to do that, the command might fail to find files or other commands it relies on, or it might pick the “wrong” ones—depending on the environment in which it runs. Examples include:
PATH
;
GUILE_LOAD_PATH
and GUILE_LOAD_COMPILED_PATH
;
QT_PLUGIN_PATH
.
For a package writer, the goal is to make sure commands always work the same
rather than depend on some external settings. One way to achieve that is to
wrap commands in a thin script that sets those environment variables,
thereby ensuring that those run-time dependencies are always found. The
wrapper would be used to set PATH
, GUILE_LOAD_PATH
, or
QT_PLUGIN_PATH
in the examples above.
To ease that task, the (guix build utils)
module provides a couple of
helpers to wrap commands.
Make a wrapper for program. variables should look like this:
'(variable delimiter position list-of-directories)
where delimiter is optional. :
will be used if delimiter
is not given.
For example, this call:
(wrap-program "foo"
'("PATH" ":" = ("/gnu/.../bar/bin"))
'("CERT_PATH" suffix ("/gnu/.../baz/certs"
"/qux/certs")))
will copy foo to .foo-real and create the file foo with the following contents:
#!location/of/bin/bash export PATH="/gnu/.../bar/bin" export CERT_PATH="$CERT_PATH${CERT_PATH:+:}/gnu/.../baz/certs:/qux/certs" exec -a $0 location/of/.foo-real "$@"
If program has previously been wrapped by wrap-program
, the
wrapper is extended with definitions for variables. If it is not,
sh will be used as the interpreter.
Wrap the script program such that variables are set first. The
format of variables is the same as in the wrap-program
procedure. This procedure differs from wrap-program
in that it does
not create a separate shell script. Instead, program is modified
directly by prepending a Guile script, which is interpreted as a comment in
the script’s language.
Special encoding comments as supported by Python are recreated on the second line.
Note that this procedure can only be used once per file as Guile scripts are not supported.
Próximo: O armazém, Anterior: Build Utilities, Acima: Interface de programação [Conteúdo][Índice]
Many programs and libraries look for input data in a search path, a list of directories: shells like Bash look for executables in the command search path, a C compiler looks for .h files in its header search path, the Python interpreter looks for .py files in its search path, the spell checker has a search path for dictionaries, and so on.
Search paths can usually be defined or overridden via environment
variables (veja Environment Variables em The GNU C Library Reference
Manual). For example, the search paths mentioned above can be changed by
defining the PATH
, C_INCLUDE_PATH
, PYTHONPATH
(or
GUIX_PYTHONPATH
), and DICPATH
environment variables—you know,
all these something-PATH variables that you need to get right or things
“won’t be found”.
You may have noticed from the command line that Guix “knows” which search
path environment variables should be defined, and how. When you install
packages in your default profile, the file
~/.guix-profile/etc/profile is created, which you can “source” from
the shell to set those variables. Likewise, if you ask guix shell
to create an environment containing Python and NumPy, a Python library, and
if you pass it the --search-paths option, it will tell you about
PATH
and GUIX_PYTHONPATH
(veja Invoking guix shell
):
$ guix shell python python-numpy --pure --search-paths export PATH="/gnu/store/…-profile/bin" export GUIX_PYTHONPATH="/gnu/store/…-profile/lib/python3.9/site-packages"
When you omit --search-paths, it defines these environment variables right away, such that Python can readily find NumPy:
$ guix shell python python-numpy -- python3 Python 3.9.6 (default, Jan 1 1970, 00:00:01) [GCC 10.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import numpy >>> numpy.version.version '1.20.3'
For this to work, the definition of the python
package
declares the search path it cares about and its associated
environment variable, GUIX_PYTHONPATH
. It looks like this:
(package
(name "python")
(version "3.9.9")
;; some fields omitted...
(native-search-paths
(list (search-path-specification
(variable "GUIX_PYTHONPATH")
(files (list "lib/python/3.9/site-packages"))))))
What this native-search-paths
field says is that, when the
python
package is used, the GUIX_PYTHONPATH
environment
variable must be defined to include all the
lib/python/3.9/site-packages sub-directories encountered in its
environment. (The native-
bit means that, if we are in a
cross-compilation environment, only native inputs may be added to the search
path; veja search-paths
.) In the NumPy example
above, the profile where python
appears contains exactly one such
sub-directory, and GUIX_PYTHONPATH
is set to that. When there are
several lib/python/3.9/site-packages—this is the case in package
build environments—they are all added to GUIX_PYTHONPATH
, separated
by colons (:
).
Nota: Notice that
GUIX_PYTHONPATH
is specified as part of the definition of thepython
package, and not as part of that ofpython-numpy
. This is because this environment variable “belongs” to Python, not NumPy: Python actually reads the value of that variable and honors it.Corollary: if you create a profile that does not contain
python
,GUIX_PYTHONPATH
will not be defined, even if it contains packages that provide .py files:$ guix shell python-numpy --search-paths --pure export PATH="/gnu/store/…-profile/bin"This makes a lot of sense if we look at this profile in isolation: no software in this profile would read
GUIX_PYTHONPATH
.
Of course, there are many variations on that theme: some packages honor more
than one search path, some use separators other than colon, some accumulate
several directories in their search path, and so on. A more complex example
is the search path of libxml2: the value of the XML_CATALOG_FILES
environment variable is space-separated, it must contain a list of
catalog.xml files (not directories), which are to be found in
xml sub-directories—nothing less. The search path specification
looks like this:
(search-path-specification
(variable "XML_CATALOG_FILES")
(separator " ")
(files '("xml"))
(file-pattern "^catalog\\.xml$")
(file-type 'regular))
Worry not, search path specifications are usually not this tricky.
The (guix search-paths)
module defines the data type of search path
specifications and a number of helper procedures. Below is the reference of
search path specifications.
The data type for search path specifications.
variable
The name of the environment variable for this search path (a string).
files
The list of sub-directories (strings) that should be added to the search path.
separator
(default: ":"
)The string used to separate search path components.
As a special case, a separator
value of #f
specifies a
“single-component search path”—in other words, a search path that cannot
contain more than one element. This is useful in some cases, such as the
SSL_CERT_DIR
variable (honored by OpenSSL, cURL, and a few other
packages) or the ASPELL_DICT_DIR
variable (honored by the GNU Aspell
spell checker), both of which must point to a single directory.
file-type
(default: 'directory
)The type of file being matched—'directory
or 'regular
,
though it can be any symbol returned by stat:type
(veja stat
em GNU Guile Reference Manual).
In the XML_CATALOG_FILES
example above, we would match regular files;
in the Python example, we would match directories.
file-pattern
(default: #f
)This must be either #f
or a regular expression specifying files to be
matched within the sub-directories specified by the files
field.
Again, the XML_CATALOG_FILES
example shows a situation where this is
needed.
Some search paths are not tied by a single package but to many packages. To
reduce duplications, some of them are pre-defined in (guix
search-paths)
.
These two search paths indicate where the TR9401 catalog22 or XML catalog files can be found.
These two search paths indicate where X.509 certificates can be found (veja Certificados X.509).
These pre-defined search paths can be used as in the following example:
(package
(name "curl")
;; some fields omitted ...
(native-search-paths (list $SSL_CERT_DIR $SSL_CERT_FILE)))
How do you turn search path specifications on one hand and a bunch of
directories on the other hand in a set of environment variable definitions?
That’s the job of evaluate-search-paths
.
Evaluate search-paths, a list of search-path specifications, for directories, a list of directory names, and return a list of specification/value pairs. Use getenv to determine the current settings and report only settings not already effective.
The (guix profiles)
provides a higher-level helper procedure,
load-profile
, that sets the environment variables of a profile.
Próximo: Derivações, Anterior: Search Paths, Acima: Interface de programação [Conteúdo][Índice]
Conceptually, the store is the place where derivations that have been built successfully are stored—by default, /gnu/store. Sub-directories in the store are referred to as store items or sometimes store paths. The store has an associated database that contains information such as the store paths referred to by each store path, and the list of valid store items—results of successful builds. This database resides in localstatedir/guix/db, where localstatedir is the state directory specified via --localstatedir at configure time, usually /var.
The store is always accessed by the daemon on behalf of its clients
(veja Invocando guix-daemon
). To manipulate the store, clients connect to
the daemon over a Unix-domain socket, send requests to it, and read the
result—these are remote procedure calls, or RPCs.
Nota: Users must never modify files under /gnu/store directly. This would lead to inconsistencies and break the immutability assumptions of Guix’s functional model (veja Introdução).
Veja
guix gc --verify
, for information on how to check the integrity of the store and attempt recovery from accidental modifications.
The (guix store)
module provides procedures to connect to the daemon,
and to perform RPCs. These are described below. By default,
open-connection
, and thus all the guix
commands, connect to
the local daemon or to the URI specified by the GUIX_DAEMON_SOCKET
environment variable.
When set, the value of this variable should be a file name or a URI designating the daemon endpoint. When it is a file name, it denotes a Unix-domain socket to connect to. In addition to file names, the supported URI schemes are:
file
unix
These are for Unix-domain sockets.
file:///var/guix/daemon-socket/socket
is equivalent to
/var/guix/daemon-socket/socket.
guix
¶These URIs denote connections over TCP/IP, without encryption nor authentication of the remote host. The URI must specify the host name and optionally a port number (by default port 44146 is used):
guix://master.guix.example.org:1234
This setup is suitable on local networks, such as clusters, where only
trusted nodes may connect to the build daemon at
master.guix.example.org
.
The --listen option of guix-daemon
can be used to
instruct it to listen for TCP connections (veja --listen).
ssh
¶These URIs allow you to connect to a remote daemon over SSH. This feature
requires Guile-SSH (veja Requisitos) and a working guile
binary in PATH
on the destination machine. It supports public key and
GSSAPI authentication. A typical URL might look like this:
ssh://charlie@guix.example.org:22
As for guix copy
, the usual OpenSSH client configuration files are
honored (veja Invocando guix copy
).
Additional URI schemes may be supported in the future.
Nota: The ability to connect to remote build daemons is considered experimental as of 9356a8c. Please get in touch with us to share any problems or suggestions you may have (veja Contribuindo).
Connect to the daemon over the Unix-domain socket at uri (a string). When reserve-space? is true, instruct it to reserve a little bit of extra space on the file system so that the garbage collector can still operate should the disk become full. Return a server object.
file defaults to %default-socket-path
, which is the normal
location given the options that were passed to configure
.
Close the connection to server.
This variable is bound to a SRFI-39 parameter, which refers to the port where build and error logs sent by the daemon should be written.
Procedures that make RPCs all take a server object as their first argument.
Return #t
when path designates a valid store item and #f
otherwise (an invalid item may exist on disk but still be invalid, for
instance because it is the result of an aborted or failed build).
A &store-protocol-error
condition is raised if path is not
prefixed by the store directory (/gnu/store).
Add text under file name in the store, and return its store path. references is the list of store paths referred to by the resulting store path.
Build derivations, a list of <derivation>
objects, .drv
file names, or derivation/output pairs, using the specified
mode—(build-mode normal)
by default.
Note that the (guix monads)
module provides a monad as well as
monadic versions of the above procedures, with the goal of making it more
convenient to work with code that accesses the store (veja A mônada do armazém).
This section is currently incomplete.
Próximo: A mônada do armazém, Anterior: O armazém, Acima: Interface de programação [Conteúdo][Índice]
Low-level build actions and the environment in which they are performed are represented by derivations. A derivation contains the following pieces of information:
x86_64-linux
.
Derivations allow clients of the daemon to communicate build actions to the
store. They exist in two forms: as an in-memory representation, both on the
client- and daemon-side, and as files in the store whose name end in
.drv—these files are referred to as derivation paths.
Derivations paths can be passed to the build-derivations
procedure to
perform the build actions they prescribe (veja O armazém).
Operations such as file downloads and version-control checkouts for which the expected content hash is known in advance are modeled as fixed-output derivations. Unlike regular derivations, the outputs of a fixed-output derivation are independent of its inputs—e.g., a source code download produces the same result regardless of the download method and tools being used.
The outputs of derivations—i.e., the build results—have a set of
references, as reported by the references
RPC or the
guix gc --references
command (veja Invocando guix gc
).
References are the set of run-time dependencies of the build results.
References are a subset of the inputs of the derivation; this subset is
automatically computed by the build daemon by scanning all the files in the
outputs.
The (guix derivations)
module provides a representation of
derivations as Scheme objects, along with procedures to create and otherwise
manipulate derivations. The lowest-level primitive to create a derivation
is the derivation
procedure:
[#:inputs ’()] [#:env-vars ’()] [#:system (%current-system)]
[#:references-graphs #f] [#:allowed-references #f]
[#:disallowed-references #f] [#:leaked-env-vars #f] [#:local-build? #f] [#:substitutable? #t] [#:properties ’()] Build a derivation with the given
arguments, and return the resulting <derivation>
object.
When hash and hash-algo are given, a fixed-output derivation is created—i.e., one whose result is known in advance, such as a file download. If, in addition, recursive? is true, then that fixed output may be an executable file or a directory and hash must be the hash of an archive containing this output.
When references-graphs is true, it must be a list of file name/store path pairs. In that case, the reference graph of each store path is exported in the build environment in the corresponding file, in a simple text format.
When allowed-references is true, it must be a list of store items or outputs that the derivation’s output may refer to. Likewise, disallowed-references, if true, must be a list of things the outputs may not refer to.
When leaked-env-vars is true, it must be a list of strings denoting
environment variables that are allowed to “leak” from the daemon’s
environment to the build environment. This is only applicable to
fixed-output derivations—i.e., when hash is true. The main use is
to allow variables such as http_proxy
to be passed to derivations
that download files.
When local-build? is true, declare that the derivation is not a good candidate for offloading and should rather be built locally (veja Usando o recurso de descarregamento). This is the case for small derivations where the costs of data transfers would outweigh the benefits.
When substitutable? is false, declare that substitutes of the derivation’s output should not be used (veja Substitutos). This is useful, for instance, when building packages that capture details of the host CPU instruction set.
properties must be an association list describing “properties” of the derivation. It is kept as-is, uninterpreted, in the derivation.
Here’s an example with a shell script as its builder, assuming store is an open connection to the daemon, and bash points to a Bash executable in the store:
(use-modules (guix utils) (guix store) (guix derivations)) (let ((builder ; add the Bash script to the store (add-text-to-store store "my-builder.sh" "echo hello world > $out\n" '()))) (derivation store "foo" bash `("-e" ,builder) #:inputs `((,bash) (,builder)) #:env-vars '(("HOME" . "/homeless")))) ⇒ #<derivation /gnu/store/…-foo.drv => /gnu/store/…-foo>
As can be guessed, this primitive is cumbersome to use directly. A better
approach is to write build scripts in Scheme, of course! The best course of
action for that is to write the build code as a “G-expression”, and to
pass it to gexp->derivation
. For more information,
veja Expressões-G.
Once upon a time, gexp->derivation
did not exist and constructing
derivations with build code written in Scheme was achieved with
build-expression->derivation
, documented below. This procedure is
now deprecated in favor of the much nicer gexp->derivation
.
#f] [#:hash-algo #f] [#:recursive? #f] [#:env-vars ’()] [#:modules ’()] [#:references-graphs #f] [#:allowed-references #f] [#:disallowed-references #f] [#:local-build? #f] [#:substitutable? #t]
[#:guile-for-build #f] Return a derivation that executes Scheme expression
exp as a builder for derivation name. inputs must be a
list of (name drv-path sub-drv)
tuples; when sub-drv is
omitted, "out"
is assumed. modules is a list of names of Guile
modules from the current search path to be copied in the store, compiled,
and made available in the load path during the execution of
exp—e.g., ((guix build utils) (guix build gnu-build-system))
.
exp is evaluated in an environment where %outputs
is bound to a
list of output/path pairs, and where %build-inputs
is bound to a list
of string/output-path pairs made from inputs. Optionally,
env-vars is a list of string pairs specifying the name and value of
environment variables visible to the builder. The builder terminates by
passing the result of exp to exit
; thus, when exp returns
#f
, the build is considered to have failed.
exp is built using guile-for-build (a derivation). When
guile-for-build is omitted or is #f
, the value of the
%guile-for-build
fluid is used instead.
See the derivation
procedure for the meaning of
references-graphs, allowed-references,
disallowed-references, local-build?, and substitutable?.
Here’s an example of a single-output derivation that creates a directory containing one file:
(let ((builder '(let ((out (assoc-ref %outputs "out"))) (mkdir out) ; create /gnu/store/…-goo (call-with-output-file (string-append out "/test") (lambda (p) (display '(hello guix) p)))))) (build-expression->derivation store "goo" builder)) ⇒ #<derivation /gnu/store/…-goo.drv => …>
Próximo: Expressões-G, Anterior: Derivações, Acima: Interface de programação [Conteúdo][Índice]
The procedures that operate on the store described in the previous sections all take an open connection to the build daemon as their first argument. Although the underlying model is functional, they either have side effects or depend on the current state of the store.
The former is inconvenient: the connection to the build daemon has to be carried around in all those functions, making it impossible to compose functions that do not take that parameter with functions that do. The latter can be problematic: since store operations have side effects and/or depend on external state, they have to be properly sequenced.
This is where the (guix monads)
module comes in. This module
provides a framework for working with monads, and a particularly
useful monad for our uses, the store monad. Monads are a construct
that allows two things: associating “context” with values (in our case,
the context is the store), and building sequences of computations (here
computations include accesses to the store). Values in a monad—values
that carry this additional context—are called monadic values;
procedures that return such values are called monadic procedures.
Consider this “normal” procedure:
(define (sh-symlink store)
;; Return a derivation that symlinks the 'bash' executable.
(let* ((drv (package-derivation store bash))
(out (derivation->output-path drv))
(sh (string-append out "/bin/bash")))
(build-expression->derivation store "sh"
`(symlink ,sh %output))))
Using (guix monads)
and (guix gexp)
, it may be rewritten as a
monadic function:
(define (sh-symlink)
;; Same, but return a monadic value.
(mlet %store-monad ((drv (package->derivation bash)))
(gexp->derivation "sh"
#~(symlink (string-append #$drv "/bin/bash")
#$output))))
There are several things to note in the second version: the store
parameter is now implicit and is “threaded” in the calls to the
package->derivation
and gexp->derivation
monadic procedures,
and the monadic value returned by package->derivation
is bound
using mlet
instead of plain let
.
As it turns out, the call to package->derivation
can even be omitted
since it will take place implicitly, as we will see later
(veja Expressões-G):
(define (sh-symlink)
(gexp->derivation "sh"
#~(symlink (string-append #$bash "/bin/bash")
#$output)))
Calling the monadic sh-symlink
has no effect. As someone once said,
“you exit a monad like you exit a building on fire: by running”. So, to
exit the monad and get the desired effect, one must use
run-with-store
:
(run-with-store (open-connection) (sh-symlink)) ⇒ /gnu/store/...-sh-symlink
Note that the (guix monad-repl)
module extends the Guile REPL with
new “commands” to make it easier to deal with monadic procedures:
run-in-store
, and enter-store-monad
(veja Using Guix Interactively). The former is used to “run” a single monadic value
through the store:
scheme@(guile-user)> ,run-in-store (package->derivation hello) $1 = #<derivation /gnu/store/…-hello-2.9.drv => …>
The latter enters a recursive REPL, where all the return values are automatically run through the store:
scheme@(guile-user)> ,enter-store-monad store-monad@(guile-user) [1]> (package->derivation hello) $2 = #<derivation /gnu/store/…-hello-2.9.drv => …> store-monad@(guile-user) [1]> (text-file "foo" "Hello!") $3 = "/gnu/store/…-foo" store-monad@(guile-user) [1]> ,q scheme@(guile-user)>
Note that non-monadic values cannot be returned in the store-monad
REPL.
Other meta-commands are available at the REPL, such as ,build
to
build a file-like object (veja Using Guix Interactively).
The main syntactic forms to deal with monads in general are provided by the
(guix monads)
module and are described below.
Evaluate any >>=
or return
forms in body as being in
monad.
Return a monadic value that encapsulates val.
Bind monadic value mval, passing its “contents” to monadic procedures mproc…23. There can be one mproc or several of them, as in this example:
(run-with-state (with-monad %state-monad (>>= (return 1) (lambda (x) (return (+ 1 x))) (lambda (x) (return (* 2 x))))) 'some-state) ⇒ 4 ⇒ some-state
Bind the variables var to the monadic values mval in body,
which is a sequence of expressions. As with the bind operator, this can be
thought of as “unpacking” the raw, non-monadic value “contained” in
mval and making var refer to that raw, non-monadic value within
the scope of the body. The form (var -> val) binds
var to the “normal” value val, as per let
. The binding
operations occur in sequence from left to right. The last expression of
body must be a monadic expression, and its result will become the
result of the mlet
or mlet*
when run in the monad.
mlet*
is to mlet
what let*
is to let
(veja Local Bindings em GNU Guile Reference Manual).
Bind mexp and the following monadic expressions in sequence, returning the result of the last expression. Every expression in the sequence must be a monadic expression.
This is akin to mlet
, except that the return values of the monadic
expressions are ignored. In that sense, it is analogous to begin
,
but applied to monadic expressions.
When condition is true, evaluate the sequence of monadic expressions
mexp0..mexp* as in an mbegin
. When condition is
false, return *unspecified*
in the current monad. Every expression
in the sequence must be a monadic expression.
When condition is false, evaluate the sequence of monadic expressions
mexp0..mexp* as in an mbegin
. When condition is
true, return *unspecified*
in the current monad. Every expression in
the sequence must be a monadic expression.
The (guix monads)
module provides the state monad, which allows
an additional value—the state—to be threaded through monadic
procedure calls.
The state monad. Procedures in the state monad can access and change the state that is threaded.
Consider the example below. The square
procedure returns a value in
the state monad. It returns the square of its argument, but also increments
the current state value:
(define (square x) (mlet %state-monad ((count (current-state))) (mbegin %state-monad (set-current-state (+ 1 count)) (return (* x x))))) (run-with-state (sequence %state-monad (map square (iota 3))) 0) ⇒ (0 1 4) ⇒ 3
When “run” through %state-monad
, we obtain that additional state
value, which is the number of square
calls.
Return the current state as a monadic value.
Set the current state to value and return the previous state as a monadic value.
Push value to the current state, which is assumed to be a list, and return the previous state as a monadic value.
Pop a value from the current state and return it as a monadic value. The state is assumed to be a list.
Run monadic value mval starting with state as the initial state. Return two values: the resulting value, and the resulting state.
The main interface to the store monad, provided by the (guix store)
module, is as follows.
The store monad—an alias for %state-monad
.
Values in the store monad encapsulate accesses to the store. When its
effect is needed, a value of the store monad must be “evaluated” by
passing it to the run-with-store
procedure (see below).
value in the store monad, in store, an open store connection.
Return as a monadic value the absolute file name in the store of the file containing text, a string. references is a list of store items that the resulting text file refers to; it defaults to the empty list.
Return as a monadic value the absolute file name in the store of the file containing data, a bytevector. references is a list of store items that the resulting binary file refers to; it defaults to the empty list.
interned in the store. Use name as its store name, or the basename of file if name is omitted.
When recursive? is true, the contents of file are added recursively; if file designates a flat file and recursive? is true, its contents are added, and its permission bits are kept.
When recursive? is true, call (select? file
stat)
for each directory entry, where file is the entry’s
absolute file name and stat is the result of lstat
; exclude
entries for which select? does not return true.
The example below adds a file to the store, under two different names:
(run-with-store (open-connection) (mlet %store-monad ((a (interned-file "README")) (b (interned-file "README" "LEGU-MIN"))) (return (list a b)))) ⇒ ("/gnu/store/rwm…-README" "/gnu/store/44i…-LEGU-MIN")
The (guix packages)
module exports the following package-related
monadic procedures:
monadic value in the absolute file name of file within the output directory of package. When file is omitted, return the name of the output directory of package. When target is true, use it as a cross-compilation target triplet.
Note that this procedure does not build package. Thus, the result might or might not designate an existing file. We recommend not using this procedure unless you know what you are doing.
package-derivation
andpackage-cross-derivation
(veja Definindo pacotes).
Próximo: Invocando guix repl
, Anterior: A mônada do armazém, Acima: Interface de programação [Conteúdo][Índice]
So we have “derivations”, which represent a sequence of build actions to
be performed to produce an item in the store (veja Derivações). These
build actions are performed when asking the daemon to actually build the
derivations; they are run by the daemon in a container (veja Invocando guix-daemon
).
It should come as no surprise that we like to write these build actions in
Scheme. When we do that, we end up with two strata of Scheme
code24: the
“host code”—code that defines packages, talks to the daemon, etc.—and
the “build code”—code that actually performs build actions, such as
making directories, invoking make
, and so on (veja Build Phases).
To describe a derivation and its build actions, one typically needs to embed
build code inside host code. It boils down to manipulating build code as
data, and the homoiconicity of Scheme—code has a direct representation as
data—comes in handy for that. But we need more than the normal
quasiquote
mechanism in Scheme to construct build expressions.
The (guix gexp)
module implements G-expressions, a form of
S-expressions adapted to build expressions. G-expressions, or gexps,
consist essentially of three syntactic forms: gexp
, ungexp
,
and ungexp-splicing
(or simply: #~
, #$
, and
#$@
), which are comparable to quasiquote
, unquote
, and
unquote-splicing
, respectively (veja quasiquote
em GNU Guile Reference Manual). However, there are
major differences:
This mechanism is not limited to package and derivation objects:
compilers able to “lower” other high-level objects to derivations or
files in the store can be defined, such that these objects can also be
inserted into gexps. For example, a useful type of high-level objects that
can be inserted in a gexp is “file-like objects”, which make it easy to
add files to the store and to refer to them in derivations and such (see
local-file
and plain-file
below).
To illustrate the idea, here is an example of a gexp:
(define build-exp
#~(begin
(mkdir #$output)
(chdir #$output)
(symlink (string-append #$coreutils "/bin/ls")
"list-files")))
This gexp can be passed to gexp->derivation
; we obtain a derivation
that builds a directory containing exactly one symlink to
/gnu/store/…-coreutils-8.22/bin/ls:
(gexp->derivation "the-thing" build-exp)
As one would expect, the "/gnu/store/…-coreutils-8.22"
string
is substituted to the reference to the coreutils package in the actual
build code, and coreutils is automatically made an input to the
derivation. Likewise, #$output
(equivalent to (ungexp
output)
) is replaced by a string containing the directory name of the
output of the derivation.
In a cross-compilation context, it is useful to distinguish between
references to the native build of a package—that can run on the
host—versus references to cross builds of a package. To that end, the
#+
plays the same role as #$
, but is a reference to a native
package build:
(gexp->derivation "vi"
#~(begin
(mkdir #$output)
(mkdir (string-append #$output "/bin"))
(system* (string-append #+coreutils "/bin/ln")
"-s"
(string-append #$emacs "/bin/emacs")
(string-append #$output "/bin/vi")))
#:target "aarch64-linux-gnu")
In the example above, the native build of coreutils is used, so that
ln
can actually run on the host; but then the cross-compiled build
of emacs is referenced.
Another gexp feature is imported modules: sometimes you want to be
able to use certain Guile modules from the “host environment” in the gexp,
so those modules should be imported in the “build environment”. The
with-imported-modules
form allows you to express that:
(let ((build (with-imported-modules '((guix build utils))
#~(begin
(use-modules (guix build utils))
(mkdir-p (string-append #$output "/bin"))))))
(gexp->derivation "empty-dir"
#~(begin
#$build
(display "success!\n")
#t)))
In this example, the (guix build utils)
module is automatically
pulled into the isolated build environment of our gexp, such that
(use-modules (guix build utils))
works as expected.
Usually you want the closure of the module to be imported—i.e., the
module itself and all the modules it depends on—rather than just the
module; failing to do that, attempts to use the module will fail because of
missing dependent modules. The source-module-closure
procedure
computes the closure of a module by looking at its source file headers,
which comes in handy in this case:
(use-modules (guix modules)) ;for 'source-module-closure' (with-imported-modules (source-module-closure '((guix build utils) (gnu build image))) (gexp->derivation "something-with-vms" #~(begin (use-modules (guix build utils) (gnu build image)) …)))
In the same vein, sometimes you want to import not just pure-Scheme modules,
but also “extensions” such as Guile bindings to C libraries or other
“full-blown” packages. Say you need the guile-json
package
available on the build side, here’s how you would do it:
(use-modules (gnu packages guile)) ;for 'guile-json' (with-extensions (list guile-json) (gexp->derivation "something-with-json" #~(begin (use-modules (json)) …)))
The syntactic form to construct gexps is summarized below.
Return a G-expression containing exp. exp may contain one or more of the following forms:
#$obj
(ungexp obj)
Introduce a reference to obj. obj may have one of the supported
types, for example a package or a derivation, in which case the
ungexp
form is replaced by its output file name—e.g.,
"/gnu/store/…-coreutils-8.22
.
If obj is a list, it is traversed and references to supported objects are substituted similarly.
If obj is another gexp, its contents are inserted and its dependencies are added to those of the containing gexp.
If obj is another kind of object, it is inserted as is.
#$obj:saída
(ungexp obj saída)
This is like the form above, but referring explicitly to the output of obj—this is useful when obj produces multiple outputs (veja Pacotes com múltiplas saídas).
Sometimes a gexp unconditionally refers to the "out"
output, but the
user of that gexp would still like to insert a reference to another output.
The gexp-input
procedure aims to address that. Veja gexp-input.
#+obj
#+obj:output
(ungexp-native obj)
(ungexp-native obj output)
Same as ungexp
, but produces a reference to the native build
of obj when used in a cross compilation context.
#$output[:saída]
(ungexp output [saída])
Insert a reference to derivation output output, or to the main output when output is omitted.
This only makes sense for gexps passed to gexp->derivation
.
#$@lst
(ungexp-splicing lst)
Like the above, but splices the contents of lst inside the containing list.
#+@lst
(ungexp-native-splicing lst)
Like the above, but refers to native builds of the objects listed in lst.
G-expressions created by gexp
or #~
are run-time objects of
the gexp?
type (see below).
Mark the gexps defined in body… as requiring modules in their execution environment.
Each item in modules can be the name of a module, such as (guix
build utils)
, or it can be a module name, followed by an arrow, followed by
a file-like object:
`((guix build utils) (guix gcrypt) ((guix config) => ,(scheme-file "config.scm" #~(define-module …))))
In the example above, the first two modules are taken from the search path, and the last one is created from the given file-like object.
This form has lexical scope: it has an effect on the gexps directly defined in body…, but not on those defined, say, in procedures called from body….
Mark the gexps defined in body… as requiring extensions in
their build and execution environment. extensions is typically a list
of package objects such as those defined in the (gnu packages guile)
module.
Concretely, the packages listed in extensions are added to the load path while compiling imported modules in body…; they are also added to the load path of the gexp returned by body….
Return #t
if obj is a G-expression.
G-expressions are meant to be written to disk, either as code building some derivation, or as plain files in the store. The monadic procedures below allow you to do that (veja A mônada do armazém, for more information about monads).
[#:hash-algo #f] [#:recursive? #f] [#:env-vars ’()] [#:modules ’()] [#:module-path %load-path
] [#:effective-version "2.2"] [#:references-graphs #f] [#:allowed-references #f] [#:disallowed-references #f] [#:leaked-env-vars #f] [#:script-name
(string-append name "-builder")] [#:deprecation-warnings #f] [#:local-build? #f] [#:substitutable? #t] [#:properties ’()]
[#:guile-for-build #f] Return a derivation name that runs exp (a
gexp) with guile-for-build (a derivation) on system; exp
is stored in a file called script-name. When target is true, it
is used as the cross-compilation target triplet for packages referred to by
exp.
modules is deprecated in favor of with-imported-modules
. Its
meaning is to make modules available in the evaluation context of
exp; modules is a list of names of Guile modules searched in
module-path to be copied in the store, compiled, and made available in
the load path during the execution of exp—e.g., ((guix build
utils) (guix build gnu-build-system))
.
effective-version determines the string to use when adding extensions
of exp (see with-extensions
) to the search path—e.g.,
"2.2"
.
graft? determines whether packages referred to by exp should be grafted when applicable.
When references-graphs is true, it must be a list of tuples of one of the following forms:
(file-name obj) (file-name obj output) (file-name gexp-input) (file-name store-item)
The right-hand-side of each element of references-graphs is automatically made an input of the build process of exp. In the build environment, each file-name contains the reference graph of the corresponding item, in a simple text format.
allowed-references must be either #f
or a list of output names
and packages. In the latter case, the list denotes store items that the
result is allowed to refer to. Any reference to another store item will
lead to a build error. Similarly for disallowed-references, which can
list items that must not be referenced by the outputs.
deprecation-warnings determines whether to show deprecation warnings
while compiling modules. It can be #f
, #t
, or
'detailed
.
The other arguments are as for derivation
(veja Derivações).
The local-file
, plain-file
, computed-file
,
program-file
, and scheme-file
procedures below return
file-like objects. That is, when unquoted in a G-expression, these
objects lead to a file in the store. Consider this G-expression:
#~(system* #$(file-append glibc "/sbin/nscd") "-f" #$(local-file "/tmp/my-nscd.conf"))
The effect here is to “intern” /tmp/my-nscd.conf by copying it to
the store. Once expanded, for instance via gexp->derivation
, the
G-expression refers to that copy under /gnu/store; thus, modifying or
removing the file in /tmp does not have any effect on what the
G-expression does. plain-file
can be used similarly; it differs in
that the file content is directly passed as a string.
Return an object representing local file file to add to the store; this object can be used in a gexp. If file is a literal string denoting a relative file name, it is looked up relative to the source file where it appears; if file is not a literal string, it is looked up relative to the current working directory at run time. file will be added to the store under name–by default the base name of file.
When recursive? is true, the contents of file are added recursively; if file designates a flat file and recursive? is true, its contents are added, and its permission bits are kept.
When recursive? is true, call (select? file
stat)
for each directory entry, where file is the entry’s
absolute file name and stat is the result of lstat
; exclude
entries for which select? does not return true.
file can be wrapped in the assume-valid-file-name
syntactic
keyword. When this is done, there will not be a warning when
local-file
is used with a non-literal path. The path is still looked
up relative to the current working directory at run time. Wrapping is done
like this:
(define alice-key-file-path "alice.pub") ;; ... (local-file (assume-valid-file-name alice-key-file-path))
file can be wrapped in the assume-source-relative-file-name
syntactic keyword. When this is done, the file name will be looked up
relative to the source file where it appears even when it is not a string
literal.
This is the declarative counterpart of the interned-file
monadic
procedure (veja interned-file
).
Return an object representing a text file called name with the given content (a string or a bytevector) to be added to the store.
This is the declarative counterpart of text-file
.
Return an object representing the store item name, a file or directory
computed by gexp. When local-build? is true (the default), the
derivation is built locally. options is a list of additional
arguments to pass to gexp->derivation
.
This is the declarative counterpart of gexp->derivation
.
(%current-system)] [#:target #f] Return an executable script name that runs exp using guile, with exp’s imported modules in its search path. Look up exp’s modules in module-path.
The example below builds a script that simply invokes the ls
command:
(use-modules (guix gexp) (gnu packages base)) (gexp->script "list-files" #~(execl #$(file-append coreutils "/bin/ls") "ls"))
When “running” it through the store (veja run-with-store
), we obtain a derivation that produces an executable
file /gnu/store/…-list-files along these lines:
#!/gnu/store/…-guile-2.0.11/bin/guile -ds !# (execl "/gnu/store/…-coreutils-8.22"/bin/ls" "ls")
Return an object representing the executable store item name that runs gexp. guile is the Guile package used to execute that script. Imported modules of gexp are looked up in module-path.
This is the declarative counterpart of gexp->script
.
(default-guile)] Return a derivation that builds a file name containing exp. When splice? is true, exp is considered to be a list of expressions that will be spliced in the resulting file.
When set-load-path? is true, emit code in the resulting file to set
%load-path
and %load-compiled-path
to honor exp’s
imported modules. Look up exp’s modules in module-path.
The resulting file holds references to all the dependencies of exp or a subset thereof.
file name that contains exp. guile is the Guile package used to produce that file.
This is the declarative counterpart of gexp->file
.
Return as a monadic value a derivation that builds a text file containing all of text. text may list, in addition to strings, objects of any type that can be used in a gexp: packages, derivations, local file objects, etc. The resulting store file holds references to all these.
This variant should be preferred over text-file
anytime the file to
create will reference items from the store. This is typically the case when
building a configuration file that embeds store file names, like this:
(define (profile.sh)
;; Return the name of a shell script in the store that
;; initializes the 'PATH' environment variable.
(text-file* "profile.sh"
"export PATH=" coreutils "/bin:"
grep "/bin:" sed "/bin\n"))
In this example, the resulting /gnu/store/…-profile.sh file will reference coreutils, grep, and sed, thereby preventing them from being garbage-collected during its lifetime.
Return an object representing store file name containing text. text is a sequence of strings and file-like objects, as in:
(mixed-text-file "profile"
"export PATH=" coreutils "/bin:" grep "/bin")
This is the declarative counterpart of text-file*
.
Return a <computed-file>
that builds a directory containing all of
files. Each item in files must be a two-element list where the
first element is the file name to use in the new directory, and the second
element is a gexp denoting the target file. Here’s an example:
(file-union "etc"
`(("hosts" ,(plain-file "hosts"
"127.0.0.1 localhost"))
("bashrc" ,(plain-file "bashrc"
"alias ls='ls --color=auto'"))))
This yields an etc
directory containing these two files.
Return a directory that is the union of things, where things is a list of file-like objects denoting directories. For example:
(directory-union "guile+emacs" (list guile emacs))
yields a directory that is the union of the guile
and emacs
packages.
Return a file-like object that expands to the concatenation of obj and suffix, where obj is a lowerable object and each suffix is a string.
As an example, consider this gexp:
(gexp->script "run-uname"
#~(system* #$(file-append coreutils
"/bin/uname")))
The same effect could be achieved with:
(gexp->script "run-uname"
#~(system* (string-append #$coreutils
"/bin/uname")))
There is one difference though: in the file-append
case, the
resulting script contains the absolute file name as a string, whereas in the
second case, the resulting script contains a (string-append …)
expression to construct the file name at run time.
Bind system to the currently targeted system—e.g.,
"x86_64-linux"
—within body.
In the second case, additionally bind target to the current
cross-compilation target—a GNU triplet such as
"arm-linux-gnueabihf"
—or #f
if we are not cross-compiling.
let-system
is useful in the occasional case where the object spliced
into the gexp depends on the target system, as in this example:
#~(system* #+(let-system system (cond ((string-prefix? "armhf-" system) (file-append qemu "/bin/qemu-system-arm")) ((string-prefix? "x86_64-" system) (file-append qemu "/bin/qemu-system-x86_64")) (else (error "dunno!")))) "-net" "user" #$image)
This macro is similar to the parameterize
form for dynamically-bound
parameters (veja Parameters em GNU Guile Reference Manual).
The key difference is that it takes effect when the file-like object
returned by exp is lowered to a derivation or store item.
A typical use of with-parameters
is to force the system in effect for
a given object:
(with-parameters ((%current-system "i686-linux"))
coreutils)
The example above returns an object that corresponds to the i686 build of
Coreutils, regardless of the current value of %current-system
.
Return a gexp input record for the given output of file-like
object obj, with #:native?
determining whether this is a native
reference (as with ungexp-native
) or not.
This procedure is helpful when you want to pass a reference to a specific output of an object to some procedure that may not know about that output. For example, assume you have this procedure, which takes one file-like object:
(define (make-symlink target)
(computed-file "the-symlink"
#~(symlink #$target #$output)))
Here make-symlink
can only ever refer to the default output of
target—the "out"
output (veja Pacotes com múltiplas saídas). To have it refer to, say, the "lib"
output of the
hwloc
package, you can call it like so:
(make-symlink (gexp-input hwloc "lib"))
You can also compose it like any other file-like object:
(make-symlink
(file-append (gexp-input hwloc "lib") "/lib/libhwloc.so"))
Of course, in addition to gexps embedded in “host” code, there are also
modules containing build tools. To make it clear that they are meant to be
used in the build stratum, these modules are kept in the (guix build
…)
name space.
Internally, high-level objects are lowered, using their compiler, to
either derivations or store items. For instance, lowering a package yields
a derivation, and lowering a plain-file
yields a store item. This is
achieved using the lower-object
monadic procedure.
%store-monad
the derivation orstore item corresponding to obj for system, cross-compiling for
target if target is true. obj must be an object that has
an associated gexp compiler, such as a <package>
.
Sometimes, it may be useful to convert a G-exp into a S-exp. For example,
some linters (veja Invocando guix lint
) peek into the build phases of a
package to detect potential problems. This conversion can be achieved with
this procedure. However, some information can be lost in the process. More
specifically, lowerable objects will be silently replaced with some
arbitrary object – currently the list (*approximate*)
, but this may
change.
Próximo: Using Guix Interactively, Anterior: Expressões-G, Acima: Interface de programação [Conteúdo][Índice]
guix repl
The guix repl
command makes it easier to program Guix in Guile by
launching a Guile read-eval-print loop (REPL) for interactive
programming (veja Using Guile Interactively em GNU Guile Reference
Manual), or by running Guile scripts (veja Running Guile Scripts em GNU Guile Reference Manual). Compared to just launching the
guile
command, guix repl
guarantees that all the Guix
modules and all its dependencies are available in the search path.
The general syntax is:
guix repl options [file args]
When a file argument is provided, file is executed as a Guile scripts:
guix repl my-script.scm
To pass arguments to the script, use --
to prevent them from being
interpreted as arguments to guix repl
itself:
guix repl -- my-script.scm --input=foo.txt
To make a script executable directly from the shell, using the guix executable that is on the user’s search path, add the following two lines at the top of the script:
#!/usr/bin/env -S guix repl --
!#
To make a script that launches an interactive REPL directly from the shell,
use the --interactive
flag:
#!/usr/bin/env -S guix repl --interactive
!#
Without a file name argument, a Guile REPL is started, allowing for interactive use (veja Using Guix Interactively):
$ guix repl scheme@(guile-user)> ,use (gnu packages base) scheme@(guile-user)> coreutils $1 = #<package coreutils@8.29 gnu/packages/base.scm:327 3e28300>
In addition, guix repl
implements a simple machine-readable REPL
protocol for use by (guix inferior)
, a facility to interact with
inferiors, separate processes running a potentially different revision
of Guix.
The available options are as follows:
--list-types
Display the TYPE options for guix repl --type=TYPE
and exit.
--type=type
-t tipo
Start a REPL of the given TYPE, which can be one of the following:
guile
This is default, and it spawns a standard full-featured Guile REPL.
machine
Spawn a REPL that uses the machine-readable protocol. This is the protocol
that the (guix inferior)
module speaks.
--listen=endpoint
By default, guix repl
reads from standard input and writes to
standard output. When this option is passed, it will instead listen for
connections on endpoint. Here are examples of valid options:
--listen=tcp:37146
Accept connections on localhost on port 37146.
--listen=unix:/tmp/socket
Accept connections on the Unix-domain socket /tmp/socket.
--interactive
-i
Launch the interactive REPL after file is executed.
--load-path=directory
-L diretório
Add directory to the front of the package module search path (veja Módulos de pacote).
This allows users to define their own packages and make them visible to the script or REPL.
-q
Inhibit loading of the ~/.guile file. By default, that configuration
file is loaded when spawning a guile
REPL.
Anterior: Invocando guix repl
, Acima: Interface de programação [Conteúdo][Índice]
The guix repl
command gives you access to a warm and friendly
read-eval-print loop (REPL) (veja Invocando guix repl
). If you’re
getting into Guix programming—defining your own packages, writing
manifests, defining services for Guix System or Guix Home, etc.—you will
surely find it convenient to toy with ideas at the REPL.
If you use Emacs, the most convenient way to do that is with Geiser
(veja A configuração perfeita), but you do not have to use Emacs to enjoy the
REPL. When using guix repl
or guile
in the terminal,
we recommend using Readline for completion and Colorized to get colorful
output. To do that, you can run:
guix install guile guile-readline guile-colorized
... and then create a .guile file in your home directory containing this:
(use-modules (ice-9 readline) (ice-9 colorized)) (activate-readline) (activate-colorized)
The REPL lets you evaluate Scheme code; you type a Scheme expression at the prompt, and the REPL prints what it evaluates to:
$ guix repl scheme@(guix-user)> (+ 2 3) $1 = 5 scheme@(guix-user)> (string-append "a" "b") $2 = "ab"
It becomes interesting when you start fiddling with Guix at the REPL. The
first thing you’ll want to do is to “import” the (guix)
module,
which gives access to the main part of the programming interface, and
perhaps a bunch of useful Guix modules. You could type (use-modules
(guix))
, which is valid Scheme code to import a module (veja Using Guile
Modules em GNU Guile Reference Manual), but the REPL provides the
use
command as a shorthand notation (veja REPL Commands em GNU Guile Reference Manual):
scheme@(guix-user)> ,use (guix) scheme@(guix-user)> ,use (gnu packages base)
Notice that REPL commands are introduced by a leading comma. A REPL command
like use
is not valid Scheme code; it’s interpreted specially by the
REPL.
Guix extends the Guile REPL with additional commands for convenience. Among
those, the build
command comes in handy: it ensures that the given
file-like object is built, building it if needed, and returns its output
file name(s). In the example below, we build the coreutils
and
grep
packages, as well as a “computed file” (veja computed-file
), and we use the scandir
procedure to list the
files in Grep’s /bin
directory:
scheme@(guix-user)> ,build coreutils $1 = "/gnu/store/…-coreutils-8.32-debug" $2 = "/gnu/store/…-coreutils-8.32" scheme@(guix-user)> ,build grep $3 = "/gnu/store/…-grep-3.6" scheme@(guix-user)> ,build (computed-file "x" #~(mkdir #$output)) building /gnu/store/…-x.drv... $4 = "/gnu/store/…-x" scheme@(guix-user)> ,use(ice-9 ftw) scheme@(guix-user)> (scandir (string-append $3 "/bin")) $5 = ("." ".." "egrep" "fgrep" "grep")
As a packager, you may be willing to inspect the build phases or flags of a given package; this is particularly useful when relying a lot on inheritance to define package variants (veja Defining Package Variants) or when package arguments are a result of some computation, both of which can make it harder to foresee what ends up in the package arguments. Additional commands let you inspect those package arguments:
scheme@(guix-user)> ,phases grep $1 = (modify-phases %standard-phases (add-after 'install 'fix-egrep-and-fgrep (lambda* (#:key outputs #:allow-other-keys) (let* ((out (assoc-ref outputs "out")) (bin (string-append out "/bin"))) (substitute* (list (string-append bin "/egrep") (string-append bin "/fgrep")) (("^exec grep") (string-append "exec " bin "/grep"))))))) scheme@(guix-user)> ,configure-flags findutils $2 = (list "--localstatedir=/var") scheme@(guix-user)> ,make-flags binutils $3 = '("MAKEINFO=true")
At a lower-level, a useful command is lower
: it takes a file-like
object and “lowers” it into a derivation (veja Derivações) or a store
file:
scheme@(guix-user)> ,lower grep $6 = #<derivation /gnu/store/…-grep-3.6.drv => /gnu/store/…-grep-3.6 7f0e639115f0> scheme@(guix-user)> ,lower (plain-file "x" "Hello!") $7 = "/gnu/store/…-x"
The full list of REPL commands can be seen by typing ,help guix
and
is given below for reference.
Lower object and build it if it’s not already built, returning its output file name(s).
Lower object into a derivation or store file name and return it.
Change build verbosity to level.
This is similar to the --verbosity command-line option (veja Opções de compilação comum): level 0 means total silence, level 1 shows build events only, and higher levels print build logs.
These REPL commands return the value of one element of the arguments
field of package (veja package
Reference): the first one show the
staged code associated with #:phases
(veja Build Phases), the
second shows the code for #:configure-flags
, and ,make-flags
returns the code for #:make-flags
.
Run exp, a monadic expression, through the store monad. Veja A mônada do armazém, for more information.
Enter a new REPL to evaluate monadic expressions (veja A mônada do armazém).
You can quit this “inner” REPL by typing ,q
.
Próximo: Foreign Architectures, Anterior: Interface de programação, Acima: GNU Guix [Conteúdo][Índice]
This section describes Guix command-line utilities. Some of them are primarily targeted at developers and users who write new package definitions, while others are more generally useful. They complement the Scheme programming interface of Guix in a convenient way.
guix build
guix edit
guix download
guix hash
guix import
guix refresh
guix style
guix lint
guix size
guix graph
guix publish
guix challenge
guix copy
guix container
guix weather
guix processes
Próximo: Invocando guix edit
, Acima: Utilitários [Conteúdo][Índice]
guix build
The guix build
command builds packages or derivations and their
dependencies, and prints the resulting store paths. Note that it does not
modify the user’s profile—this is the job of the guix package
command (veja Invocando guix package
). Thus, it is mainly useful for
distribution developers.
The general syntax is:
guix build options package-or-derivation…
As an example, the following command builds the latest versions of Emacs and of Guile, displays their build logs, and finally displays the resulting directories:
guix build emacs guile
Similarly, the following command builds all the available packages:
guix build --quiet --keep-going \ $(guix package -A | awk '{ print $1 "@" $2 }')
package-or-derivation may be either the name of a package found in the
software distribution such as coreutils
or coreutils@8.20
, or
a derivation such as /gnu/store/…-coreutils-8.19.drv. In the
former case, a package with the corresponding name (and optionally version)
is searched for among the GNU distribution modules (veja Módulos de pacote).
Alternatively, the --expression option may be used to specify a Scheme expression that evaluates to a package; this is useful when disambiguating among several same-named packages or package variants is needed.
There may be zero or more options. The available options are described in the subsections below.
Próximo: Opções de transformação de pacote, Acima: Invocando guix build
[Conteúdo][Índice]
A number of options that control the build process are common to
guix build
and other commands that can spawn builds, such as
guix package
or guix archive
. These are the following:
--load-path=directory
-L diretório
Add directory to the front of the package module search path (veja Módulos de pacote).
This allows users to define their own packages and make them visible to the command-line tools.
--keep-failed
-K
Keep the build tree of failed builds. Thus, if a build fails, its build tree is kept under /tmp, in a directory whose name is shown at the end of the build log. This is useful when debugging build issues. Veja Depurando falhas de compilação, for tips and tricks on how to debug build issues.
This option implies --no-offload, and it has no effect when
connecting to a remote daemon with a guix://
URI (veja the GUIX_DAEMON_SOCKET
variable).
--keep-going
-k
Keep going when some of the derivations fail to build; return only once all the builds have either completed or failed.
The default behavior is to stop as soon as one of the specified derivations has failed.
--dry-run
-n
Do not build the derivations.
--fallback
When substituting a pre-built binary fails, fall back to building packages locally (veja Falha na substituição).
--substitute-urls=urls
Consider urls the whitespace-separated list of substitute source URLs,
overriding the default list of URLs of guix-daemon
(veja guix-daemon
URLs).
This means that substitutes may be downloaded from urls, provided they are signed by a key authorized by the system administrator (veja Substitutos).
When urls is the empty string, substitutes are effectively disabled.
--no-substitutes
Não use substitutos para compilar produtos. Ou seja, sempre crie coisas localmente, em vez de permitir downloads de binários pré-compilados (veja Substitutos).
--no-grafts
Do not “graft” packages. In practice, this means that package updates available as grafts are not applied. Veja Atualizações de segurança, for more information on grafts.
--rounds=n
Build each derivation n times in a row, and raise an error if consecutive build results are not bit-for-bit identical.
This is a useful way to detect non-deterministic builds processes.
Non-deterministic build processes are a problem because they make it
practically impossible for users to verify whether third-party
binaries are genuine. Veja Invocando guix challenge
, for more.
Quando usado em conjunto com --keep-failed, uma saída de comparação é mantida no armazém, sob /gnu/store/…-check. Isso facilita procurar por diferenças entre os dois resultados.
--no-offload
Do not use offload builds to other machines (veja Usando o recurso de descarregamento). That is, always build things locally instead of offloading builds to remote machines.
--max-silent-time=segundos
Quando o processo de compilação ou substituição permanecer em silêncio por mais de segundos, encerra-o e relata uma falha de compilação.
By default, the daemon’s setting is honored (veja --max-silent-time).
--timeout=segundos
Da mesma forma, quando o processo de compilação ou substituição durar mais que segundos, encerra-o e relata uma falha de compilação.
By default, the daemon’s setting is honored (veja --timeout).
-v level
--verbosity=level
Use the given verbosity level, an integer. Choosing 0 means that no output is produced, 1 is for quiet output; 2 is similar to 1 but it additionally displays download URLs; 3 shows all the build log output on standard error.
--cores=n
-c n
Allow the use of up to n CPU cores for the build. The special value
0
means to use as many CPU cores as available.
--max-jobs=n
-M n
Allow at most n build jobs in parallel. Veja --max-jobs, for details about this option and the equivalent
guix-daemon
option.
--debug=level
Produce debugging output coming from the build daemon. level must be an integer between 0 and 5; higher means more verbose output. Setting a level of 4 or more may be helpful when debugging setup issues with the build daemon.
Behind the scenes, guix build
is essentially an interface to the
package-derivation
procedure of the (guix packages)
module,
and to the build-derivations
procedure of the (guix
derivations)
module.
In addition to options explicitly passed on the command line, guix
build
and other guix
commands that support building honor the
GUIX_BUILD_OPTIONS
environment variable.
Users can define this variable to a list of command line options that will
automatically be used by guix build
and other guix
commands that can perform builds, as in the example below:
$ export GUIX_BUILD_OPTIONS="--no-substitutes -c 2 -L /foo/bar"
These options are parsed independently, and the result is appended to the parsed command-line options.
Próximo: Opções de compilação adicional, Anterior: Opções de compilação comum, Acima: Invocando guix build
[Conteúdo][Índice]
Another set of command-line options supported by guix build
and
also guix package
are package transformation options. These
are options that make it possible to define package variants—for
instance, packages built from different source code. This is a convenient
way to create customized packages on the fly without having to type in the
definitions of package variants (veja Definindo pacotes).
Package transformation options are preserved across upgrades: guix
upgrade
attempts to apply transformation options initially used when
creating the profile to the upgraded packages.
The available options are listed below. Most commands support them and also support a --help-transform option that lists all the available options and a synopsis (these options are not shown in the --help output for brevity).
--tune[=cpu]
Use versions of the packages marked as “tunable” optimized for cpu.
When cpu is native
, or when it is omitted, tune for the CPU on
which the guix
command is running.
Valid cpu names are those recognized by the underlying compiler, by
default the GNU Compiler Collection. On x86_64 processors, this includes
CPU names such as nehalem
, haswell
, and skylake
(veja -march
em Using the GNU Compiler Collection
(GCC)).
As new generations of CPUs come out, they augment the standard instruction set architecture (ISA) with additional instructions, in particular instructions for single-instruction/multiple-data (SIMD) parallel processing. For example, while Core2 and Skylake CPUs both implement the x86_64 ISA, only the latter supports AVX2 SIMD instructions.
The primary gain one can expect from --tune is for programs that
can make use of those SIMD capabilities and that do not already have
a mechanism to select the right optimized code at run time. Packages that
have the tunable?
property set are considered tunable packages
by the --tune option; a package definition with the property set
looks like this:
(package
(name "hello-simd")
;; ...
;; This package may benefit from SIMD extensions so
;; mark it as "tunable".
(properties '((tunable? . #t))))
Other packages are not considered tunable. This allows Guix to use generic binaries in the cases where tuning for a specific CPU is unlikely to provide any gain.
Tuned packages are built with -march=CPU
; under the hood, the
-march option is passed to the actual wrapper by a compiler
wrapper. Since the build machine may not be able to run code for the target
CPU micro-architecture, the test suite is not run when building a tuned
package.
To reduce rebuilds to the minimum, tuned packages are grafted onto packages that depend on them (veja grafts). Thus, using --no-grafts cancels the effect of --tune.
We call this technique package multi-versioning: several variants of tunable packages may be built, one for each CPU variant. It is the coarse-grain counterpart of function multi-versioning as implemented by the GNU tool chain (veja Function Multiversioning em Using the GNU Compiler Collection (GCC)).
--with-source=fonte
--with-source=pacote=fonte
--with-source=package@version=source
Use source as the source of package, and version as its
version number. source must be a file name or a URL, as for
guix download
(veja Invocando guix download
).
When package is omitted, it is taken to be the package name specified
on the command line that matches the base of source—e.g., if
source is /src/guile-2.0.10.tar.gz
, the corresponding package
is guile
.
Likewise, when version is omitted, the version string is inferred from
source; in the previous example, it is 2.0.10
.
This option allows users to try out versions of packages other than the one
provided by the distribution. The example below downloads
ed-1.7.tar.gz from a GNU mirror and uses that as the source for the
ed
package:
guix build ed --with-source=mirror://gnu/ed/ed-1.4.tar.gz
As a developer, --with-source makes it easy to test release candidates, and even to test their impact on packages that depend on them:
guix build elogind --with-source=…/shepherd-0.9.0rc1.tar.gz
… or to build from a checkout in a pristine environment:
$ git clone git://git.sv.gnu.org/guix.git $ guix build guix --with-source=guix@1.0=./guix
--with-input=pacote=substituto
Replace dependency on package by a dependency on replacement.
package must be a package name, and replacement must be a
package specification such as guile
or guile@1.8
.
For instance, the following command builds Guix, but replaces its dependency
on the current stable version of Guile with a dependency on the legacy
version of Guile, guile@2.2
:
guix build --with-input=guile=guile@2.2 guix
This is a recursive, deep replacement. So in this example, both guix
and its dependency guile-json
(which also depends on guile
)
get rebuilt against guile@2.2
.
This is implemented using the package-input-rewriting/spec
Scheme
procedure (veja package-input-rewriting/spec
).
--with-graft=package=replacement
This is similar to --with-input but with an important difference: instead of rebuilding the whole dependency chain, replacement is built and then grafted onto the binaries that were initially referring to package. Veja Atualizações de segurança, for more information on grafts.
For example, the command below grafts version 3.5.4 of GnuTLS onto Wget and all its dependencies, replacing references to the version of GnuTLS they currently refer to:
guix build --with-graft=gnutls=gnutls@3.5.4 wget
This has the advantage of being much faster than rebuilding everything. But there is a caveat: it works if and only if package and replacement are strictly compatible—for example, if they provide a library, the application binary interface (ABI) of those libraries must be compatible. If replacement is somehow incompatible with package, then the resulting package may be unusable. Use with care!
--with-debug-info=package
Build package in a way that preserves its debugging info and graft it
onto packages that depend on it. This is useful if package does not
already provide debugging info as a debug
output (veja Instalando arquivos de depuração).
For example, suppose you’re experiencing a crash in Inkscape and would like
to see what’s up in GLib, a library deep down in Inkscape’s dependency
graph. GLib lacks a debug
output, so debugging is tough.
Fortunately, you rebuild GLib with debugging info and tack it on Inkscape:
guix install inkscape --with-debug-info=glib
Only GLib needs to be recompiled so this takes a reasonable amount of time. Veja Instalando arquivos de depuração, for more info.
Nota: Under the hood, this option works by passing the ‘#:strip-binaries? #f’ to the build system of the package of interest (veja Sistemas de compilação). Most build systems support that option but some do not. In that case, an error is raised.
Likewise, if a C/C++ package is built without
-g
(which is rarely the case), debugging info will remain unavailable even when#:strip-binaries?
is false.
--with-c-toolchain=package=toolchain
This option changes the compilation of package and everything that depends on it so that they get built with toolchain instead of the default GNU tool chain for C/C++.
Consider this example:
guix build octave-cli \ --with-c-toolchain=fftw=gcc-toolchain@10 \ --with-c-toolchain=fftwf=gcc-toolchain@10
The command above builds a variant of the fftw
and fftwf
packages using version 10 of gcc-toolchain
instead of the default
tool chain, and then builds a variant of the GNU Octave command-line
interface using them. GNU Octave itself is also built with
gcc-toolchain@10
.
This other example builds the Hardware Locality (hwloc
) library and
its dependents up to intel-mpi-benchmarks
with the Clang C compiler:
guix build --with-c-toolchain=hwloc=clang-toolchain \ intel-mpi-benchmarks
Nota: There can be application binary interface (ABI) incompatibilities among tool chains. This is particularly true of the C++ standard library and run-time support libraries such as that of OpenMP. By rebuilding all dependents with the same tool chain, --with-c-toolchain minimizes the risks of incompatibility but cannot entirely eliminate them. Choose package wisely.
--with-git-url=pacote=url
¶Build package from the latest commit of the master
branch of
the Git repository at url. Git sub-modules of the repository are
fetched, recursively.
For example, the following command builds the NumPy Python library against the latest commit of the master branch of Python itself:
guix build python-numpy \ --with-git-url=python=https://github.com/python/cpython
This option can also be combined with --with-branch or --with-commit (see below).
Obviously, since it uses the latest commit of the given branch, the result of such a command varies over time. Nevertheless it is a convenient way to rebuild entire software stacks against the latest commit of one or more packages. This is particularly useful in the context of continuous integration (CI).
Checkouts are kept in a cache under ~/.cache/guix/checkouts to speed up consecutive accesses to the same repository. You may want to clean it up once in a while to save disk space.
--with-branch=pacote=ramo
Build package from the latest commit of branch. If the
source
field of package is an origin with the git-fetch
method (veja origin
Reference) or a git-checkout
object, the
repository URL is taken from that source
. Otherwise you have to use
--with-git-url to specify the URL of the Git repository.
For instance, the following command builds guile-sqlite3
from the
latest commit of its master
branch, and then builds guix
(which depends on it) and cuirass
(which depends on guix
)
against this specific guile-sqlite3
build:
guix build --with-branch=guile-sqlite3=master cuirass
--with-commit=pacote=commit
This is similar to --with-branch, except that it builds from
commit rather than the tip of a branch. commit must be a valid
Git commit SHA1 identifier, a tag, or a git describe
style
identifier such as 1.0-3-gabc123
.
--with-patch=package=file
Add file to the list of patches applied to package, where
package is a spec such as python@3.8
or glibc
.
file must contain a patch; it is applied with the flags specified in
the origin
of package (veja origin
Reference), which by
default includes -p1
(veja patch Directories em Comparing and Merging Files).
As an example, the command below rebuilds Coreutils with the GNU C Library (glibc) patched with the given patch:
guix build coreutils --with-patch=glibc=./glibc-frob.patch
In this example, glibc itself as well as everything that leads to Coreutils in the dependency graph is rebuilt.
--with-configure-flag=package=flag
Append flag to the configure flags of package, where
package is a spec such as guile@3.0
or glibc
. The
build system of package must support the #:configure-flags
argument.
For example, the command below builds GNU Hello with the configure flag
--disable-nls
:
guix build hello --with-configure-flag=hello=--disable-nls
The following command passes an extra flag to cmake
as it builds
lapack
:
guix build lapack \ --with-configure-flag=lapack=-DBUILD_SHARED_LIBS=OFF
Nota: Under the hood, this option works by passing the ‘#:configure-flags’ argument to the build system of the package of interest (veja Sistemas de compilação). Most build systems support that option but some do not. In that case, an error is raised.
--with-latest=package
--with-version=package=version
So you like living on the bleeding edge? The --with-latest option
is for you! It replaces occurrences of package in the dependency graph
with its latest upstream version, as reported by guix refresh
(veja Invocando guix refresh
).
It does so by determining the latest upstream release of package (if possible), downloading it, and authenticating it if it comes with an OpenPGP signature.
As an example, the command below builds Guix against the latest version of Guile-JSON:
guix build guix --with-latest=guile-json
The --with-version works similarly except that it lets you specify that you want precisely version, assuming that version exists upstream. For example, to spawn a development environment with SciPy built against version 1.22.4 of NumPy (skipping its test suite because hey, we’re not gonna wait this long), you would run:
guix shell python python-scipy --with-version=python-numpy=1.22.4
Aviso: Because they depend on source code published at a given point in time on upstream servers, deployments made with --with-latest and --with-version may be non-reproducible: source might disappear or be modified in place on the servers.
To deploy old software versions without compromising on reproducibility, veja
guix time-machine
.
There are limitations. First, in cases where the tool cannot or does not know how to authenticate source code, you are at risk of running malicious code; a warning is emitted in this case. Second, this option simply changes the source used in the existing package definitions, which is not always sufficient: there might be additional dependencies that need to be added, patches to apply, and more generally the quality assurance work that Guix developers normally do will be missing.
You’ve been warned! When those limitations are acceptable, it’s a snappy way to stay on top. We encourage you to submit patches updating the actual package definitions once you have successfully tested an upgrade with --with-latest (veja Contribuindo).
--without-tests=package
Build package without running its tests. This can be useful in situations where you want to skip the lengthy test suite of a intermediate package, or if a package’s test suite fails in a non-deterministic fashion. It should be used with care because running the test suite is a good way to ensure a package is working as intended.
Turning off tests leads to a different store item. Consequently, when using this option, anything that depends on package must be rebuilt, as in this example:
guix install --without-tests=python python-notebook
The command above installs python-notebook
on top of python
built without running its test suite. To do so, it also rebuilds everything
that depends on python
, including python-notebook
itself.
Internally, --without-tests relies on changing the #:tests?
option of a package’s check
phase (veja Sistemas de compilação). Note that
some packages use a customized check
phase that does not respect a
#:tests? #f
setting. Therefore, --without-tests has no
effect on these packages.
Wondering how to achieve the same effect using Scheme code, for example in your manifest, or how to write your own package transformation? Veja Defining Package Variants, for an overview of the programming interfaces available.
Próximo: Depurando falhas de compilação, Anterior: Opções de transformação de pacote, Acima: Invocando guix build
[Conteúdo][Índice]
The command-line options presented below are specific to guix
build
.
--quiet
-q
Build quietly, without displaying the build log; this is equivalent to --verbosity=0. Upon completion, the build log is kept in /var (or similar) and can always be retrieved using the --log-file option.
--file=file
-f arquivo
Build the package, derivation, or other file-like object that the code within file evaluates to (veja file-like objects).
As an example, file might contain a package definition like this (veja Definindo pacotes):
(use-modules (guix) (guix build-system gnu) (guix licenses)) (package (name "hello") (version "2.10") (source (origin (method url-fetch) (uri (string-append "mirror://gnu/hello/hello-" version ".tar.gz")) (sha256 (base32 "0ssi1wpaf7plaswqqjwigppsg5fyh99vdlb9kzl7c9lng89ndq1i")))) (build-system gnu-build-system) (synopsis "Hello, GNU world: An example GNU package") (description "Guess what GNU Hello prints!") (home-page "http://www.gnu.org/software/hello/") (license gpl3+))
The file may also contain a JSON representation of one or more package
definitions. Running guix build -f
on hello.json with the
following contents would result in building the packages myhello
and
greeter
:
[ { "name": "myhello", "version": "2.10", "source": "mirror://gnu/hello/hello-2.10.tar.gz", "build-system": "gnu", "arguments": { "tests?": false }, "home-page": "https://www.gnu.org/software/hello/", "synopsis": "Hello, GNU world: An example GNU package", "description": "GNU Hello prints a greeting.", "license": "GPL-3.0+", "native-inputs": ["gettext"] }, { "name": "greeter", "version": "1.0", "source": "mirror://gnu/hello/hello-2.10.tar.gz", "build-system": "gnu", "arguments": { "test-target": "foo", "parallel-build?": false }, "home-page": "https://example.com/", "synopsis": "Greeter using GNU Hello", "description": "This is a wrapper around GNU Hello.", "license": "GPL-3.0+", "inputs": ["myhello", "hello"] } ]
--manifest=manifest
-m manifest
Build all packages listed in the given manifest (veja --manifest).
--expression=expr
-e expr
Build the package or derivation expr evaluates to.
For example, expr may be (@ (gnu packages guile) guile-1.8)
,
which unambiguously designates this specific variant of version 1.8 of
Guile.
Alternatively, expr may be a G-expression, in which case it is used as
a build program passed to gexp->derivation
(veja Expressões-G).
Lastly, expr may refer to a zero-argument monadic procedure
(veja A mônada do armazém). The procedure must return a derivation as a
monadic value, which is then passed through run-with-store
.
--source
-S
Build the source derivations of the packages, rather than the packages themselves.
For instance, guix build -S gcc
returns something like
/gnu/store/…-gcc-4.7.2.tar.bz2, which is the GCC source
tarball.
The returned source tarball is the result of applying any patches and code
snippets specified in the package origin
(veja Definindo pacotes).
As with other derivations, the result of building a source derivation can be verified using the --check option (veja build-check). This is useful to validate that a (potentially already built or substituted, thus cached) package source matches against its declared hash.
Note that guix build -S
compiles the sources only of the specified
packages. They do not include the sources of statically linked dependencies
and by themselves are insufficient for reproducing the packages.
--sources
Fetch and return the source of package-or-derivation and all their dependencies, recursively. This is a handy way to obtain a local copy of all the source code needed to build packages, allowing you to eventually build them even without network access. It is an extension of the --source option and can accept one of the following optional argument values:
pacote
This value causes the --sources option to behave in the same way as the --source option.
all
Build the source derivations of all packages, including any source that
might be listed as inputs
. This is the default value.
$ guix build --sources tzdata The following derivations will be built: /gnu/store/…-tzdata2015b.tar.gz.drv /gnu/store/…-tzcode2015b.tar.gz.drv
transitive
Build the source derivations of all packages, as well of all transitive inputs to the packages. This can be used e.g. to prefetch package source for later offline building.
$ guix build --sources=transitive tzdata The following derivations will be built: /gnu/store/…-tzcode2015b.tar.gz.drv /gnu/store/…-findutils-4.4.2.tar.xz.drv /gnu/store/…-grep-2.21.tar.xz.drv /gnu/store/…-coreutils-8.23.tar.xz.drv /gnu/store/…-make-4.1.tar.xz.drv /gnu/store/…-bash-4.3.tar.xz.drv …
--system=system
-s sistema
Attempt to build for system—e.g., i686-linux
—instead of the
system type of the build host. The guix build
command allows you
to repeat this option several times, in which case it builds for all the
specified systems; other commands ignore extraneous -s options.
Nota: The --system flag is for native compilation and must not be confused with cross-compilation. See --target below for information on cross-compilation.
An example use of this is on Linux-based systems, which can emulate
different personalities. For instance, passing --system=i686-linux
on an x86_64-linux
system or --system=armhf-linux on an
aarch64-linux
system allows you to build packages in a complete
32-bit environment.
Nota: Building for an
armhf-linux
system is unconditionally enabled onaarch64-linux
machines, although certain aarch64 chipsets do not allow for this functionality, notably the ThunderX.
Similarly, when transparent emulation with QEMU and binfmt_misc
is
enabled (veja qemu-binfmt-service-type
),
you can build for any system for which a QEMU binfmt_misc
handler is
installed.
Builds for a system other than that of the machine you are using can also be offloaded to a remote machine of the right architecture. Veja Usando o recurso de descarregamento, for more information on offloading.
--target=triplet
¶Cross-build for triplet, which must be a valid GNU triplet, such as
"aarch64-linux-gnu"
(veja GNU
configuration triplets em Autoconf).
--list-systems
List all the supported systems, that can be passed as an argument to --system.
--list-targets
List all the supported targets, that can be passed as an argument to --target.
--check
¶Rebuild package-or-derivation, which are already available in the store, and raise an error if the build results are not bit-for-bit identical.
This mechanism allows you to check whether previously installed substitutes
are genuine (veja Substitutos), or whether the build result of a package
is deterministic. Veja Invocando guix challenge
, for more background
information and tools.
Quando usado em conjunto com --keep-failed, uma saída de comparação é mantida no armazém, sob /gnu/store/…-check. Isso facilita procurar por diferenças entre os dois resultados.
--repair
¶Attempt to repair the specified store items, if they are corrupt, by re-downloading or rebuilding them.
This operation is not atomic and thus restricted to root
.
--derivations
-d
Return the derivation paths, not the output paths, of the given packages.
--root=arquivo
¶-r arquivo
Make file a symlink to the result, and register it as a garbage collector root.
Consequently, the results of this guix build
invocation are
protected from garbage collection until file is removed. When that
option is omitted, build results are eligible for garbage collection as soon
as the build completes. Veja Invocando guix gc
, for more on GC roots.
--log-file
¶Return the build log file names or URLs for the given package-or-derivation, or raise an error if build logs are missing.
This works regardless of how packages or derivations are specified. For instance, the following invocations are equivalent:
guix build --log-file $(guix build -d guile) guix build --log-file $(guix build guile) guix build --log-file guile guix build --log-file -e '(@ (gnu packages guile) guile-2.0)'
If a log is unavailable locally, and unless --no-substitutes is passed, the command looks for a corresponding log on one of the substitute servers.
So for instance, imagine you want to see the build log of GDB on
aarch64
, but you are actually on an x86_64
machine:
$ guix build --log-file gdb -s aarch64-linux https://bordeaux.guix.gnu.org/log/…-gdb-7.10
You can freely access a huge library of build logs!
Anterior: Opções de compilação adicional, Acima: Invocando guix build
[Conteúdo][Índice]
When defining a new package (veja Definindo pacotes), you will probably find yourself spending some time debugging and tweaking the build until it succeeds. To do that, you need to operate the build commands yourself in an environment as close as possible to the one the build daemon uses.
To that end, the first thing to do is to use the --keep-failed or
-K option of guix build
, which will keep the failed build
tree in /tmp or whatever directory you specified as TMPDIR
(veja --keep-failed).
From there on, you can cd
to the failed build tree and source the
environment-variables file, which contains all the environment
variable definitions that were in place when the build failed. So let’s say
you’re debugging a build failure in package foo
; a typical session
would look like this:
$ guix build foo -K … build fails $ cd /tmp/guix-build-foo.drv-0 $ source ./environment-variables $ cd foo-1.2
Now, you can invoke commands as if you were the daemon (almost) and troubleshoot your build process.
Sometimes it happens that, for example, a package’s tests pass when you run them manually but they fail when the daemon runs them. This can happen because the daemon runs builds in containers where, unlike in our environment above, network access is missing, /bin/sh does not exist, etc. (veja Configuração do ambiente de compilação).
In such cases, you may need to inspect the build process from within a container similar to the one the build daemon creates:
$ guix build -K foo … $ cd /tmp/guix-build-foo.drv-0 $ guix shell --no-grafts -C -D foo strace gdb [env]# source ./environment-variables [env]# cd foo-1.2
Here, guix shell -C
creates a container and spawns a new shell in
it (veja Invoking guix shell
). The strace gdb
part adds the
strace
and gdb
commands to the container, which you may
find handy while debugging. The --no-grafts option makes sure we
get the exact same environment, with ungrafted packages (veja Atualizações de segurança, for more info on grafts).
To get closer to a container like that used by the build daemon, we can remove /bin/sh:
[env]# rm /bin/sh
(Don’t worry, this is harmless: this is all happening in the throw-away
container created by guix shell
.)
The strace
command is probably not in the search path, but we can
run:
[env]# $GUIX_ENVIRONMENT/bin/strace -f -o log make check
In this way, not only you will have reproduced the environment variables the daemon uses, you will also be running the build process in a container similar to the one the daemon uses.
Próximo: Invocando guix download
, Anterior: Invocando guix build
, Acima: Utilitários [Conteúdo][Índice]
guix edit
So many packages, so many source files! The guix edit
command
facilitates the life of users and packagers by pointing their editor at the
source file containing the definition of the specified packages. For
instance:
guix edit gcc@4.9 vim
launches the program specified in the VISUAL
or in the EDITOR
environment variable to view the recipe of GCC 4.9.3 and that of Vim.
If you are using a Guix Git checkout (veja Compilando do git), or have
created your own packages on GUIX_PACKAGE_PATH
(veja Módulos de pacote), you will be able to edit the package recipes. In other cases,
you will be able to examine the read-only recipes for packages currently in
the store.
Instead of GUIX_PACKAGE_PATH
, the command-line option
--load-path=directory (or in short -L
directory) allows you to add directory to the front of the
package module search path and so make your own packages visible.
Próximo: Invocando guix hash
, Anterior: Invocando guix edit
, Acima: Utilitários [Conteúdo][Índice]
guix download
When writing a package definition, developers typically need to download a
source tarball, compute its SHA256 hash, and write that hash in the package
definition (veja Definindo pacotes). The guix download
tool
helps with this task: it downloads a file from the given URI, adds it to the
store, and prints both its file name in the store and its SHA256 hash.
The fact that the downloaded file is added to the store saves bandwidth:
when the developer eventually tries to build the newly defined package with
guix build
, the source tarball will not have to be downloaded
again because it is already in the store. It is also a convenient way to
temporarily stash files, which may be deleted eventually (veja Invocando guix gc
).
The guix download
command supports the same URIs as used in
package definitions. In particular, it supports mirror://
URIs.
https
URIs (HTTP over TLS) are supported provided the Guile
bindings for GnuTLS are available in the user’s environment; when they are
not available, an error is raised. Veja how to install
the GnuTLS bindings for Guile em GnuTLS-Guile, for more
information.
guix download
verifies HTTPS server certificates by loading the
certificates of X.509 authorities from the directory pointed to by the
SSL_CERT_DIR
environment variable (veja Certificados X.509), unless
--no-check-certificate is used.
Alternatively, guix download
can also retrieve a Git repository,
possibly a specific commit, tag, or branch.
The following options are available:
--hash=algorithm
-H algorithm
Compute a hash using the specified algorithm. Veja Invocando guix hash
, for more information.
--format=fmt
-f fmt
Write the hash in the format specified by fmt. For more information
on the valid values for fmt, veja Invocando guix hash
.
--no-check-certificate
Do not validate the X.509 certificates of HTTPS servers.
When using this option, you have absolutely no guarantee that you are communicating with the authentic server responsible for the given URL, which makes you vulnerable to “man-in-the-middle” attacks.
--output=arquivo
-o arquivo
Save the downloaded file to file instead of adding it to the store.
--git
-g
Checkout the Git repository at the latest commit on the default branch.
--commit=commit-or-tag
Checkout the Git repository at commit-or-tag.
commit-or-tag can be either a tag or a commit defined in the Git repository.
--branch=ramo
Checkout the Git repository at branch.
The repository will be checked out at the latest commit of branch, which must be a valid branch of the Git repository.
--recursive
-r
Recursively clone the Git repository.
Próximo: Invoking guix import
, Anterior: Invocando guix download
, Acima: Utilitários [Conteúdo][Índice]
guix hash
The guix hash
command computes the hash of a file. It is
primarily a convenience tool for anyone contributing to the distribution: it
computes the cryptographic hash of one or more files, which can be used in
the definition of a package (veja Definindo pacotes).
The general syntax is:
guix hash option file ...
When file is -
(a hyphen), guix hash
computes the
hash of data read from standard input. guix hash
has the
following options:
--hash=algorithm
-H algorithm
Compute a hash using the specified algorithm, sha256
by
default.
algorithm must be the name of a cryptographic hash algorithm supported
by Libgcrypt via Guile-Gcrypt—e.g., sha512
or sha3-256
(veja Hash Functions em Guile-Gcrypt Reference Manual).
--format=fmt
-f fmt
Write the hash in the format specified by fmt.
Supported formats: base64
, nix-base32
, base32
,
base16
(hex
and hexadecimal
can be used as well).
If the --format option is not specified, guix hash
will
output the hash in nix-base32
. This representation is used in the
definitions of packages.
--recursive
-r
The --recursive option is deprecated in favor of --serializer=nar (see below); -r remains accepted as a convenient shorthand.
--serializer=type
-S type
Compute the hash on file using type serialization.
type may be one of the following:
nenhuma
This is the default: it computes the hash of a file’s contents.
nar
Compute the hash of a “normalized archive” (or “nar”) containing
file, including its children if it is a directory. Some of the
metadata of file is part of the archive; for instance, when file
is a regular file, the hash is different depending on whether file is
executable or not. Metadata such as time stamps have no impact on the hash
(veja Invocando guix archive
, for more info on the nar format).
git
Compute the hash of the file or directory as a Git “tree”, following the same method as the Git version control system.
--exclude-vcs
-x
When combined with --recursive, exclude version control system directories (.bzr, .git, .hg, etc.).
As an example, here is how you would compute the hash of a Git checkout,
which is useful when using the git-fetch
method (veja origin
Reference):
$ git clone http://example.org/foo.git $ cd foo $ guix hash -x --serializer=nar .
Próximo: Invocando guix refresh
, Anterior: Invocando guix hash
, Acima: Utilitários [Conteúdo][Índice]
guix import
The guix import
command is useful for people who would like to add
a package to the distribution with as little work as possible—a legitimate
demand. The command knows of a few repositories from which it can
“import” package metadata. The result is a package definition, or a
template thereof, in the format we know (veja Definindo pacotes).
The general syntax is:
guix import [global-options…] importer package [options…]
importer specifies the source from which to import package metadata,
and options specifies a package identifier and other options specific
to importer. guix import
itself has the following
global-options:
--insert=file
-i file
Insert the package definition(s) that the importer generated into the specified file, either in alphabetical order among existing package definitions, or at the end of the file otherwise.
Some of the importers rely on the ability to run the gpgv
command. For these, GnuPG must be installed and in $PATH
; run
guix install gnupg
if needed.
Currently, the available “importers” are:
gnu
Import metadata for the given GNU package. This provides a template for the latest version of that GNU package, including the hash of its source tarball, and its canonical synopsis and description.
Additional information such as the package dependencies and its license needs to be figured out manually.
For example, the following command returns a package definition for GNU Hello:
guix import gnu hello
Specific command-line options are:
--key-download=policy
As for guix refresh
, specify the policy to handle missing OpenPGP
keys when verifying the package signature. Veja --key-download.
pypi
¶Import metadata from the Python Package
Index. Information is taken from the JSON-formatted description available
at pypi.python.org
and usually includes all the relevant information,
including package dependencies. For maximum efficiency, it is recommended
to install the unzip
utility, so that the importer can unzip
Python wheels and gather data from them.
The command below imports metadata for the latest version of the
itsdangerous
Python package:
guix import pypi itsdangerous
You can also ask for a specific version:
guix import pypi itsdangerous@1.1.0
--recursive
-r
Traverse the dependency graph of the given upstream package recursively and generate package expressions for all those packages that are not yet in Guix.
gem
¶Import metadata from RubyGems. Information is
taken from the JSON-formatted description available at rubygems.org
and includes most relevant information, including runtime dependencies.
There are some caveats, however. The metadata doesn’t distinguish between
synopses and descriptions, so the same string is used for both fields.
Additionally, the details of non-Ruby dependencies required to build native
extensions is unavailable and left as an exercise to the packager.
The command below imports metadata for the rails
Ruby package:
guix import gem rails
You can also ask for a specific version:
guix import gem rails@7.0.4
--recursive
-r
Traverse the dependency graph of the given upstream package recursively and generate package expressions for all those packages that are not yet in Guix.
minetest
¶Import metadata from ContentDB. Information is taken from the JSON-formatted metadata provided through ContentDB’s API and includes most relevant information, including dependencies. There are some caveats, however. The license information is often incomplete. The commit hash is sometimes missing. The descriptions are in the Markdown format, but Guix uses Texinfo instead. Texture packs and subgames are unsupported.
The command below imports metadata for the Mesecons mod by Jeija:
guix import minetest Jeija/mesecons
The author name can also be left out:
guix import minetest mesecons
--recursive
-r
Traverse the dependency graph of the given upstream package recursively and generate package expressions for all those packages that are not yet in Guix.
cpan
¶Import metadata from MetaCPAN.
Information is taken from the JSON-formatted metadata provided through
MetaCPAN’s API and includes most
relevant information, such as module dependencies. License information
should be checked closely. If Perl is available in the store, then the
corelist
utility will be used to filter core modules out of the list
of dependencies.
The command below imports metadata for the Acme::Boolean Perl module:
guix import cpan Acme::Boolean
cran
¶Import metadata from CRAN, the central repository for the GNU R statistical and graphical environment.
Information is extracted from the DESCRIPTION file of the package.
The command below imports metadata for the Cairo R package:
guix import cran Cairo
You can also ask for a specific version:
guix import cran rasterVis@0.50.3
When --recursive is added, the importer will traverse the dependency graph of the given upstream package recursively and generate package expressions for all those packages that are not yet in Guix.
When --style=specification is added, the importer will generate package definitions whose inputs are package specifications instead of references to package variables. This is useful when generated package definitions are to be appended to existing user modules, as the list of used package modules need not be changed. The default is --style=variable.
When --prefix=license: is added, the importer will prefix license
atoms with license:
, allowing a prefixed import of (guix
licenses)
.
When --archive=bioconductor is added, metadata is imported from Bioconductor, a repository of R packages for the analysis and comprehension of high-throughput genomic data in bioinformatics.
Information is extracted from the DESCRIPTION file contained in the package archive.
The command below imports metadata for the GenomicRanges R package:
guix import cran --archive=bioconductor GenomicRanges
Finally, you can also import R packages that have not yet been published on CRAN or Bioconductor as long as they are in a git repository. Use --archive=git followed by the URL of the git repository:
guix import cran --archive=git https://github.com/immunogenomics/harmony
texlive
¶Import TeX package information from the TeX Live package database for TeX packages that are part of the TeX Live distribution.
Information about the package is obtained from the TeX Live package
database, a plain text file that is included in the texlive-scripts
package. The source code is downloaded from possibly multiple locations in
the SVN repository of the Tex Live project. Note that therefore SVN must be
installed and in $PATH
; run guix install subversion
if needed.
The command below imports metadata for the fontspec
TeX package:
guix import texlive fontspec
Additional options include:
--recursive
-r
Traverse the dependency graph of the given upstream package recursively and generate package expressions for all those packages that are not yet in Guix.
json
¶Import package metadata from a local JSON file. Consider the following example package definition in JSON format:
{ "name": "hello", "version": "2.10", "source": "mirror://gnu/hello/hello-2.10.tar.gz", "build-system": "gnu", "home-page": "https://www.gnu.org/software/hello/", "synopsis": "Hello, GNU world: An example GNU package", "description": "GNU Hello prints a greeting.", "license": "GPL-3.0+", "native-inputs": ["gettext"] }
The field names are the same as for the <package>
record
(Veja Definindo pacotes). References to other packages are provided as
JSON lists of quoted package specification strings such as guile
or
guile@2.0
.
The importer also supports a more explicit source definition using the
common fields for <origin>
records:
{ … "source": { "method": "url-fetch", "uri": "mirror://gnu/hello/hello-2.10.tar.gz", "sha256": { "base32": "0ssi1wpaf7plaswqqjwigppsg5fyh99vdlb9kzl7c9lng89ndq1i" } } … }
The command below reads metadata from the JSON file hello.json
and
outputs a package expression:
guix import json hello.json
hackage
¶Import metadata from the Haskell community’s central package archive Hackage. Information is taken from Cabal files and includes all the relevant information, including package dependencies.
Specific command-line options are:
--stdin
-s
Read a Cabal file from standard input.
--no-test-dependencies
-t
Do not include dependencies required only by the test suites.
--cabal-environment=alist
-e alist
alist is a Scheme alist defining the environment in which the Cabal
conditionals are evaluated. The accepted keys are: os
, arch
,
impl
and a string representing the name of a flag. The value
associated with a flag has to be either the symbol true
or
false
. The value associated with other keys has to conform to the
Cabal file format definition. The default value associated with the keys
os
, arch
and impl
is ‘linux’, ‘x86_64’ and
‘ghc’, respectively.
--recursive
-r
Traverse the dependency graph of the given upstream package recursively and generate package expressions for all those packages that are not yet in Guix.
The command below imports metadata for the latest version of the HTTP
Haskell package without including test dependencies and specifying the value
of the flag ‘network-uri’ as false
:
guix import hackage -t -e "'((\"network-uri\" . false))" HTTP
A specific package version may optionally be specified by following the package name by an at-sign and a version number as in the following example:
guix import hackage mtl@2.1.3.1
stackage
¶The stackage
importer is a wrapper around the hackage
one. It
takes a package name, looks up the package version included in a long-term
support (LTS) Stackage release and uses the
hackage
importer to retrieve its metadata. Note that it is up to you
to select an LTS release compatible with the GHC compiler used by Guix.
Specific command-line options are:
--no-test-dependencies
-t
Do not include dependencies required only by the test suites.
--lts-version=versão
-l versão
version is the desired LTS release version. If omitted the latest release is used.
--recursive
-r
Traverse the dependency graph of the given upstream package recursively and generate package expressions for all those packages that are not yet in Guix.
The command below imports metadata for the HTTP Haskell package included in the LTS Stackage release version 7.18:
guix import stackage --lts-version=7.18 HTTP
elpa
¶Import metadata from an Emacs Lisp Package Archive (ELPA) package repository (veja Packages em The GNU Emacs Manual).
Specific command-line options are:
--archive=repo
-a repo
repo identifies the archive repository from which to retrieve the information. Currently the supported repositories and their identifiers are:
gnu
identifier. This is the default.
Packages from elpa.gnu.org
are signed with one of the keys contained
in the GnuPG keyring at share/emacs/25.1/etc/package-keyring.gpg (or
similar) in the emacs
package (veja ELPA
package signatures em The GNU Emacs Manual).
nongnu
identifier.
melpa-stable
identifier.
melpa
identifier.
--recursive
-r
Traverse the dependency graph of the given upstream package recursively and generate package expressions for all those packages that are not yet in Guix.
crate
¶Import metadata from the crates.io Rust package repository crates.io, as in this example:
guix import crate blake2-rfc
The crate importer also allows you to specify a version string:
guix import crate constant-time-eq@0.1.0
Additional options include:
--recursive
-r
Traverse the dependency graph of the given upstream package recursively and generate package expressions for all those packages that are not yet in Guix.
--recursive-dev-dependencies
If --recursive-dev-dependencies is specified, also the recursively imported packages contain their development dependencies, which are recursively imported as well.
--allow-yanked
If no non-yanked version of a crate is available, use the latest yanked version instead instead of aborting.
elm
¶Import metadata from the Elm package repository package.elm-lang.org, as in this example:
guix import elm elm-explorations/webgl
The Elm importer also allows you to specify a version string:
guix import elm elm-explorations/webgl@1.1.3
Additional options include:
--recursive
-r
Traverse the dependency graph of the given upstream package recursively and generate package expressions for all those packages that are not yet in Guix.
npm-binary
¶Import metadata from the npm Registry, as in this example:
guix import npm-binary buffer-crc32
The npm-binary importer also allows you to specify a version string:
guix import npm-binary buffer-crc32@1.0.0
Nota: Generated package expressions skip the build step of the
node-build-system
. As such, generated package expressions often refer to transpiled or generated files, instead of being built from source.
Additional options include:
--recursive
-r
Traverse the dependency graph of the given upstream package recursively and generate package expressions for all those packages that are not yet in Guix.
opam
¶Import metadata from the OPAM package repository used by the OCaml community.
Additional options include:
--recursive
-r
Traverse the dependency graph of the given upstream package recursively and generate package expressions for all those packages that are not yet in Guix.
composer
¶Import metadata from the Composer package archive used by the PHP community, as in this example:
guix import composer phpunit/phpunit
Additional options include:
--recursive
-r
Traverse the dependency graph of the given upstream package recursively and generate package expressions for all those packages that are not yet in Guix.
--repo
By default, packages are searched in the official OPAM repository. This option, which can be used more than once, lets you add other repositories which will be searched for packages. It accepts as valid arguments:
opam
,
coq
(equivalent to coq-released
), coq-core-dev
,
coq-extra-dev
or grew
.
opam repository add
command (for instance, the URL equivalent of the
above opam
name would be https://opam.ocaml.org).
Repositories are assumed to be passed to this option by order of
preference. The additional repositories will not replace the default
opam
repository, which is always kept as a fallback.
Also, please note that versions are not compared across repositories. The first repository (from left to right) that has at least one version of a given package will prevail over any others, and the version imported will be the latest one found in this repository only.
go
¶Import metadata for a Go module using proxy.golang.org.
guix import go gopkg.in/yaml.v2
It is possible to use a package specification with a @VERSION
suffix
to import a specific version.
Additional options include:
--recursive
-r
Traverse the dependency graph of the given upstream package recursively and generate package expressions for all those packages that are not yet in Guix.
--pin-versions
When using this option, the importer preserves the exact versions of the Go modules dependencies instead of using their latest available versions. This can be useful when attempting to import packages that recursively depend on former versions of themselves to build. When using this mode, the symbol of the package is made by appending the version to its name, so that multiple versions of the same package can coexist.
egg
¶Import metadata for CHICKEN eggs. The information is taken from PACKAGE.egg files found in the eggs-5-all Git repository. However, it does not provide all the information that we need, there is no “description” field, and the licenses used are not always precise (BSD is often used instead of BSD-N).
guix import egg sourcehut
You can also ask for a specific version:
guix import egg arrays@1.0
Additional options include:
--recursive
-r
Traverse the dependency graph of the given upstream package recursively and generate package expressions for all those packages that are not yet in Guix.
hexpm
¶Import metadata from the hex.pm Erlang and Elixir package repository hex.pm, as in this example:
guix import hexpm stun
The importer tries to determine the build system used by the package.
The hexpm importer also allows you to specify a version string:
guix import hexpm cf@0.3.0
Additional options include:
--recursive
-r
Traverse the dependency graph of the given upstream package recursively and generate package expressions for all those packages that are not yet in Guix.
The structure of the guix import
code is modular. It would be
useful to have more importers for other package formats, and your help is
welcome here (veja Contribuindo).
Próximo: Invoking guix style
, Anterior: Invoking guix import
, Acima: Utilitários [Conteúdo][Índice]
guix refresh
The primary audience of the guix refresh
command is packagers. As
a user, you may be interested in the --with-latest option, which
can bring you package update superpowers built upon guix refresh
(veja --with-latest). By
default, guix refresh
reports any packages provided by the
distribution that are outdated compared to the latest upstream version, like
this:
$ guix refresh gnu/packages/gettext.scm:29:13: gettext would be upgraded from 0.18.1.1 to 0.18.2.1 gnu/packages/glib.scm:77:12: glib would be upgraded from 2.34.3 to 2.37.0
Alternatively, one can specify packages to consider, in which case a warning is emitted for packages that lack an updater:
$ guix refresh coreutils guile guile-ssh gnu/packages/ssh.scm:205:2: warning: no updater for guile-ssh gnu/packages/guile.scm:136:12: guile would be upgraded from 2.0.12 to 2.0.13
guix refresh
browses the upstream repository of each package and
determines the highest version number of the releases therein. The command
knows how to update specific types of packages: GNU packages, ELPA packages,
etc.—see the documentation for --type below. There are many
packages, though, for which it lacks a method to determine whether a new
upstream release is available. However, the mechanism is extensible, so
feel free to get in touch with us to add a new method!
--recursive
Consider the packages specified, and all the packages upon which they depend.
$ guix refresh --recursive coreutils gnu/packages/acl.scm:40:13: acl would be upgraded from 2.2.53 to 2.3.1 gnu/packages/m4.scm:30:12: 1.4.18 is already the latest version of m4 gnu/packages/xml.scm:68:2: warning: no updater for expat gnu/packages/multiprecision.scm:40:12: 6.1.2 is already the latest version of gmp …
If for some reason you don’t want to update to the latest version, you can update to a specific version by appending an equal sign and the desired version number to the package specification. Note that not all updaters support this; an error is reported when an updater cannot refresh to the specified version.
$ guix refresh trytond-party gnu/packages/guile.scm:392:2: guile would be upgraded from 3.0.3 to 3.0.5 $ guix refresh -u guile=3.0.4 … gnu/packages/guile.scm:392:2: guile: updating from version 3.0.3 to version 3.0.4... … $ guix refresh -u guile@2.0=2.0.12 … gnu/packages/guile.scm:147:2: guile: updating from version 2.0.10 to version 2.0.12... …
In some specific cases, you may have many packages specified via a manifest or a module selection which should all be updated together; for these cases, the --target-version option can be provided to have them all refreshed to the same version, as shown in the examples below:
$ guix refresh qtbase qtdeclarative --target-version=6.5.2 gnu/packages/qt.scm:1248:13: qtdeclarative would be upgraded from 6.3.2 to 6.5.2 gnu/packages/qt.scm:584:2: qtbase would be upgraded from 6.3.2 to 6.5.2
$ guix refresh --manifest=qt5-manifest.scm --target-version=5.15.10 gnu/packages/qt.scm:1173:13: qtxmlpatterns would be upgraded from 5.15.8 to 5.15.10 gnu/packages/qt.scm:1202:13: qtdeclarative would be upgraded from 5.15.8 to 5.15.10 gnu/packages/qt.scm:1762:13: qtserialbus would be upgraded from 5.15.8 to 5.15.10 gnu/packages/qt.scm:2070:13: qtquickcontrols2 would be upgraded from 5.15.8 to 5.15.10 …
Sometimes the upstream name differs from the package name used in Guix, and
guix refresh
needs a little help. Most updaters honor the
upstream-name
property in package definitions, which can be used to
that effect:
(define-public network-manager
(package
(name "network-manager")
;; …
(properties '((upstream-name . "NetworkManager")))))
When passed --update, it modifies distribution source files to
update the version numbers and source code hashes of those package
definitions, as well as possibly their inputs (veja Definindo pacotes).
This is achieved by downloading each package’s latest source tarball and its
associated OpenPGP signature, authenticating the downloaded tarball against
its signature using gpgv
, and finally computing its hash—note
that GnuPG must be installed and in $PATH
; run guix install
gnupg
if needed.
When the public key used to sign the tarball is missing from the user’s
keyring, an attempt is made to automatically retrieve it from a public key
server; when this is successful, the key is added to the user’s keyring;
otherwise, guix refresh
reports an error.
The following options are supported:
--expression=expr
-e expr
Consider the package expr evaluates to.
This is useful to precisely refer to a package, as in this example:
guix refresh -l -e '(@@ (gnu packages commencement) glibc-final)'
This command lists the dependents of the “final” libc (essentially all the packages).
--update
-u
Update distribution source files (package definitions) in place. This is usually run from a checkout of the Guix source tree (veja Executando guix antes dele ser instalado):
./pre-inst-env guix refresh -s non-core -u
Veja Definindo pacotes, for more information on package definitions. You can also run it on packages from a third-party channel:
guix refresh -L /path/to/channel -u package
Veja Creating a Channel, on how to create a channel.
This command updates the version and source code hash of the package. Depending on the updater being used, it can also update the various ‘inputs’ fields of the package. In some cases, the updater might get inputs wrong—it might not know about an extra input that’s necessary, or it might add an input that should be avoided.
To address that, packagers can add properties stating inputs that should be
added to those found by the updater or inputs that should be ignored: the
updater-extra-inputs
and updater-ignored-inputs
properties
pertain to “regular” inputs, and there are equivalent properties for
‘native’ and ‘propagated’ inputs. In the example below, we tell
the updater that we need ‘openmpi’ as an additional input:
(define-public python-mpi4py
(package
(name "python-mpi4py")
;; …
(inputs (list openmpi))
(properties
'((updater-extra-inputs . ("openmpi"))))))
That way, guix refresh -u python-mpi4py
will leave the
‘openmpi’ input, even if it is not among the inputs it would normally
add.
--select=[subset]
-s subset
Select all the packages in subset, one of core
, non-core
or module:name
.
The core
subset refers to all the packages at the core of the
distribution—i.e., packages that are used to build “everything else”.
This includes GCC, libc, Binutils, Bash, etc. Usually, changing one of
these packages in the distribution entails a rebuild of all the others.
Thus, such updates are an inconvenience to users in terms of build time or
bandwidth used to achieve the upgrade.
The non-core
subset refers to the remaining packages. It is
typically useful in cases where an update of the core packages would be
inconvenient.
The module:name
subset refers to all the packages in a
specified guile module. The module can be specified as module:guile
or module:(gnu packages guile)
, the former is a shorthand for the
later.
--manifest=arquivo
-m arquivo
Select all the packages from the manifest in file. This is useful to check if any packages of the user manifest can be updated.
--type=updater
-t updater
Select only packages handled by updater (may be a comma-separated list of updaters). Currently, updater may be one of:
gnu
the updater for GNU packages;
savannah
the updater for packages hosted at Savannah;
sourceforge
the updater for packages hosted at SourceForge;
gnome
the updater for GNOME packages;
kde
the updater for KDE packages;
xorg
the updater for X.org packages;
kernel.org
the updater for packages hosted on kernel.org;
egg
the updater for Egg packages;
elpa
the updater for ELPA packages;
cran
the updater for CRAN packages;
bioconductor
the updater for Bioconductor R packages;
cpan
the updater for CPAN packages;
pypi
the updater for PyPI packages.
gem
the updater for RubyGems packages.
github
the updater for GitHub packages.
hackage
the updater for Hackage packages.
stackage
the updater for Stackage packages.
crate
the updater for Crates packages.
launchpad
the updater for Launchpad packages.
generic-html
a generic updater that crawls the HTML page where the source tarball of the
package is hosted, when applicable, or the HTML page specified by the
release-monitoring-url
property of the package.
generic-git
a generic updater for packages hosted on Git repositories. It tries to be smart about parsing Git tag names, but if it is not able to parse the tag name and compare tags correctly, users can define the following properties for a package.
release-tag-prefix
: a regular expression for matching a prefix of
the tag name.
release-tag-suffix
: a regular expression for matching a suffix of
the tag name.
release-tag-version-delimiter
: a string used as the delimiter in
the tag name for separating the numbers of the version.
accept-pre-releases
: by default, the updater will ignore
pre-releases; to make it also look for pre-releases, set the this property
to #t
.
(package
(name "foo")
;; ...
(properties
'((release-tag-prefix . "^release0-")
(release-tag-suffix . "[a-z]?$")
(release-tag-version-delimiter . ":"))))
For instance, the following command only checks for updates of Emacs
packages hosted at elpa.gnu.org
and for updates of CRAN packages:
$ guix refresh --type=elpa,cran gnu/packages/statistics.scm:819:13: r-testthat would be upgraded from 0.10.0 to 0.11.0 gnu/packages/emacs.scm:856:13: emacs-auctex would be upgraded from 11.88.6 to 11.88.9
--list-updaters
List available updaters and exit (see --type above).
For each updater, display the fraction of packages it covers; at the end, display the fraction of packages covered by all these updaters.
In addition, guix refresh
can be passed one or more package names,
as in this example:
$ ./pre-inst-env guix refresh -u emacs idutils gcc@4.8
The command above specifically updates the emacs
and idutils
packages. The --select option would have no effect in this case.
You might also want to update definitions that correspond to the packages
installed in your profile:
$ ./pre-inst-env guix refresh -u \ $(guix package --list-installed | cut -f1)
When considering whether to upgrade a package, it is sometimes convenient to
know which packages would be affected by the upgrade and should be checked
for compatibility. For this the following option may be used when passing
guix refresh
one or more package names:
--list-dependent
-l
List top-level dependent packages that would need to be rebuilt as a result of upgrading one or more packages.
Veja the reverse-package
type of guix
graph
, for information on how to visualize the list of dependents of a
package.
Be aware that the --list-dependent option only approximates the rebuilds that would be required as a result of an upgrade. More rebuilds might be required under some circumstances.
$ guix refresh --list-dependent flex Building the following 120 packages would ensure 213 dependent packages are rebuilt: hop@2.4.0 emacs-geiser@0.13 notmuch@0.18 mu@0.9.9.5 cflow@1.4 idutils@4.6 …
The command above lists a set of packages that could be built to check for
compatibility with an upgraded flex
package.
--list-transitive
-T
List all the packages which one or more packages depend upon.
$ guix refresh --list-transitive flex flex@2.6.4 depends on the following 25 packages: perl@5.28.0 help2man@1.47.6 bison@3.0.5 indent@2.2.10 tar@1.30 gzip@1.9 bzip2@1.0.6 xz@5.2.4 file@5.33 …
The command above lists a set of packages which, when changed, would cause
flex
to be rebuilt.
The following options can be used to customize GnuPG operation:
--gpg=command
Use command as the GnuPG 2.x command. command is searched for
in $PATH
.
--keyring=file
Use file as the keyring for upstream keys. file must be in the
keybox format. Keybox files usually have a name ending in .kbx
and the GNU Privacy Guard (GPG) can manipulate these files
(veja kbxutil
em Using the GNU Privacy Guard,
for information on a tool to manipulate keybox files).
When this option is omitted, guix refresh
uses
~/.config/guix/upstream/trustedkeys.kbx as the keyring for upstream
signing keys. OpenPGP signatures are checked against keys from this
keyring; missing keys are downloaded to this keyring as well (see
--key-download below).
You can export keys from your default GPG keyring into a keybox file using commands like this one:
gpg --export rms@gnu.org | kbxutil --import-openpgp >> mykeyring.kbx
Likewise, you can fetch keys to a specific keybox file like this:
gpg --no-default-keyring --keyring mykeyring.kbx \ --recv-keys 3CE464558A84FDC69DB40CFB090B11993D9AEBB5
Veja --keyring em Using the GNU Privacy Guard, for more information on GPG’s --keyring option.
--key-download=policy
Handle missing OpenPGP keys according to policy, which may be one of:
always
Always download missing OpenPGP keys from the key server, and add them to the user’s GnuPG keyring.
never
Never try to download missing OpenPGP keys. Instead just bail out.
interactive
When a package signed with an unknown OpenPGP key is encountered, ask the user whether to download it or not. This is the default behavior.
--key-server=host
Use host as the OpenPGP key server when importing a public key.
--load-path=directory
-L diretório
Add directory to the front of the package module search path (veja Módulos de pacote).
This allows users to define their own packages and make them visible to the command-line tools.
The github
updater uses the GitHub API to query for new releases. When used repeatedly e.g. when
refreshing all packages, GitHub will eventually refuse to answer any further
API requests. By default 60 API requests per hour are allowed, and a full
refresh on all GitHub packages in Guix requires more than this.
Authentication with GitHub through the use of an API token alleviates these
limits. To use an API token, set the environment variable
GUIX_GITHUB_TOKEN
to a token procured from
https://github.com/settings/tokens or otherwise.
Próximo: Invocando guix lint
, Anterior: Invocando guix refresh
, Acima: Utilitários [Conteúdo][Índice]
guix style
The guix style
command helps users and packagers alike style their
package definitions and configuration files according to the latest
fashionable trends. It can either reformat whole files, with the
--whole-file option, or apply specific styling rules to
individual package definitions. The command currently provides the
following styling rules:
The way package inputs are written is going through a transition
(veja package
Reference, for more on package inputs). Until version
1.3.0, package inputs were written using the “old style”, where each input
was given an explicit label, most of the time the package name:
(package
;; …
;; The "old style" (deprecated).
(inputs `(("libunistring" ,libunistring)
("libffi" ,libffi))))
Today, the old style is deprecated and the preferred style looks like this:
(package
;; …
;; The "new style".
(inputs (list libunistring libffi)))
Likewise, uses of alist-delete
and friends to manipulate inputs is
now deprecated in favor of modify-inputs
(veja Defining Package Variants, for more info on modify-inputs
).
In the vast majority of cases, this is a purely mechanical change on the
surface syntax that does not even incur a package rebuild. Running
guix style -S inputs
can do that for you, whether you’re working
on packages in Guix proper or in an external channel.
The general syntax is:
guix style [options] package…
This causes guix style
to analyze and rewrite the definition of
package… or, when package is omitted, of all the
packages. The --styling or -S option allows you to select
the style rule, the default rule being format
—see below.
To reformat entire source files, the syntax is:
guix style --whole-file file…
The available options are listed below.
--dry-run
-n
Show source file locations that would be edited but do not modify them.
--whole-file
-f
Reformat the given files in their entirety. In that case, subsequent arguments are interpreted as file names (rather than package names), and the --styling option has no effect.
As an example, here is how you might reformat your operating system configuration (you need write permissions for the file):
guix style -f /etc/config.scm
--alphabetical-sort
-A
Place the top-level package definitions in the given files in alphabetical order. Package definitions with matching names are placed with versions in descending order. This option only has an effect in combination with --whole-file.
--styling=rule
-S rule
Apply rule, one of the following styling rules:
format
Format the given package definition(s)—this is the default styling rule. For example, a packager running Guix on a checkout (veja Executando guix antes dele ser instalado) might want to reformat the definition of the Coreutils package like so:
./pre-inst-env guix style coreutils
entradas
Rewrite package inputs to the “new style”, as described above. This is
how you would rewrite inputs of package whatnot
in your own channel:
guix style -L ~/my/channel -S inputs whatnot
Rewriting is done in a conservative way: preserving comments and bailing out if it cannot make sense of the code that appears in an inputs field. The --input-simplification option described below provides fine-grain control over when inputs should be simplified.
arguments
Rewrite package arguments to use G-expressions (veja Expressões-G). For example, consider this package definition:
(define-public my-package
(package
;; …
(arguments ;old-style quoted arguments
'(#:make-flags '("V=1")
#:phases (modify-phases %standard-phases
(delete 'build))))))
Running guix style -S arguments
on this package would rewrite its
arguments
field like to:
(define-public my-package
(package
;; …
(arguments
(list #:make-flags #~'("V=1")
#:phases #~(modify-phases %standard-phases
(delete 'build))))))
Note that changes made by the arguments
rule do not entail a rebuild
of the affected packages. Furthermore, if a package definition happens to
be using G-expressions already, guix style
leaves it unchanged.
--list-stylings
-l
List and describe the available styling rules and exit.
--load-path=directory
-L diretório
Add directory to the front of the package module search path (veja Módulos de pacote).
--expression=expr
-e expr
Style the package expr evaluates to.
For example, running:
guix style -e '(@ (gnu packages gcc) gcc-5)'
styles the gcc-5
package definition.
--input-simplification=policy
When using the inputs
styling rule, with ‘-S inputs’, this
option specifies the package input simplification policy for cases where an
input label does not match the corresponding package name. policy may
be one of the following:
silent
Simplify inputs only when the change is “silent”, meaning that the package does not need to be rebuilt (its derivation is unchanged).
safe
Simplify inputs only when that is “safe” to do: the package might need to be rebuilt, but the change is known to have no observable effect.
always
Simplify inputs even when input labels do not match package names, and even if that might have an observable effect.
The default is silent
, meaning that input simplifications do not
trigger any package rebuild.
Próximo: Invocando guix size
, Anterior: Invoking guix style
, Acima: Utilitários [Conteúdo][Índice]
guix lint
The guix lint
command is meant to help package developers avoid
common errors and use a consistent style. It runs a number of checks on a
given set of packages in order to find common mistakes in their
definitions. Available checkers include (see --list-checkers
for a complete list):
synopsis
description
Validate certain typographical and stylistic rules about package descriptions and synopses.
inputs-should-be-native
Identify inputs that should most likely be native inputs.
source
página inicial
mirror-url
github-url
source-file-name
Probe home-page
and source
URLs and report those that are
invalid. Suggest a mirror://
URL when applicable. If the
source
URL redirects to a GitHub URL, recommend usage of the GitHub
URL. Check that the source file name is meaningful, e.g. is not just a
version number or “git-checkout”, without a declared file-name
(veja origin
Reference).
source-unstable-tarball
Parse the source
URL to determine if a tarball from GitHub is
autogenerated or if it is a release tarball. Unfortunately GitHub’s
autogenerated tarballs are sometimes regenerated.
derivation
Check that the derivation of the given packages can be successfully computed for all the supported systems (veja Derivações).
profile-collisions
Check whether installing the given packages in a profile would lead to
collisions. Collisions occur when several packages with the same name but a
different version or a different store file name are propagated.
Veja propagated-inputs
, for more information on
propagated inputs.
archival
¶Checks whether the package’s source code is archived at Software Heritage.
When the source code that is not archived comes from a version-control
system (VCS)—e.g., it’s obtained with git-fetch
, send Software
Heritage a “save” request so that it eventually archives it. This ensures
that the source will remain available in the long term, and that Guix can
fall back to Software Heritage should the source code disappear from its
original host. The status of recent “save” requests can be
viewed on-line.
When source code is a tarball obtained with url-fetch
, simply print a
message when it is not archived. As of this writing, Software Heritage does
not allow requests to save arbitrary tarballs; we are working on ways to
ensure that non-VCS source code is also archived.
Software Heritage
limits the
request rate per IP address. When the limit is reached, guix
lint
prints a message and the archival
checker stops doing anything
until that limit has been reset.
cve
¶Report known vulnerabilities found in the Common Vulnerabilities and Exposures (CVE) databases of the current and past year published by the US NIST.
To view information about a particular vulnerability, visit pages such as:
https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-YYYY-ABCD
’
https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-YYYY-ABCD
’
where CVE-YYYY-ABCD
is the CVE identifier—e.g.,
CVE-2015-7554
.
Package developers can specify in package recipes the Common Platform Enumeration (CPE) name and version of the package when they differ from the name or version that Guix uses, as in this example:
(package
(name "grub")
;; …
;; CPE calls this package "grub2".
(properties '((cpe-name . "grub2")
(cpe-version . "2.3"))))
Some entries in the CVE database do not specify which version of a package they apply to, and would thus “stick around” forever. Package developers who found CVE alerts and verified they can be ignored can declare them as in this example:
(package
(name "t1lib")
;; …
;; These CVEs no longer apply and can be safely ignored.
(properties `((lint-hidden-cve . ("CVE-2011-0433"
"CVE-2011-1553"
"CVE-2011-1554"
"CVE-2011-5244")))))
formatting
Warn about obvious source code formatting issues: trailing white space, use of tabulations, etc.
input-labels
Report old-style input labels that do not match the name of the
corresponding package. This aims to help migrate from the “old input
style”. Veja package
Reference, for more information on package inputs
and input styles. Veja Invoking guix style
, on how to migrate to the new
style.
The general syntax is:
guix lint options package…
If no package is given on the command line, then all packages are checked. The options may be zero or more of the following:
--list-checkers
-l
List and describe all the available checkers that will be run on packages and exit.
--checkers
-c
Only enable the checkers specified in a comma-separated list using the names returned by --list-checkers.
--exclude
-x
Only disable the checkers specified in a comma-separated list using the names returned by --list-checkers.
--expression=expr
-e expr
Consider the package expr evaluates to.
This is useful to unambiguously designate packages, as in this example:
guix lint -c archival -e '(@ (gnu packages guile) guile-3.0)'
--no-network
-n
Only enable the checkers that do not depend on Internet access.
--load-path=directory
-L diretório
Add directory to the front of the package module search path (veja Módulos de pacote).
This allows users to define their own packages and make them visible to the command-line tools.
Próximo: Invocando guix graph
, Anterior: Invocando guix lint
, Acima: Utilitários [Conteúdo][Índice]
guix size
The guix size
command helps package developers profile the disk
usage of packages. It is easy to overlook the impact of an additional
dependency added to a package, or the impact of using a single output for a
package that could easily be split (veja Pacotes com múltiplas saídas). Such are the typical issues that guix size
can
highlight.
The command can be passed one or more package specifications such as
gcc@4.8
or guile:debug
, or a file name in the store.
Consider this example:
$ guix size coreutils store item total self /gnu/store/…-gcc-5.5.0-lib 60.4 30.1 38.1% /gnu/store/…-glibc-2.27 30.3 28.8 36.6% /gnu/store/…-coreutils-8.28 78.9 15.0 19.0% /gnu/store/…-gmp-6.1.2 63.1 2.7 3.4% /gnu/store/…-bash-static-4.4.12 1.5 1.5 1.9% /gnu/store/…-acl-2.2.52 61.1 0.4 0.5% /gnu/store/…-attr-2.4.47 60.6 0.2 0.3% /gnu/store/…-libcap-2.25 60.5 0.2 0.2% total: 78.9 MiB
The store items listed here constitute the transitive closure of Coreutils—i.e., Coreutils and all its dependencies, recursively—as would be returned by:
$ guix gc -R /gnu/store/…-coreutils-8.23
Here the output shows three columns next to store items. The first column, labeled “total”, shows the size in mebibytes (MiB) of the closure of the store item—that is, its own size plus the size of all its dependencies. The next column, labeled “self”, shows the size of the item itself. The last column shows the ratio of the size of the item itself to the space occupied by all the items listed here.
In this example, we see that the closure of Coreutils weighs in at 79 MiB, most of which is taken by libc and GCC’s run-time support libraries. (That libc and GCC’s libraries represent a large fraction of the closure is not a problem per se because they are always available on the system anyway.)
Since the command also accepts store file names, assessing the size of a build result is straightforward:
guix size $(guix system build config.scm)
When the package(s) passed to guix size
are available in the
store25, guix size
queries the daemon to determine its
dependencies, and measures its size in the store, similar to du -ms
--apparent-size
(veja du invocation em GNU Coreutils).
When the given packages are not in the store, guix size
reports information based on the available substitutes
(veja Substitutos). This makes it possible to profile the disk usage of
store items that are not even on disk, only available remotely.
You can also specify several package names:
$ guix size coreutils grep sed bash store item total self /gnu/store/…-coreutils-8.24 77.8 13.8 13.4% /gnu/store/…-grep-2.22 73.1 0.8 0.8% /gnu/store/…-bash-4.3.42 72.3 4.7 4.6% /gnu/store/…-readline-6.3 67.6 1.2 1.2% … total: 102.3 MiB
In this example we see that the combination of the four packages takes 102.3 MiB in total, which is much less than the sum of each closure since they have a lot of dependencies in common.
When looking at the profile returned by guix size
, you may find
yourself wondering why a given package shows up in the profile at all. To
understand it, you can use guix graph --path -t references
to
display the shortest path between the two packages (veja Invocando guix graph
).
The available options are:
Use substitute information from urls. Veja the same option for guix build
.
Sort lines according to key, one of the following options:
próprio
the size of each item (the default);
closure
the total size of the item’s closure.
Write a graphical map of disk usage in PNG format to file.
For the example above, the map looks like this:
This option requires that
Guile-Charting be
installed and visible in Guile’s module search path. When that is not the
case, guix size
fails as it tries to load it.
Consider packages for system—e.g., x86_64-linux
.
Add directory to the front of the package module search path (veja Módulos de pacote).
This allows users to define their own packages and make them visible to the command-line tools.
Próximo: Invocando guix publish
, Anterior: Invocando guix size
, Acima: Utilitários [Conteúdo][Índice]
guix graph
Packages and their dependencies form a graph, specifically a directed
acyclic graph (DAG). It can quickly become difficult to have a mental model
of the package DAG, so the guix graph
command provides a visual
representation of the DAG. By default, guix graph
emits a DAG
representation in the input format of Graphviz, so its output can be passed directly to the dot
command
of Graphviz. It can also emit an HTML page with embedded JavaScript code to
display a “chord diagram” in a Web browser, using the
d3.js library, or emit Cypher queries to construct
a graph in a graph database supporting the
openCypher query language. With
--path, it simply displays the shortest path between two packages.
The general syntax is:
guix graph options package…
For example, the following command generates a PDF file representing the package DAG for the GNU Core Utilities, showing its build-time dependencies:
guix graph coreutils | dot -Tpdf > dag.pdf
The output looks like this:
Nice little graph, no?
You may find it more pleasant to navigate the graph interactively with
xdot
(from the xdot
package):
guix graph coreutils | xdot -
But there is more than one graph! The one above is concise: it is the graph
of package objects, omitting implicit inputs such as GCC, libc, grep, etc.
It is often useful to have such a concise graph, but sometimes one may want
to see more details. guix graph
supports several types of graphs,
allowing you to choose the level of detail:
pacote
This is the default type used in the example above. It shows the DAG of package objects, excluding implicit dependencies. It is concise, but filters out many details.
reverse-package
This shows the reverse DAG of packages. For example:
guix graph --type=reverse-package ocaml
... yields the graph of packages that explicitly depend on OCaml
(if you are also interested in cases where OCaml is an implicit dependency,
see reverse-bag
below).
Note that for core packages this can yield huge graphs. If all you want is
to know the number of packages that depend on a given package, use
guix refresh --list-dependent
(veja --list-dependent).
bag-emerged
This is the package DAG, including implicit inputs.
For instance, the following command:
guix graph --type=bag-emerged coreutils
... yields this bigger graph:
At the bottom of the graph, we see all the implicit inputs of
gnu-build-system (veja gnu-build-system
).
Now, note that the dependencies of these implicit inputs—that is, the bootstrap dependencies (veja Inicializando)—are not shown here, for conciseness.
bag
Similar to bag-emerged
, but this time including all the bootstrap
dependencies.
bag-with-origins
Similar to bag
, but also showing origins and their dependencies.
reverse-bag
This shows the reverse DAG of packages. Unlike
reverse-package
, it also takes implicit dependencies into account.
For example:
guix graph -t reverse-bag dune
... yields the graph of all packages that depend on Dune, directly or
indirectly. Since Dune is an implicit dependency of many packages
via dune-build-system
, this shows a large number of packages,
whereas reverse-package
would show very few if any.
derivation
This is the most detailed representation: It shows the DAG of derivations (veja Derivações) and plain store items. Compared to the above representation, many additional nodes are visible, including build scripts, patches, Guile modules, etc.
For this type of graph, it is also possible to pass a .drv file name instead of a package name, as in:
guix graph -t derivation $(guix system build -d my-config.scm)
modulo
This is the graph of package modules (veja Módulos de pacote). For
example, the following command shows the graph for the package module that
defines the guile
package:
guix graph -t module guile | xdot -
All the types above correspond to build-time dependencies. The following graph type represents the run-time dependencies:
references
This is the graph of references of a package output, as returned by
guix gc --references
(veja Invocando guix gc
).
If the given package output is not available in the store, guix
graph
attempts to obtain dependency information from substitutes.
Here you can also pass a store file name instead of a package name. For example, the command below produces the reference graph of your profile (which can be big!):
guix graph -t references $(readlink -f ~/.guix-profile)
referrers
This is the graph of the referrers of a store item, as returned by
guix gc --referrers
(veja Invocando guix gc
).
This relies exclusively on local information from your store. For instance,
let us suppose that the current Inkscape is available in 10 profiles on your
machine; guix graph -t referrers inkscape
will show a graph rooted
at Inkscape and with those 10 profiles linked to it.
It can help determine what is preventing a store item from being garbage collected.
Often, the graph of the package you are interested in does not fit on your
screen, and anyway all you want to know is why that package actually
depends on some seemingly unrelated package. The --path option
instructs guix graph
to display the shortest path between two
packages (or derivations, or store items, etc.):
$ guix graph --path emacs libunistring emacs@26.3 mailutils@3.9 libunistring@0.9.10 $ guix graph --path -t derivation emacs libunistring /gnu/store/…-emacs-26.3.drv /gnu/store/…-mailutils-3.9.drv /gnu/store/…-libunistring-0.9.10.drv $ guix graph --path -t references emacs libunistring /gnu/store/…-emacs-26.3 /gnu/store/…-libidn2-2.2.0 /gnu/store/…-libunistring-0.9.10
Sometimes you still want to visualize the graph but would like to trim it so
it can actually be displayed. One way to do it is via the
--max-depth (or -M) option, which lets you specify the
maximum depth of the graph. In the example below, we visualize only
libreoffice
and the nodes whose distance to libreoffice
is at
most 2:
guix graph -M 2 libreoffice | xdot -f fdp -
Mind you, that’s still a big ball of spaghetti, but at least dot
can render it quickly and it can be browsed somewhat.
The available options are the following:
Produce a graph output of type, where type must be one of the values listed above.
Lista os tipos de gráficos disponíveis.
Produce a graph using the selected backend.
Lista os backends de gráficos disponíveis.
Currently, the available backends are Graphviz and d3.js.
Display the shortest path between two nodes of the type specified by
--type. The example below shows the shortest path between
libreoffice
and llvm
according to the references of
libreoffice
:
$ guix graph --path -t references libreoffice llvm /gnu/store/…-libreoffice-6.4.2.2 /gnu/store/…-libepoxy-1.5.4 /gnu/store/…-mesa-19.3.4 /gnu/store/…-llvm-9.0.1
Consider the package expr evaluates to.
This is useful to precisely refer to a package, as in this example:
guix graph -e '(@@ (gnu packages commencement) gnu-make-final)'
Display the graph for system—e.g., i686-linux
.
The package dependency graph is largely architecture-independent, but there are some architecture-dependent bits that this option allows you to visualize.
Add directory to the front of the package module search path (veja Módulos de pacote).
This allows users to define their own packages and make them visible to the command-line tools.
On top of that, guix graph
supports all the usual package
transformation options (veja Opções de transformação de pacote). This makes
it easy to view the effect of a graph-rewriting transformation such as
--with-input. For example, the command below outputs the graph of
git
once openssl
has been replaced by libressl
everywhere in the graph:
guix graph git --with-input=openssl=libressl
So many possibilities, so much fun!
Próximo: Invocando guix challenge
, Anterior: Invocando guix graph
, Acima: Utilitários [Conteúdo][Índice]
guix publish
The purpose of guix publish
is to enable users to easily share
their store with others, who can then use it as a substitute server
(veja Substitutos).
When guix publish
runs, it spawns an HTTP server which allows
anyone with network access to obtain substitutes from it. This means that
any machine running Guix can also act as if it were a build farm, since the
HTTP interface is compatible with Cuirass, the software behind the
bordeaux.guix.gnu.org
build farm.
For security, each substitute is signed, allowing recipients to check their
authenticity and integrity (veja Substitutos). Because guix
publish
uses the signing key of the system, which is only readable by the
system administrator, it must be started as root; the --user option
makes it drop root privileges early on.
The signing key pair must be generated before guix publish
is
launched, using guix archive --generate-key
(veja Invocando guix archive
).
When the --advertise option is passed, the server advertises its availability on the local network using multicast DNS (mDNS) and DNS service discovery (DNS-SD), currently via Guile-Avahi (veja Using Avahi in Guile Scheme Programs).
The general syntax is:
guix publish options…
Running guix publish
without any additional arguments will spawn
an HTTP server on port 8080:
guix publish
guix publish
can also be started following the systemd “socket
activation” protocol (veja make-systemd-constructor
em The GNU Shepherd Manual).
Once a publishing server has been authorized, the daemon may download substitutes from it. Veja Getting Substitutes from Other Servers.
By default, guix publish
compresses archives on the fly as it
serves them. This “on-the-fly” mode is convenient in that it requires no
setup and is immediately available. However, when serving lots of clients,
we recommend using the --cache option, which enables caching of the
archives before they are sent to clients—see below for details. The
guix weather
command provides a handy way to check what a server
provides (veja Invocando guix weather
).
As a bonus, guix publish
also serves as a content-addressed mirror
for source files referenced in origin
records (veja origin
Reference). For instance, assuming guix publish
is running on
example.org
, the following URL returns the raw
hello-2.10.tar.gz file with the given SHA256 hash (represented in
nix-base32
format, veja Invocando guix hash
):
http://example.org/file/hello-2.10.tar.gz/sha256/0ssi1…ndq1i
Obviously, these URLs only work for files that are in the store; in other cases, they return 404 (“Not Found”).
Build logs are available from /log
URLs like:
http://example.org/log/gwspk…-guile-2.2.3
When guix-daemon
is configured to save compressed build logs, as
is the case by default (veja Invocando guix-daemon
), /log
URLs
return the compressed log as-is, with an appropriate Content-Type
and/or Content-Encoding
header. We recommend running
guix-daemon
with --log-compression=gzip since Web
browsers can automatically decompress it, which is not the case with Bzip2
compression.
The following options are available:
--port=porta
-p porta
Ouve requisições HTTP na porta.
--listen=host
Listen on the network interface for host. The default is to accept connections from any interface.
--user=user
-u usuário
Change privileges to user as soon as possible—i.e., once the server socket is open and the signing key has been read.
--compression[=method[:level]]
-C [method[:level]]
Compress data using the given method and level. method is
one of lzip
, zstd
, and gzip
; when method is
omitted, gzip
is used.
When level is zero, disable compression. The range 1 to 9 corresponds to different compression levels: 1 is the fastest, and 9 is the best (CPU-intensive). The default is 3.
Usually, lzip
compresses noticeably better than gzip
for a
small increase in CPU usage; see
benchmarks on the lzip Web
page. However, lzip
achieves low decompression throughput (on the
order of 50 MiB/s on modern hardware), which can be a bottleneck for
someone who downloads over a fast network connection.
The compression ratio of zstd
is between that of lzip
and that
of gzip
; its main advantage is a
high decompression speed.
Unless --cache is used, compression occurs on the fly and the
compressed streams are not cached. Thus, to reduce load on the machine that
runs guix publish
, it may be a good idea to choose a low
compression level, to run guix publish
behind a caching proxy, or
to use --cache. Using --cache has the advantage that it
allows guix publish
to add Content-Length
HTTP header to
its responses.
This option can be repeated, in which case every substitute gets compressed using all the selected methods, and all of them are advertised. This is useful when users may not support all the compression methods: they can select the one they support.
--cache=directory
-c directory
Cache archives and meta-data (.narinfo
URLs) to directory and
only serve archives that are in cache.
When this option is omitted, archives and meta-data are created on-the-fly.
This can reduce the available bandwidth, especially when compression is
enabled, since this may become CPU-bound. Another drawback of the default
mode is that the length of archives is not known in advance, so
guix publish
does not add a Content-Length
HTTP header to
its responses, which in turn prevents clients from knowing the amount of
data being downloaded.
Conversely, when --cache is used, the first request for a store
item (via a .narinfo
URL) triggers a background process to
bake the archive—computing its .narinfo
and compressing the
archive, if needed. Once the archive is cached in directory,
subsequent requests succeed and are served directly from the cache, which
guarantees that clients get the best possible bandwidth.
That first .narinfo
request nonetheless returns 200, provided the
requested store item is “small enough”, below the cache bypass
threshold—see --cache-bypass-threshold below. That way, clients
do not have to wait until the archive is baked. For larger store items, the
first .narinfo
request returns 404, meaning that clients have to wait
until the archive is baked.
The “baking” process is performed by worker threads. By default, one thread per CPU core is created, but this can be customized. See --workers below.
When --ttl is used, cached entries are automatically deleted when they have expired.
--workers=N
When --cache is used, request the allocation of N worker threads to “bake” archives.
--ttl=ttl
Produce Cache-Control
HTTP headers that advertise a time-to-live
(TTL) of ttl. ttl must denote a duration: 5d
means 5
days, 1m
means 1 month, and so on.
This allows the user’s Guix to keep substitute information in cache for
ttl. However, note that guix publish
does not itself guarantee
that the store items it provides will indeed remain available for as long as
ttl.
Additionally, when --cache is used, cached entries that have not been accessed for ttl and that no longer have a corresponding item in the store, may be deleted.
--negative-ttl=ttl
Similarly produce Cache-Control
HTTP headers to advertise the
time-to-live (TTL) of negative lookups—missing store items, for
which the HTTP 404 code is returned. By default, no negative TTL is
advertised.
This parameter can help adjust server load and substitute latency by instructing cooperating clients to be more or less patient when a store item is missing.
--cache-bypass-threshold=size
When used in conjunction with --cache, store items smaller than
size are immediately available, even when they are not yet in cache.
size is a size in bytes, or it can be suffixed by M
for
megabytes and so on. The default is 10M
.
“Cache bypass” allows you to reduce the publication delay for clients at the expense of possibly additional I/O and CPU use on the server side: depending on the client access patterns, those store items can end up being baked several times until a copy is available in cache.
Increasing the threshold may be useful for sites that have few users, or to guarantee that users get substitutes even for store items that are not popular.
--nar-path=path
Use path as the prefix for the URLs of “nar” files (veja normalized archives).
By default, nars are served at a URL such as
/nar/gzip/…-coreutils-8.25
. This option allows you to change
the /nar
part to path.
--public-key=file
--private-key=file
Use the specific files as the public/private key pair used to sign the store items being published.
The files must correspond to the same key pair (the private key is used for
signing and the public key is merely advertised in the signature metadata).
They must contain keys in the canonical s-expression format as produced by
guix archive --generate-key
(veja Invocando guix archive
). By
default, /etc/guix/signing-key.pub and
/etc/guix/signing-key.sec are used.
--repl[=port]
-r [porta]
Spawn a Guile REPL server (veja REPL Servers em GNU Guile Reference
Manual) on port (37146 by default). This is used primarily for
debugging a running guix publish
server.
Enabling guix publish
on Guix System is a one-liner: just
instantiate a guix-publish-service-type
service in the
services
field of the operating-system
declaration
(veja guix-publish-service-type
).
If you are instead running Guix on a “foreign distro”, follow these instructions:
# ln -s ~root/.guix-profile/lib/systemd/system/guix-publish.service \ /etc/systemd/system/ # systemctl start guix-publish && systemctl enable guix-publish
# ln -s ~root/.guix-profile/lib/upstart/system/guix-publish.conf /etc/init/ # start guix-publish
Próximo: Invocando guix copy
, Anterior: Invocando guix publish
, Acima: Utilitários [Conteúdo][Índice]
guix challenge
Do the binaries provided by this server really correspond to the source code
it claims to build? Is a package build process deterministic? These are the
questions the guix challenge
command attempts to answer.
The former is obviously an important question: Before using a substitute server (veja Substitutos), one had better verify that it provides the right binaries, and thus challenge it. The latter is what enables the former: If package builds are deterministic, then independent builds of the package should yield the exact same result, bit for bit; if a server provides a binary different from the one obtained locally, it may be either corrupt or malicious.
We know that the hash that shows up in /gnu/store file names is the
hash of all the inputs of the process that built the file or
directory—compilers, libraries, build scripts,
etc. (veja Introdução). Assuming deterministic build processes, one
store file name should map to exactly one build output. guix
challenge
checks whether there is, indeed, a single mapping by comparing
the build outputs of several independent builds of any given store item.
The command output looks like this:
$ guix challenge \ --substitute-urls="https://bordeaux.guix.gnu.org https://guix.example.org" \ openssl git pius coreutils grep updating substitutes from 'https://bordeaux.guix.gnu.org'... 100.0% updating substitutes from 'https://guix.example.org'... 100.0% /gnu/store/…-openssl-1.0.2d contents differ: local hash: 0725l22r5jnzazaacncwsvp9kgf42266ayyp814v7djxs7nk963q https://bordeaux.guix.gnu.org/nar/…-openssl-1.0.2d: 0725l22r5jnzazaacncwsvp9kgf42266ayyp814v7djxs7nk963q https://guix.example.org/nar/…-openssl-1.0.2d: 1zy4fmaaqcnjrzzajkdn3f5gmjk754b43qkq47llbyak9z0qjyim differing files: /lib/libcrypto.so.1.1 /lib/libssl.so.1.1 /gnu/store/…-git-2.5.0 contents differ: local hash: 00p3bmryhjxrhpn2gxs2fy0a15lnip05l97205pgbk5ra395hyha https://bordeaux.guix.gnu.org/nar/…-git-2.5.0: 069nb85bv4d4a6slrwjdy8v1cn4cwspm3kdbmyb81d6zckj3nq9f https://guix.example.org/nar/…-git-2.5.0: 0mdqa9w1p6cmli6976v4wi0sw9r4p5prkj7lzfd1877wk11c9c73 differing file: /libexec/git-core/git-fsck /gnu/store/…-pius-2.1.1 contents differ: local hash: 0k4v3m9z1zp8xzzizb7d8kjj72f9172xv078sq4wl73vnq9ig3ax https://bordeaux.guix.gnu.org/nar/…-pius-2.1.1: 0k4v3m9z1zp8xzzizb7d8kjj72f9172xv078sq4wl73vnq9ig3ax https://guix.example.org/nar/…-pius-2.1.1: 1cy25x1a4fzq5rk0pmvc8xhwyffnqz95h2bpvqsz2mpvlbccy0gs differing file: /share/man/man1/pius.1.gz … 5 store items were analyzed: - 2 (40.0%) were identical - 3 (60.0%) differed - 0 (0.0%) were inconclusive
In this example, guix challenge
queries all the substitute servers
for each of the fives packages specified on the command line. It then
reports those store items for which the servers obtained a result different
from the local build (if it exists) and/or different from one another; here,
the ‘local hash’ lines indicate that a local build result was available
for each of these packages and shows its hash.
As an example, guix.example.org
always gets a different answer.
Conversely, bordeaux.guix.gnu.org
agrees with local builds,
except in the case of Git. This might indicate that the build process of
Git is non-deterministic, meaning that its output varies as a function of
various things that Guix does not fully control, in spite of building
packages in isolated environments (veja Recursos). Most common sources
of non-determinism include the addition of timestamps in build results, the
inclusion of random numbers, and directory listings sorted by inode number.
See https://reproducible-builds.org/docs/, for more information.
To find out what is wrong with this Git binary, the easiest approach is to run:
guix challenge git \ --diff=diffoscope \ --substitute-urls="https://bordeaux.guix.gnu.org https://guix.example.org"
This automatically invokes diffoscope
, which displays detailed
information about files that differ.
Alternatively, we can do something along these lines (veja Invocando guix archive
):
$ wget -q -O - https://bordeaux.guix.gnu.org/nar/lzip/…-git-2.5.0 \ | lzip -d | guix archive -x /tmp/git $ diff -ur --no-dereference /gnu/store/…-git.2.5.0 /tmp/git
This command shows the difference between the files resulting from the local
build, and the files resulting from the build on
bordeaux.guix.gnu.org
(veja Comparing and Merging
Files em Comparing and Merging Files). The diff
command works great for text files. When binary files differ, a better
option is Diffoscope, a tool that helps
visualize differences for all kinds of files.
Once you have done that work, you can tell whether the differences are due
to a non-deterministic build process or to a malicious server. We try hard
to remove sources of non-determinism in packages to make it easier to verify
substitutes, but of course, this is a process that involves not just Guix,
but a large part of the free software community. In the meantime,
guix challenge
is one tool to help address the problem.
If you are writing packages for Guix, you are encouraged to check whether
bordeaux.guix.gnu.org
and other substitute servers obtain the
same build result as you did with:
guix challenge package
The general syntax is:
guix challenge options argument…
where argument is a package specification such as guile@2.0
or
glibc:debug
or, alternatively, a store file name as returned, for
example, by guix build
or guix gc --list-live
.
When a difference is found between the hash of a locally-built item and that of a server-provided substitute, or among substitutes provided by different servers, the command displays it as in the example above and its exit code is 2 (other non-zero exit codes denote other kinds of errors).
The one option that matters is:
--substitute-urls=urls
Consider urls the whitespace-separated list of substitute source URLs to compare to.
--diff=mode
Upon mismatches, show differences according to mode, one of:
simple
(the default)Show the list of files that differ.
diffoscope
Invoke Diffoscope, passing it two directories whose contents do not match.
When command is an absolute file name, run command instead of Diffoscope.
nenhuma
Do not show further details about the differences.
Thus, unless --diff=none is passed, guix challenge
downloads the store items from the given substitute servers so that it can
compare them.
--verbose
-v
Show details about matches (identical contents) in addition to information about mismatches.
Próximo: Invocando guix container
, Anterior: Invocando guix challenge
, Acima: Utilitários [Conteúdo][Índice]
guix copy
The guix copy
command copies items from the store of one machine
to that of another machine over a secure shell (SSH)
connection26. For example, the following
command copies the coreutils
package, the user’s profile, and all
their dependencies over to host, logged in as user:
guix copy --to=user@host \ coreutils $(readlink -f ~/.guix-profile)
If some of the items to be copied are already present on host, they are not actually sent.
The command below retrieves libreoffice
and gimp
from
host, assuming they are available there:
guix copy --from=host libreoffice gimp
The SSH connection is established using the Guile-SSH client, which is compatible with OpenSSH: it honors ~/.ssh/known_hosts and ~/.ssh/config, and uses the SSH agent for authentication.
The key used to sign items that are sent must be accepted by the remote
machine. Likewise, the key used by the remote machine to sign items you are
retrieving must be in /etc/guix/acl so it is accepted by your own
daemon. Veja Invocando guix archive
, for more information about store item
authentication.
The general syntax is:
guix copy [--to=spec|--from=spec] items…
You must always specify one of the following options:
--to=spec
--from=spec
Specify the host to send to or receive from. spec must be an SSH spec
such as example.org
, charlie@example.org
, or
charlie@example.org:2222
.
The items can be either package names, such as gimp
, or store
items, such as /gnu/store/…-idutils-4.6.
When specifying the name of a package to send, it is first built if needed, unless --dry-run was specified. Common build options are supported (veja Opções de compilação comum).
Próximo: Invocando guix weather
, Anterior: Invocando guix copy
, Acima: Utilitários [Conteúdo][Índice]
guix container
Nota: As of version 9356a8c, this tool is experimental. The interface is subject to radical change in the future.
The purpose of guix container
is to manipulate processes running
within an isolated environment, commonly known as a “container”, typically
created by the guix shell
(veja Invoking guix shell
) and
guix system container
(veja Invoking guix system
) commands.
The general syntax is:
guix container action options…
action specifies the operation to perform with a container, and options specifies the context-specific arguments for the action.
The following actions are available:
exec
Execute a command within the context of a running container.
The syntax is:
guix container exec pid program arguments…
pid specifies the process ID of the running container. program specifies an executable file name within the root file system of the container. arguments are the additional options that will be passed to program.
The following command launches an interactive login shell inside a Guix
system container, started by guix system container
, and whose
process ID is 9001:
guix container exec 9001 /run/current-system/profile/bin/bash --login
Note that the pid cannot be the parent process of a container. It must be PID 1 of the container or one of its child processes.
Próximo: Invocando guix processes
, Anterior: Invocando guix container
, Acima: Utilitários [Conteúdo][Índice]
guix weather
Occasionally you’re grumpy because substitutes are lacking and you end up
building packages by yourself (veja Substitutos). The guix
weather
command reports on substitute availability on the specified servers
so you can have an idea of whether you’ll be grumpy today. It can sometimes
be useful info as a user, but it is primarily useful to people running
guix publish
(veja Invocando guix publish
). Sometimes
substitutes are available but they are not authorized on your system;
guix weather
reports it so you can authorize them if you want
(veja Getting Substitutes from Other Servers).
Here’s a sample run:
$ guix weather --substitute-urls=https://guix.example.org computing 5,872 package derivations for x86_64-linux... looking for 6,128 store items on https://guix.example.org.. updating substitutes from 'https://guix.example.org'... 100.0% https://guix.example.org 43.4% substitutes available (2,658 out of 6,128) 7,032.5 MiB of nars (compressed) 19,824.2 MiB on disk (uncompressed) 0.030 seconds per request (182.9 seconds in total) 33.5 requests per second 9.8% (342 out of 3,470) of the missing items are queued 867 queued builds x86_64-linux: 518 (59.7%) i686-linux: 221 (25.5%) aarch64-linux: 128 (14.8%) build rate: 23.41 builds per hour x86_64-linux: 11.16 builds per hour i686-linux: 6.03 builds per hour aarch64-linux: 6.41 builds per hour
As you can see, it reports the fraction of all the packages for which
substitutes are available on the server—regardless of whether substitutes
are enabled, and regardless of whether this server’s signing key is
authorized. It also reports the size of the compressed archives (“nars”)
provided by the server, the size the corresponding store items occupy in the
store (assuming deduplication is turned off), and the server’s throughput.
The second part gives continuous integration (CI) statistics, if the server
supports it. In addition, using the --coverage option,
guix weather
can list “important” package substitutes missing on
the server (see below).
To achieve that, guix weather
queries over HTTP(S) meta-data
(narinfos) for all the relevant store items. Like guix
challenge
, it ignores signatures on those substitutes, which is innocuous
since the command only gathers statistics and cannot install those
substitutes.
The general syntax is:
guix weather options… [packages…]
When packages is omitted, guix weather
checks the
availability of substitutes for all the packages, or for those
specified with --manifest; otherwise it only considers the
specified packages. It is also possible to query specific system types with
--system. guix weather
exits with a non-zero code when
the fraction of available substitutes is below 100%.
The available options are listed below.
--substitute-urls=urls
urls is the space-separated list of substitute server URLs to query.
When this option is omitted, the URLs specified with the
--substitute-urls option of guix-daemon
are used or, as a
last resort, the default set of substitute URLs.
--system=system
-s sistema
Query substitutes for system—e.g., aarch64-linux
. This
option can be repeated, in which case guix weather
will query
substitutes for several system types.
--manifest=arquivo
Instead of querying substitutes for all the packages, only ask for those
specified in file. file must contain a manifest, as with
the -m
option of guix package
(veja Invocando guix package
).
This option can be repeated several times, in which case the manifests are concatenated.
--expression=expr
-e expr
Consider the package expr evaluates to.
A typical use case for this option is specifying a package that is hidden and thus cannot be referred to in the usual way, as in this example:
guix weather -e '(@@ (gnu packages rust) rust-bootstrap)'
This option can be repeated.
--coverage[=contagem]
-c [contagem]
Report on substitute coverage for packages: list packages with at least count dependents (zero by default) for which substitutes are unavailable. Dependent packages themselves are not listed: if b depends on a and a has no substitutes, only a is listed, even though b usually lacks substitutes as well. The result looks like this:
$ guix weather --substitute-urls=https://bordeaux.guix.gnu.org https://ci.guix.gnu.org -c 10 computing 8,983 package derivations for x86_64-linux... looking for 9,343 store items on https://bordeaux.guix.gnu.org https://ci.guix.gnu.org... updating substitutes from 'https://bordeaux.guix.gnu.org https://ci.guix.gnu.org'... 100.0% https://bordeaux.guix.gnu.org https://ci.guix.gnu.org 64.7% substitutes available (6,047 out of 9,343) … 2502 packages are missing from 'https://bordeaux.guix.gnu.org https://ci.guix.gnu.org' for 'x86_64-linux', among which: 58 kcoreaddons@5.49.0 /gnu/store/…-kcoreaddons-5.49.0 46 qgpgme@1.11.1 /gnu/store/…-qgpgme-1.11.1 37 perl-http-cookiejar@0.008 /gnu/store/…-perl-http-cookiejar-0.008 …
What this example shows is that kcoreaddons
and presumably the 58
packages that depend on it have no substitutes at
bordeaux.guix.gnu.org
; likewise for qgpgme
and the 46
packages that depend on it.
If you are a Guix developer, or if you are taking care of this build farm, you’ll probably want to have a closer look at these packages: they may simply fail to build.
--display-missing
Display the list of store items for which substitutes are missing.
Anterior: Invocando guix weather
, Acima: Utilitários [Conteúdo][Índice]
guix processes
The guix processes
command can be useful to developers and system
administrators, especially on multi-user machines and on build farms: it
lists the current sessions (connections to the daemon), as well as
information about the processes involved27. Here’s an example of the information it
returns:
$ sudo guix processes SessionPID: 19002 ClientPID: 19090 ClientCommand: guix shell python SessionPID: 19402 ClientPID: 19367 ClientCommand: guix publish -u guix-publish -p 3000 -C 9 … SessionPID: 19444 ClientPID: 19419 ClientCommand: cuirass --cache-directory /var/cache/cuirass … LockHeld: /gnu/store/…-perl-ipc-cmd-0.96.lock LockHeld: /gnu/store/…-python-six-bootstrap-1.11.0.lock LockHeld: /gnu/store/…-libjpeg-turbo-2.0.0.lock ChildPID: 20495 ChildCommand: guix offload x86_64-linux 7200 1 28800 ChildPID: 27733 ChildCommand: guix offload x86_64-linux 7200 1 28800 ChildPID: 27793 ChildCommand: guix offload x86_64-linux 7200 1 28800
In this example we see that guix-daemon
has three clients:
guix shell
, guix publish
, and the Cuirass continuous
integration tool; their process identifier (PID) is given by the
ClientPID
field. The SessionPID
field gives the PID of the
guix-daemon
sub-process of this particular session.
The LockHeld
fields show which store items are currently locked by
this session, which corresponds to store items being built or substituted
(the LockHeld
field is not displayed when guix processes
is
not running as root). Last, by looking at the ChildPID
and
ChildCommand
fields, we understand that these three builds are being
offloaded (veja Usando o recurso de descarregamento).
The output is in Recutils format so we can use the handy recsel
command to select sessions of interest (veja Selection Expressions em GNU recutils manual). As an example, the command shows the
command line and PID of the client that triggered the build of a Perl
package:
$ sudo guix processes | \ recsel -p ClientPID,ClientCommand -e 'LockHeld ~ "perl"' ClientPID: 19419 ClientCommand: cuirass --cache-directory /var/cache/cuirass …
Additional options are listed below.
--format=format
-f format
Produce output in the specified format, one of:
recutils
The default option. It outputs a set of Session recutils records that
include each ChildProcess
as a field.
normalized
Normalize the output records into record sets (veja Record Sets em GNU recutils manual). Normalizing into record sets allows joins
across record types. The example below lists the PID of each
ChildProcess
and the associated PID for Session
that spawned
the ChildProcess
where the Session
was started using
guix build
.
$ guix processes --format=normalized | \ recsel \ -j Session \ -t ChildProcess \ -p Session.PID,PID \ -e 'Session.ClientCommand ~ "guix build"' PID: 4435 Session_PID: 4278 PID: 4554 Session_PID: 4278 PID: 4646 Session_PID: 4278
Próximo: Configuração do sistema, Anterior: Utilitários, Acima: GNU Guix [Conteúdo][Índice]
You can target computers of different CPU architectures when producing
packages (veja Invocando guix package
), packs (veja Invocando guix pack
)
or full systems (veja Invoking guix system
).
GNU Guix supports two distinct mechanisms to target foreign architectures:
Próximo: Native Builds, Acima: Foreign Architectures [Conteúdo][Índice]
The commands supporting cross-compilation are proposing the --list-targets and --target options.
The --list-targets option lists all the supported targets that can be passed as an argument to --target.
$ guix build --list-targets The available targets are: - aarch64-linux-gnu - arm-linux-gnueabihf - avr - i586-pc-gnu - i686-linux-gnu - i686-w64-mingw32 - mips64el-linux-gnu - or1k-elf - powerpc-linux-gnu - powerpc64le-linux-gnu - riscv64-linux-gnu - x86_64-linux-gnu - x86_64-linux-gnux32 - x86_64-w64-mingw32 - xtensa-ath9k-elf
Targets are specified as GNU triplets (veja GNU configuration triplets em Autoconf).
Those triplets are passed to GCC and the other underlying compilers possibly involved when building a package, a system image or any other GNU Guix output.
$ guix build --target=aarch64-linux-gnu hello /gnu/store/9926by9qrxa91ijkhw9ndgwp4bn24g9h-hello-2.12 $ file /gnu/store/9926by9qrxa91ijkhw9ndgwp4bn24g9h-hello-2.12/bin/hello /gnu/store/9926by9qrxa91ijkhw9ndgwp4bn24g9h-hello-2.12/bin/hello: ELF 64-bit LSB executable, ARM aarch64 …
The major benefit of cross-compilation is that there are no performance penalty compared to emulation using QEMU. There are however higher risks that some packages fail to cross-compile because fewer users are using this mechanism extensively.
Anterior: Cross-Compilation, Acima: Foreign Architectures [Conteúdo][Índice]
The commands that support impersonating a specific system have the --list-systems and --system options.
The --list-systems option lists all the supported systems that can be passed as an argument to --system.
$ guix build --list-systems The available systems are: - x86_64-linux [current] - aarch64-linux - armhf-linux - i586-gnu - i686-linux - mips64el-linux - powerpc-linux - powerpc64le-linux - riscv64-linux $ guix build --system=i686-linux hello /gnu/store/cc0km35s8x2z4pmwkrqqjx46i8b1i3gm-hello-2.12 $ file /gnu/store/cc0km35s8x2z4pmwkrqqjx46i8b1i3gm-hello-2.12/bin/hello /gnu/store/cc0km35s8x2z4pmwkrqqjx46i8b1i3gm-hello-2.12/bin/hello: ELF 32-bit LSB executable, Intel 80386 …
In the above example, the current system is x86_64-linux. The hello package is however built for the i686-linux system.
This is possible because the i686 CPU instruction set is a subset of the x86_64, hence i686 targeting binaries can be run on x86_64.
Still in the context of the previous example, if picking the
aarch64-linux system and the guix build
--system=aarch64-linux hello
has to build some derivations, an extra step
might be needed.
The aarch64-linux targeting binaries cannot directly be run on a x86_64-linux system. An emulation layer is requested. The GNU Guix daemon can take advantage of the Linux kernel binfmt_misc mechanism for that. In short, the Linux kernel can defer the execution of a binary targeting a foreign platform, here aarch64-linux, to a userspace program, usually an emulator.
There is a service that registers QEMU as a backend for the
binfmt_misc
mechanism (veja qemu-binfmt-service-type
). On Debian based foreign distributions,
the alternative would be the qemu-user-static
package.
If the binfmt_misc
mechanism is not setup correctly, the building
will fail this way:
$ guix build --system=armhf-linux hello --check … unsupported-platform /gnu/store/jjn969pijv7hff62025yxpfmc8zy0aq0-hello-2.12.drv aarch64-linux while setting up the build environment: a `aarch64-linux' is required to build `/gnu/store/jjn969pijv7hff62025yxpfmc8zy0aq0-hello-2.12.drv', but I am a `x86_64-linux'…
whereas, with the binfmt_misc
mechanism correctly linked with QEMU,
one can expect to see:
$ guix build --system=armhf-linux hello --check /gnu/store/13xz4nghg39wpymivlwghy08yzj97hlj-hello-2.12
The main advantage of native building compared to cross-compiling, is that more packages are likely to build correctly. However it comes at a price: compilation backed by QEMU is way slower than cross-compilation, because every instruction needs to be emulated.
The availability of substitutes for the architecture targeted by the
--system
option can mitigate this problem. An other way to work
around it is to install GNU Guix on a machine whose CPU supports the
targeted instruction set, and set it up as an offload machine (veja Usando o recurso de descarregamento).
Próximo: System Troubleshooting Tips, Anterior: Foreign Architectures, Acima: GNU Guix [Conteúdo][Índice]
Guix System supports a consistent whole-system configuration mechanism. By that we mean that all aspects of the global system configuration—such as the available system services, timezone and locale settings, user accounts—are declared in a single place. Such a system configuration can be instantiated—i.e., effected.
One of the advantages of putting all the system configuration under the control of Guix is that it supports transactional system upgrades, and makes it possible to roll back to a previous system instantiation, should something go wrong with the new one (veja Recursos). Another advantage is that it makes it easy to replicate the exact same configuration across different machines, or at different points in time, without having to resort to additional administration tools layered on top of the own tools of the system.
This section describes this mechanism. First we focus on the system administrator’s viewpoint—explaining how the system is configured and instantiated. Then we show how this mechanism can be extended, for instance to support new system services.
operating-system
Referenceguix system
guix deploy
Próximo: Usando o sistema de configuração, Acima: Configuração do sistema [Conteúdo][Índice]
You’re reading this section probably because you have just installed Guix
System (veja Instalação do sistema) and would like to know where to go from
here. If you’re already familiar with GNU/Linux system administration, the
way Guix System is configured is very different from what you’re used to:
you won’t install a system service by running guix install
, you
won’t configure services by modifying files under /etc, and you won’t
create user accounts by invoking useradd
; instead, all these
aspects are spelled out in a system configuration file.
The first step with Guix System is thus to write the system configuration file; luckily, system installation already generated one for you and stored it under /etc/config.scm.
Nota: You can store your system configuration file anywhere you like—it doesn’t have to be at /etc/config.scm. It’s a good idea to keep it under version control, for instance in a