guix build
guix edit
guix download
guix hash
guix import
guix refresh
guix lint
guix size
guix graph
guix publish
guix challenge
guix copy
guix container
guix weather
guix processes
operating-system
Referenceguix system
guix deploy
这份文档介绍GNU Guix版本1.3.0,一个为GNU系统编写的函数式包管理器。
This manual is also available in Simplified Chinese (see GNU Guix参考手册), French (see Manuel de référence de GNU Guix), German (see Referenzhandbuch zu GNU Guix), Spanish (see Manual de referencia de GNU Guix), and Russian (see Руководство GNU Guix). If you would like to translate it in your native language, consider joining Weblate.
• 介绍 | Guix是关于什么的? | |
• 安装 | 安装Guix。 | |
• 系统安装 | 安装整个操作系统。 | |
• 入门 | Your first steps. | |
• 软件包管理 | 软件包安装、升级等。 | |
• 通道 | 定制软件包集合。 | |
• 开发 | Guix辅助的软件开发。 | |
• 编程接口 | 在Scheme里使用Guix。 | |
• 工具 | 软件包管理命令。 | |
• 系统配置 | 配置操作系统。 | |
• 文档 | 浏览软件用户手册。 | |
• 安装调试文件 | 为调试工具提供输入。 | |
• 安全更新 | 快速部署安全补丁。 | |
• 引导 | 从头开始构建GNU/Linux。 | |
• 移植 | 以别的平台或内核为目标。 | |
• 贡献 | 你需要帮助! | |
• 致谢 | 感谢! | |
• GNU自由文档许可证 | 这个用户手册的许可证。 | |
• 概念索引 | 概念。 | |
• 编程索引 | 数据类型、函数和变量。 | |
---详细的章节列表--- 介绍 | ||
• 以Guix的方式管理软件 | 特殊的地方。 | |
• GNU发行版 | 软件包和工具。 | |
安装 | ||
• 二进制文件安装 | 立刻运行Guix! | |
• 需求 | 构建和运行Guix需要的软件。 | |
• 运行测试套件 | 测试Guix。 | |
• 设置后台进程 | 准备“构建后台进程”的环境。 | |
• 调用guix-daemon | 运行“构建后台进程” | |
• 设置应用程序 | 应用程序相关的设置。 | |
• Upgrading Guix | 升级 Guix 及其构建守护进程。 | |
设置后台进程 | ||
• 设置构建环境 | 准备隔离的构建环境。 | |
• 下发工作给后台进程的设置 | 下发构建工作给远程的机器。 | |
• SELinux的支持 | 为后台进程使用SELinux规则。 | |
系统安装 | ||
• 限制 | 你可以期待什么。 | |
• 硬件的考虑 | 支持的硬件。 | |
• U盘和DVD安装 | 准备安装介质。 | |
• 准备安装 | 网络、分区等。 | |
• 指导的图形安装 | 简单的图形安装。 | |
• 手动安装 | 适合巫师的手动安装。 | |
• 系统安装之后 | 当安装成功后。 | |
• 在虚拟机里安装 Guix | Guix系统游乐场。 | |
• 构建安装镜像 | 这是怎样实现的。 | |
手动安装 | ||
• 键盘布局、网络和分区 | 初始设置。 | |
• 继续安装步骤 | 安装。 | |
软件包管理 | ||
• 功能 | Guix怎样让你的生活更美好。 | |
• 调用guix package | 软件包安装,移除等。 | |
• substitutes | 下载构建好的二进制文件。 | |
• 有多个输出的软件包 | 单个输入多个输出的软件包。 | |
• 调用guix gc | 运行垃圾回收器。 | |
• 调用guix pull | 获取最新的Guix和发行版。 | |
• Invoking guix time-machine | Running an older revision of Guix. | |
• Inferiors | 和其它版本的Guix交互。 | |
• 调用guix describe | 显示你的Guix版本信息。 | |
• 调用guix archive | 导出和导入仓库文件。 | |
substitutes | ||
• 官方的substitute服务器 | substitute的一个特殊来源。 | |
• 授权substitute服务器。 | 怎么开启或关闭substitute。 | |
• Getting Substitutes from Other Servers | Substitute diversity. | |
• 验证substitute | Guix怎样验证substitute。 | |
• 代理设置 | 怎样通过代理获取substitute。 | |
• substitute失败 | 当substitute失败时会发生什么。 | |
• 关于信任二进制文件 | 你怎么能信任二进制的 blob 呢? | |
通道 | ||
• Specifying Additional Channels | 拓展软件包集合。 | |
• Using a Custom Guix Channel | Using a customized Guix. | |
• Replicating Guix | Running the exact same Guix. | |
• Channel Authentication | How Guix verifies what it fetches. | |
• Channels with Substitutes | Using channels with available substitutes. | |
• 创建一个频道 | How to write your custom channel. | |
• Package Modules in a Sub-directory | Specifying the channel’s package modules location. | |
• Declaring Channel Dependencies | How to depend on other channels. | |
• Specifying Channel Authorizations | Defining channel authors authorizations. | |
• Primary URL | Distinguishing mirror to original. | |
• Writing Channel News | Communicating information to channel’s users. | |
开发 | ||
• 调用guix environment | 设置开发环境。 | |
• 调用guix pack | 创建软件bundle。 | |
• The GCC toolchain | Working with languages supported by GCC. | |
• Invoking guix git authenticate | Authenticating Git repositories. | |
编程接口 | ||
• 软件包模块 | 从程序员的角度看软件包。 | |
• 定义软件包 | 定义新软件包。 | |
• Defining Package Variants | Customizing packages. | |
• 构建系统 | 指定如何构建软件包。 | |
• Build Phases | Phases of the build process of a package. | |
• Build Utilities | Helpers for your package definitions and more. | |
• 仓库 | 操纵软件包仓库。 | |
• Derivations | 软件包derivation的底层接口。 | |
• 仓库monad | 仓库的纯函数式接口。 | |
• G-表达式 | 操纵构建表达式。 | |
• 调用guix repl | Programming Guix in Guile. | |
定义软件包 | ||
• 软件包引用 | 软件包数据类型。 | |
• origin参考手册 | origin数据类型。 | |
工具 | ||
• 调用guix build | 用命令行构建软件包。 | |
• 调用guix edit。 | 编辑软件包定义。 | |
• 调用guix download | 下载一个文件并打印它的hash。 | |
• 调用guix hash | 计算一个文件的密码学hash。 | |
• 调用guix import | 导入软件包定义。 | |
• 调用guix refresh | 更新软件包定义。 | |
• 调用guix lint | 从软件包定义里寻找错误。 | |
• 调用guix size | 分析硬盘使用情况。 | |
• 调用guix graph | 展示软件包的关系图。 | |
• 调用guix publish | 分享substitute。 | |
• 调用guix challenge | 挑战subtitute服务器。 | |
• 调用guix copy | 复制到远程的仓库,或从远程的仓库复制。 | |
• 调用guix container | 进程隔离。 | |
• 调用guix weather | 评估substitute的可用性。 | |
• 调用guix processes | 列出客户端进程。 | |
调用 | ||
• 普通的构建选项 | 大部分命令的构建选项。 | |
• 软件包变换选项。 | 创建软件包的变体。 | |
• 额外的构建选项 | 只属于’guix build’的选项。 | |
• 调试构建错误 | 真实的打包经验。 | |
系统配置 | ||
• 使用配置系统 | 定制你的GNU系统。 | |
• 操作系统参考 | 操作系统声明详情。 | |
• 文件系统 | 设置文件系统挂载。 | |
• 映射的设备 | 块设备额外的处理。 | |
• 用户帐号 | 指定用户帐号。 | |
• 键盘布局 | 系统怎样理解按键。 | |
• 区域 | 语言和文化惯例设置。 | |
• 服务 | 指定系统服务。 | |
• setuid程序 | 以root权限运行的程序。 | |
• X.509证书 | 认证HTTPS服务器。 | |
• Name Service Switch | 设置libc的name service switch。 | |
• 初始的内存虚拟硬盘 | Linux-Libre引导。 | |
• 引导设置 | 设置引导程序。 | |
• 调用guix system | 实例化一个系统配置。 | |
• 调用 guix deploy | Deploying a system configuration to a remote host. | |
• 在虚拟机里运行Guix | 怎样在虚拟机里运行Guix。 | |
• 定义服务 | 添加新的服务定义。 | |
服务 | ||
• 基础服务 | 必要的系统服务。 | |
• 执行计划任务 | mcron服务。 | |
• 日志轮替 | rottlog服务。 | |
• 网络服务 | 网络设置,SSH后台进程,等 | |
• Unattended Upgrades | Automated system upgrades. | |
• X窗口 | 图形显示器。 | |
• 打印服务 | 本地和远程打印机的支持。 | |
• 桌面服务 | D-Bus和桌面服务。 | |
• 声音服务 | ALSA和Pulseaudio服务。 | |
• 数据库服务 | SQL数据库,键值仓库,等 | |
• 邮件服务 | IMAP,POP3,SMTP,等 | |
• 消息服务 | 消息服务。 | |
• 电话服务 | 电话服务。 | |
• 监控服务 | 监控服务。 | |
• Kerberos服务 | Kerberos服务。 | |
• LDAP Services | LDAP services. | |
• Web服务 | Web服务。 | |
• 证书服务 | Let’s Encrypt TLS证书。 | |
• DNS服务 | DNS后台进程。 | |
• VPN服务 | VPN后台进程。 | |
• 网络文件系统 | 网络文件系统相关的服务。 | |
• 持续集成 | Cuirass and Laminar services. | |
• 电源管理服务 | 延长电池寿命。 | |
• 音频服务 | MPD。 | |
• 虚拟化服务 | 虚拟化服务。 | |
• 版本控制服务 | 远程访问Git仓库。 | |
• 游戏服务 | 游戏服务器。 | |
• PAM Mount Service | Service to mount volumes when logging in. | |
• Guix Services | Services relating specifically to Guix. | |
• Linux Services | Services tied to the Linux kernel. | |
• Hurd Services | Services specific for a Hurd System. | |
• 其它各种服务 | 其它服务。 | |
定义服务 | ||
• 合成服务 | 服务合成的模型。 | |
• 服务类型和服务 | 类型和服务。 | |
• 服务参考 | API参考。 | |
• Shepherd服务 | 一种特别的服务。 | |
安装调试文件 | ||
• Separate Debug Info | Installing ’debug’ outputs. | |
• Rebuilding Debug Info | Building missing debug info. | |
引导 | ||
• Reduced Binary Seed Bootstrap | A Bootstrap worthy of GNU. | |
• Preparing to Use the Bootstrap Binaries | Building that what matters most. | |
GNU Guix1是GNU系统的包管理器和发行版。Guix让无特权的用户可以轻松地安装,升级,或删除软件包,回滚到前一个软件包集合,从源代码构建软件包,及辅助软件环境的创建和维护。
你可以在现有的GNU/Linux发行版上安装GNU Guix(see 安装),Guix可以补充已有的工具,并且不会和它们产生冲突。或者你可以把它当作独立的操作系统发行版(Guix 系统2)。See GNU发行版.
• 以Guix的方式管理软件 | 特殊的地方。 | |
• GNU发行版 | 软件包和工具。 |
Guix provides a command-line package management interface (see 软件包管理), tools to help with software development (see 开发), command-line utilities for more advanced usage (see 工具), as well as Scheme programming interfaces (see 编程接口). 构建后台进程为用户构建软件包(see 设置后台进程),及从授权的源(see substitutes)下载预构建的二进制文件。
Guix包含很多GNU和非GNU的软件包定义,所有的这些软件包都尊重用户的自由。它是可扩展的:用户可以编写自己的软件包定义(see 定义软件包),并且把它们作为独立的软件包模块see 软件包模块。它也是可定制的:用户可以从现有的软件包定义衍生出特殊的软件包,包括从命令行(see 软件包变换选项。)。
在底层,Guix实现了由Nix(see 致谢)开创的函数式包管理器。在Guix里,软件包构建和安装过程被视为数学意义上的函数。函数获取输入,如构建脚本、编译器和库,并且返回一个安装好的软件包。作为一个纯函数,它的结果只取决于它的输入--例如,它不能引用没有作为显式输入传入的软件和脚本。当传入特定的输入时,一个构建函数总是得到相同的结果。它不能以任何方式修改运行系统的环境,例如,它不能创建,修改,或删除构建和安装环境之外的文件夹。这是通过在隔离的环境(容器)里运行构建进程实现的,在这个环境里只能访问到显式的输入。
软件包构建函数的结果被缓存在文件系统里的一个叫做仓库(see 仓库)的特殊文件夹内。每个软件包都被安装在仓库(默认在/gnu/store)里的一个独立的文件夹内。这个文件夹的名字含有用于构建这个软件包的所有输入的hash,所以,修改输入会得到一个不同的文件夹名。
这种手段是实现Guix的突出功能的基础:对事务型软件包升级和回滚的支持,每个用户独立的安装,软件包垃圾回收see 功能。
Previous: 以Guix的方式管理软件, Up: 介绍 [Contents][Index]
Guix提供了一个GNU系统发行版,这个发新版只包含自由软件3。这个发行版可以独立安装(see 系统安装),但是把Guix安装为一个已经安装好的GNU/Linux系统的包管理器也是可行的(see 安装)。当我们需要区分这两者时,我们把独立的发行版称为“Guix系统”。
这个发行版提供了GNU核心软件包,如libc、gcc和Binutils,以及很多GNU和非GNU应用程序。可用的软件包的完整列表可以在on-line浏览,或者通过运行guix
package
(see 调用guix package)获得:
guix package --list-available
我们的目标是提供一个基于Linux和其它GNU变体的可用的100%自由的软件发行版,我们的重点是推广和紧密集成GNU组件,以及强调帮助用户行使那些自由的程序和工具。
目前这些平台提供软件包:
x86_64-linux
Intel/AMD x86_64
架构,Linux-Libre 内核。
i686-linux
Intel 32 位架构(IA32),Linux-Libre 内核。
armhf-linux
ARMv7-A架构,带硬件浮点数、Thumb-2和NEON扩展,EABI硬件浮点数应用二进制接口(ABI),和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
(see hurd-vm-service-type
).
See 贡献, on how to help!
mips64el-linux (deprecated)
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.
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 (see substitutes), and some packages may fail to build (see Tracking Bugs and Patches). That said, the Guix community is actively working on improving this support, and now is a great time to try it and get involved!
在Guix系统里,你声明操作系统所有方面的配置,然后Guix以事务型的,可重复的,和无状态的方式解决实例化配置的问题(see 系统配置)。Guix系统使用Linux-Libre内核,Shepherd初始化系统see 介绍 in GNU Shepherd用户手册,知名的GNU工具和工具链,以及你可选的图形界面环境和系统服务。
Guix System is available on all the above platforms except
mips64el-linux
and powerpc64le-linux
.
关于移植到其它架构或内核的信息,see 移植。
构建这个发行版需要努力合作,欢迎你加入!关于你可以怎样提供帮助的信息,See 贡献。
注: 我们推荐使用shell安装脚本在已有的GNU/Linux系统(即foreign distro)上安装Guix。4这个脚本自动下载、安装并且初始化Guix,它需要以root用户身份运行。
在foreign distro上安装时,GNU Guix可以在不引起冲突的前提下补充现有的工具。它的数据只存放在两个文件夹里,通常是/gnu/store和/var/guix;系统上的其它文件,如/etc,不会被修改。
一旦安装好了,可以通过运行guix pull
升级Guix(see 调用guix pull)。
如果你希望手动执行安装步骤,或者想改变安装步骤,接下来这些小节会很有用。它们介绍Guix的软件依赖,以及如何手动安装和使用Guix。
• 二进制文件安装 | 立刻运行Guix! | |
• 需求 | 构建和运行Guix需要的软件。 | |
• 运行测试套件 | 测试Guix。 | |
• 设置后台进程 | 准备“构建后台进程”的环境。 | |
• 调用guix-daemon | 运行“构建后台进程” | |
• 设置应用程序 | 应用程序相关的设置。 | |
• Upgrading Guix | 升级 Guix 及其构建守护进程。 |
这个小节介绍如何在任意的系统上用独立的Guix二进制文件包安装Guix和它的依赖。这通常比从源代码安装更快,下一小节会介绍如何从源代码安装。唯一的需求是有GNU tar和Xz。
注: We recommend the use of this shell installer script. The script automates the download, installation, and initial configuration steps described below. It should be run as the root user. As root, you can thus run this:
cd /tmp wget https://git.savannah.gnu.org/cgit/guix.git/plain/etc/guix-install.sh chmod +x guix-install.sh ./guix-install.shWhen you’re done, see 设置应用程序 for extra configuration you might need, and 入门 for your first steps!
安装步骤如下:
https://ftp.gnu.org/gnu/guix/guix-binary-1.3.0.x86_64-linux.tar.xz
’,
where x86_64-linux
can be replaced with i686-linux
for an
i686
(32-bits) machine already running the kernel Linux, and so on
(see GNU发行版).
请确保下载相关的.sig文件,并且用它验证文件包的可靠性,方法如下:
$ wget https://ftp.gnu.org/gnu/guix/guix-binary-1.3.0.x86_64-linux.tar.xz.sig $ gpg --verify guix-binary-1.3.0.x86_64-linux.tar.xz.sig
如果那个命令因为缺少所需的公钥而失败了,那么用这个命令导入它:
$ wget 'https://sv.gnu.org/people/viewgpg.php?user_id=127547' \ -qO - | gpg --import -
再次运行gpg --verify
命令。
Take note that a warning like “This key is not certified with a trusted signature!” is normal.
root
用户。基于你的发行版,你可能需要执行su -
或sudo
-i
。以root
用户身份,执行:
# cd /tmp # tar --warning=no-timestamp -xf \ /path/to/guix-binary-1.3.0.x86_64-linux.tar.xz # mv var/guix /var/ && mv gnu /
This creates /gnu/store (see 仓库) and /var/guix.
The latter contains a ready-to-use profile for root
(see next step).
不要在一个正常的Guix系统上解压这个文件包,因为那会把现有的重要的文件覆盖。
The --warning=no-timestamp option makes sure GNU tar does not emit warnings about “implausibly old time stamps” (such warnings were triggered by GNU tar 1.26 and older; recent versions are fine). They stem from the fact that all the files in the archive have their modification time set to 1 (which means January 1st, 1970). This is done on purpose to make sure the archive content is independent of its creation time, thus making it reproducible.
guix
pull
安装更新的位置(see 调用guix pull):
# mkdir -p ~root/.config/guix # ln -sf /var/guix/profiles/per-user/root/current-guix \ ~root/.config/guix/current
Source etc/profile to augment PATH
and other relevant
environment variables:
# GUIX_PROFILE="`echo ~root`/.config/guix/current" ; \ source $GUIX_PROFILE/etc/profile
如果你的主机的发行版使用systemd init系统,可以用这些命令:
# cp ~root/.config/guix/current/lib/systemd/system/gnu-store.mount \ ~root/.config/guix/current/lib/systemd/system/guix-daemon.service \ /etc/systemd/system/ # systemctl enable --now gnu-store.mount guix-daemon
如果你的主机的发行版使用Upstart init系统:
# initctl reload-configuration # cp ~root/.config/guix/current/lib/upstart/system/guix-daemon.conf \ /etc/init/ # start guix-daemon
此外,你可以手动启动后台进程:
# ~root/.config/guix/current/bin/guix-daemon \ --build-users-group=guixbuild
guix
命令:
# mkdir -p /usr/local/bin # cd /usr/local/bin # ln -s /var/guix/profiles/per-user/root/current-guix/bin/guix
最好让这个用户手册的Info版也可以被访问:
# mkdir -p /usr/local/share/info # cd /usr/local/share/info # for i in /var/guix/profiles/per-user/root/current-guix/share/info/* ; do ln -s $i ; done
That way, assuming /usr/local/share/info is in the search path,
running info guix
will open this manual (see Other Info Directories in GNU Texinfo, for more details on changing the Info
search path).
ci.guix.gnu.org
或其镜像的substitute(see substitutes),对其授权:
# guix archive --authorize < \ ~root/.config/guix/current/share/guix/ci.guix.gnu.org.pub
瞧,安装完成了!
你可以通过给root profile安装一个软件包来确认Guix可以正常工作。
# guix install hello
二进制安装包可以通过在Guix源代码树里运行下面这些命令来重现和验证:
make guix-binary.系统.tar.xz
... 这个命令会执行:
guix pack -s 系统 --localstatedir \ --profile-name=current-guix guix
See 调用guix pack,了解这个方便的工具。
这个小节列举了从源代码构建Guix的需求。构建Guix的步骤和其它GNU软件相同,这里不介绍。请阅读Guix源代码树里的README和INSTALL文件以了解更多的信息。
GNU Guix可以从它的网站下载https://www.gnu.org/software/guix/。
GNU Guix依赖这些软件包:
这些依赖是可选的:
guix copy
(see 调用guix copy) depends on
Guile-SSH, version
0.13.0 or later.
guix publish
and for substitutes
(see 调用guix publish).
crate
importer (see 调用guix import).
go
importer (see 调用guix import) and for some of the
“updaters” (see 调用guix refresh).
guix-daemon
可以用它压缩构建日志。
Unless --disable-daemon was passed to configure
, the
following packages are also needed:
When configuring Guix on a system that already has a Guix installation, be
sure to specify the same state directory as the existing installation using
the --localstatedir option of the configure
script
(see localstatedir
in GNU Coding
Standards). Usually, this localstatedir option is set to the value
/var. The configure
script protects against unintended
misconfiguration of localstatedir so you do not inadvertently corrupt
your store (see 仓库).
成功执行configure
和make
之后,最好运行测试套件。它可以帮助查找设置和环境的错误,或者是Guix自身的bug--并且,报告测试错误是帮助改进软件的好方法。输入下面的命令以执行测试套件。
make check
测试用例可以并行运行:你可以用GNU make的-j
参数来加速运行。才一台较新的机器上第一次运行可能会花几分钟,后续的运行会更快,因为为测试创建的仓库已经包含了各种缓存。
你还可以通过定义makefile的TESTS
变量只运行测试的一个子集:
make check TESTS="tests/store.scm tests/cpio.scm"
默认情况下,测试结果只展示到文件层级。为了看每个独立的测试用例的详情,可以像这样定义SCM_LOG_DRIVER_FLAGS
makefile变量:
make check TESTS="tests/base64.scm" SCM_LOG_DRIVER_FLAGS="--brief=no"
The underlying SRFI 64 custom Automake test driver used for the ’check’ test suite (located at build-aux/test-driver.scm) also allows selecting which test cases to run at a finer level, via its --select and --exclude options. Here’s an example, to run all the test cases from the tests/packages.scm test file whose names start with “transaction-upgrade-entry”:
export SCM_LOG_DRIVER_FLAGS="--select=^transaction-upgrade-entry" make check TESTS="tests/packages.scm"
Those wishing to inspect the results of failed tests directly from the
command line can add the --errors-only=yes option to the
SCM_LOG_DRIVER_FLAGS
makefile variable and set the VERBOSE
Automake makefile variable, as in:
make check SCM_LOG_DRIVER_FLAGS="--brief=no --errors-only=yes" VERBOSE=1
The --show-duration=yes option can be used to print the duration of the individual test cases, when used in combination with --brief=no:
make check SCM_LOG_DRIVER_FLAGS="--brief=no --show-duration=yes"
See Parallel Test Harness in GNU Automake for more information about the Automake Parallel Test Harness.
遇到错误时,请给bug-guix@gnu.org发邮件,并附带test-suite.log文件。请在消息里说明使用的Guix的版本信息和依赖(see 需求)的版本信息。
Guix还附带了一个可以测试整个Guix系统实例的全系统测试套件。它只能在已经安装Guix的系统上运行:
make check-system
或者,同样的,通过定义TESTS
只运行测试的一个子集:
make check-system TESTS="basic mcron"
这些系统测试是在(gnu tests
…)
模块里定义的。它们在虚拟机(VM)里运行轻量的指令。它们的计算量可能很多也可能很少,这取决于它们依赖的substitute(see substitutes)是否已经存在。它们之中有些需要很多存储空间以保存虚拟机硬盘。
再重复一遍,如果遇到测试错误,请给bug-guix@gnu.org发邮件,并附带详细的说明。
Next: 调用guix-daemon, Previous: 运行测试套件, Up: 安装 [Contents][Index]
构建软件包或运行垃圾回收器之类的操作都是由一个特殊的进程代替客户执行的,即构建后台进程。只有这个进程可以访问仓库和相关的数据库。因此,所有修改仓库的操作都通过这个后台进程执行。例如,guix
package
和guix build
之类的命令行工具通过和这个后台进程通信(通过远程过程调用)来指示它该做什么。
接下来的几个小节介绍如何准备“构建后台进程”的环境。参考substitutes,了解怎样允许这个后台进程下载预构建好的二进制文件。
• 设置构建环境 | 准备隔离的构建环境。 | |
• 下发工作给后台进程的设置 | 下发构建工作给远程的机器。 | |
• SELinux的支持 | 为后台进程使用SELinux规则。 |
Next: 下发工作给后台进程的设置, Up: 设置后台进程 [Contents][Index]
在一个标准的多用户设置里,Guix和它的后台进程–guix-daemon
程序–是由root
用户安装的,并且guix-daemon
以root
用户身份运行。无特权的用户可以用Guix的工具构建软件包或访问仓库,这个后台进程会代替用户进行这些操作,以确保仓库保持一致的状态,并且允许构建好的软件包可以在不同用户间共享。
当guix-daemon
以root
用户身份运行时,由于安全方面的考虑,你可能不希望软件包构建进程也以root
用户身份运行。为了避免那样,我们需要创建一个构建用户池,以供后台进程启动的构建进程使用。这些构建用户不需要拥有shell和家目录:他们只会在后台进程为构建进程剥夺root
特权时使用。拥有多个这类用户使后台进程可以以不同的UID启动不同的构建进程,这保证它们不会互相干扰–这是一个重要的功能,因为构建被视为纯函数(see 介绍)。
在一个GNU/Linux系统上,可以这样创建一个构建用户池(用bash语法和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
构建用户的数量决定了有多少个构建任务可以并行执行,即--max-jobs参数(see --max-jobs)。为了使用guix system
vm
和相关的命令,你需要把构建用户添加到kvm
用户组,以使它们访问/dev/kvm。为此,把-G
guixbuild
替换成-G guixbuild,kvm
(see 调用guix system)。
之后以root
身份用下面的命令运行guix-daemon
程序command5:
# guix-daemon --build-users-group=guixbuild
这样,后台进程在一个chroot环境里,以一个guixbuilder
用户组成员的身份启动构建进程。在GNU/Linux上,默认的,这个chroot环境仅包含这些东西:
/dev
独立的6,最小的/dev
文件夹;
/proc
文件夹;它只含有当前容器的进程,因为用了一个独立的进程PID命名空间;
localhost
映射到127.0.0.1
的条目;
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 (see Derivations) or for substitutes
(see substitutes).
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.
Next: SELinux的支持, Previous: 设置构建环境, Up: 设置后台进程 [Contents][Index]
When desired, the build daemon can offload derivation builds to other
machines running Guix, using the offload
build
hook7.
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 (see 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.
/etc/guix/machines.scm文件通常是这样的:
(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")
(private-key
(string-append (getenv "HOME")
"/.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.
事实上,这个文件–并不意外地–是一个Scheme文件,当下发
钩子被启动时执行。它的返回值必须是一个包含build-machine
对象的列表。虽然这个例子展示的是一个固定的列表,你可以想象,使用DNS-SD来返回一个包含从局域网内发现的构建机器的列表,see Guile-Avahi in 在Guile
Scheme程序里使用Avahi。build-machine
数据类型的详细信息如下。
这个数据类型表示后台进程可以下发构建任务的构建机器。重要的项有:
名字
远程机器的主机名。
systems
The system types the remote machine supports—e.g., (list
"x86_64-linux" "i686-linux")
.
用户
通过SSH连接远程机器时使用的用户帐号。注意,SSH密钥不能被密码保护,以支持无交互的登录。
主机公钥
这必须是机器的OpenSSH格式的SSH公钥。这是用来在连接机器时认证身份的。它是一个像这样的长字符串:
ssh-ed25519 AAAAC3NzaC…mde+UhL hint@example.org
如果这个机器正在运行OpenSSH后台进程,sshd
,那么主机公钥可以在/etc/ssh/ssh_host_ed25519_key.pub找到。
如果这个机器正在运行GNU lsh,lshd
,那么主机公钥可以在/etc/lsh/host-key.pub或类似的位置找到。它可以通过lsh-export-key
命令转换成OpenSSH格式(see Converting keys in LSH用户手册):
$ lsh-export-key --openssh < /etc/lsh/host-key.pub ssh-rsa AAAAB3NzaC1yc2EAAAAEOp8FoQAAAQEAs1eB46LV…
一些可选的项:
port
(默认值:22
)机器上的SSH服务器的端口号。
private-key
(默认值:~root/.ssh/id_rsa)连接机器时使用的SSH私钥,OpenSSH格式。这个私钥不能被密码保护。
注意,默认值是root帐号的私钥。使用默认值时请确保它存在。
compression
(默认值:"zlib@openssh.com,zlib"
)compression-level
(默认值:3
)SSH压缩算法和压缩级别。
下发任务依赖SSH压缩来减少传输文件到构建机器时使用的带宽。
daemon-socket
(默认值:"/var/guix/daemon-socket/socket"
)那台机器上的guix-daemon
监听的Unix套接字文件名。
overload-threshold
(default: 0.6
)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
(默认值:1
)那台机器上可以并行运行的构建任务数量。
speed
(默认值:1.0
)一个相对的速度值。下发调度器会偏好速度更快的机器。
features
('()
)一个表示机器支持的功能的字符串列表。例如,"kvm"
表示机器有KVM
Linux模块和相关的硬件支持。Derivation可以通过名字请求需要的功能,然后被分发到匹配的机器的任务队列里。
guix
命令必须在构建机器的搜素路径里。你可以通过这个命令检查:
ssh build-machine guix repl --version
machines.scm到位后,还有一件要做的事。如上所述,下发任务时会在机器的仓库之间传输文件。为此,你需要在每台机器上生成一个密钥对,以使后台进程可以从仓库导出签名后的文件包(see 调用guix archive):
# guix archive --generate-key
每台构建机器都必须认证主机器的公钥,从而接收从主机器接收的仓库文件:
# guix archive --authorize < master-public-key.txt
类似的,主机器必须认证每台构建机器的公钥:
所有这些有关公钥的繁琐事宜都是为了表达主服务器和构建服务器之间成对的互相信任关系。具体地,当主机器从构建机器接收文件时(反之亦然),它的构建后台进程可以确保文件是原样的,没有被篡改,并且被认证的公钥签名过。
为了测试你的设置是否能正常工作,在主节点上运行这个命令:
# 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.
如果你希望用别的文件测试,只需要在命令行指定它:
# guix offload test machines-qualif.scm
最后,你可以像这样只测试机器列表里名字匹配某个正则表达式的子集:
# guix offload test machines.scm '\.gnu\.org$'
若想展示所有构建主机的当前负载,在主节点上运行这个命令:
# guix offload status
Previous: 下发工作给后台进程的设置, Up: 设置后台进程 [Contents][Index]
Guix附带一个SELinux策略文件,位置在etc/guix-daemon.cil,它可以在启用SELinux的系统上安装,为Guix的文件添加标签及指定后台进程的期望行为。由于Guix系统不提供SELinux基础策略,这个后台进程策略不能在Guix系统上使用。
用root用户执行这个命令以安装策略:
semodule -i etc/guix-daemon.cil
用restorecon
或者你的系统提供的其它机制重新给文件系统打标签。
一旦安装好策略,为文件系统重新打好标签,并且重启了后台进程,它应该在guix_daemon_t
环境里运行。你可以用下面这个命令确认:
ps -Zax | grep guix-daemon
运行guix build hello
之类的命令并监控SELinux日志以说服你自己SELinux允许所有的操作。
这个策略不是完美的。这里有一个关于限制和缺陷的列表,当为Guix后台进程部署提供的SELinux策略时该认真考虑。
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
不可以任意访问指向profile的链接。由于设计的原因,符号链接的目标的文件标签和符号链接本身的文件标签是不同的。尽管$localstatedir里的所有profile都被打上了标签,指向这些profile的符号链接继承它们所在的文件夹的标签。对于普通用户的家目录里的链接,标签是user_home_t
。但是对于root用户的家目录,或/tmp,或HTTP服务器的工作目录等文件夹里的链接不是这样。guix
gc
会被阻止读取和跟随这些链接。
/gnu/store/.+-(guix-.+|profile)/bin/guix-daemon
的文件都被赋予guix_daemon_exec_t
标签;这意味着任何profile里的任何有这样名字的的文件都会被允许在guix_daemon_t
域里执行。这不够理想。一个攻击者可以构建提供这个可执行程序的软件包,并说服一个用户安装、运行它,以此进入guix_daemon_t
域。那时,SELinux无法阻止它访问所在域的进程可以访问的文件。
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.
我们可以在安装时生成一个更严格的策略,仅当前安装的guix-daemon
的精确的的文件名会被打上guix_daemon_exec_t
标签,而不是用一个宽泛的正则表达式。这样的缺点是root必须在每次安装提供guix-daemon
的Guix软件包时安装或升级策略。
guix-daemon
guix-daemon
程序实现了所有访问仓库的功能。包括启动构建进程,运行垃圾回收器,查询构建结果,等。它通常以root
身份运行:
# guix-daemon --build-users-group=guixbuild
关于如何设置它,see 设置后台进程。
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 (see 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 (see 功能).
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 (see --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.
See 调用guix processes, for more information.
下面这些命令行选项受支持:
--build-users-group=用户组
这会从用户组里选取用户,以运行构建进程(see 构建用户)。
--no-substitutes
不要为构建商品使用substitute。即,总是在本地构建,而不是下载预构建的二进制文件(see substitutes)。
When the daemon runs with --no-substitutes, clients can still
explicitly enable substitution via the set-build-options
remote
procedure call (see 仓库).
--substitute-urls=urls
urls是用空格分隔的substitute源URL列表。当这个选项被省略时,默认使用‘https://ci.guix.gnu.org
’。
这意味着可以从urls下载substitute,只要它们的签名可信(see substitutes)。
See 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 (see 下发工作给后台进程的设置). That is, always build things locally instead of offloading builds to remote machines.
--cache-failures
缓存失败的构建。默认地,只缓存成功的构建。
当这个选项被使用时,可以用guix gc --list-failures
查询被标记为失败的仓库文件;guix gc
--clear-failures
从仓库里删除失败的缓存。See 调用guix gc。
--cores=n
-c n
用n个CPU核来构建每个derivation;0
表示有多少就用多少。
The default value is 0
, but it may be overridden by clients, such as
the --cores option of guix build
(see 调用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
最多允许n个并行的构建任务。默认值是1
。设置为0
表示不在本地执行构建;而是下发构建任务(see 下发工作给后台进程的设置),或者直接失败。
--max-silent-time=seconds
当构建或substitution进程超过seconds秒仍然保持静默,就把它结束掉并报告构建失败。
默认值是0
,表示关闭超时。
The value specified here can be overridden by clients (see --max-silent-time).
--timeout=seconds
类似地,当构建或substitution进程执行超过seconds秒,就把它结束掉并报告构建失败。
默认值是0
,表示关闭超时。
The value specified here can be overridden by clients (see --timeout).
--rounds=N
为每个derivation构建n次,如果连续的构建结果不是每个比特都相同就报告错误。这个设置可以被guix
build
之类的客户端覆盖(see 调用guix build)。
当和--keep-failed一起使用时,不同的输出保存在/gnu/store/…-check。这让检查两个结果的区别更容易。
--debug
生成调试输出。
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
(see 调用guix build).
--chroot-directory=dir
把dir添加到构建的chroot。
这么做可能会改变构建进程的结果–例如,如果它们使用了在dir里发现的可选依赖。因此,建议不要这么做,而是确保每个derivation声明所需的全部输入。
--disable-chroot
关闭chroot构建。
不建议使用这个选项,因为它会允许构建进程访问到没被声明的依赖。但是,当guix-daemon
以没有特权的用户身份运行时,这个选项是必须的。
--log-compression=type
以type方式压缩构建日志,可选的值:gzip
,bzip2
,none
。
Unless --lose-logs is used, all the build logs are kept in the localstatedir. To save space, the daemon automatically compresses them with Bzip2 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
关闭自动对仓库文件“去重”。
默认地,添加到仓库的文件会被自动“去重”:如果新添加的文件和仓库里找到的某个文件完全相同,后台进程把这个新文件变成另一个文件的硬链接。这可以明显地减少硬盘使用,代价是构建结束后轻微地增加输入/输出负载。这个选项关闭这个优化。
--gc-keep-outputs[=yes|no]
垃圾收集器(GC)是否必须保留存活的derivation的输出。
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. See 调用guix gc, for more on GC roots.
--gc-keep-derivations[=yes|no]
垃圾收集器(GC)是否必须保留和存活的输出相关的derivation。
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.
这可能会有助于构建那些(通常是错误地)依赖内核版本号的程序。
--lose-logs
Do not keep build logs. By default they are kept under localstatedir/guix/log.
--system=system
假设system是当前的系统类型。默认值是configure时发现的架构/内核元组,如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 (see GUIX_DAEMON_SOCKET
).
注: 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.
Next: Upgrading Guix, Previous: 调用guix-daemon, Up: 安装 [Contents][Index]
When using Guix on top of GNU/Linux distribution other than Guix System—a so-called foreign distro—a few additional steps are needed to get everything in place. Here are some of them.
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 917 MiB.
Alternatively, the glibc-utf8-locales
is smaller but limited to a few
UTF-8 locales.
The GUIX_LOCPATH
variable plays a role similar to LOCPATH
(see LOCPATH
in 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.
When using Guix on a foreign distro, we strongly recommend that the
system run the GNU C library’s name service cache daemon,
nscd
, which should be listening on the /var/run/nscd/socket
socket. Failing to do that, applications installed with Guix may fail to
look up host names or user accounts, or may even crash. The next paragraphs
explain why.
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 (see Name Service Switch in 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 (see NSS Configuration File in 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
gs-fonts
, 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 (see 有多个输出的软件包). 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.
When using Guix on a foreign distro, you can install this package and define the relevant environment variables so that packages know where to look for certificates. See X.509证书, for detailed information.
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. 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 (see Init File in The GNU Emacs Manual).
To upgrade Guix, run:
guix pull
See 调用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
(see guix system reconfigure
).
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, see 安装.
• 限制 | 你可以期待什么。 | |
• 硬件的考虑 | 支持的硬件。 | |
• U盘和DVD安装 | 准备安装介质。 | |
• 准备安装 | 网络、分区等。 | |
• 指导的图形安装 | 简单的图形安装。 | |
• 手动安装 | 适合巫师的手动安装。 | |
• 系统安装之后 | 当安装成功后。 | |
• 在虚拟机里安装 Guix | Guix系统游乐场。 | |
• 构建安装镜像 | 这是怎样实现的。 |
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.
Nevertheless, before you proceed with the installation, be aware of the following noteworthy limitations applicable to version 1.3.0:
More than a disclaimer, this is an invitation to report issues (and success stories!), and to join us in improving it. See 贡献, for more info.
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
(see firmware
).
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.
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-1.3.0.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-1.3.0.系统.iso.sig $ gpg --verify guix-system-install-1.3.0.系统.iso.sig
如果那个命令因为缺少所需的公钥而失败了,那么用这个命令导入它:
$ wget https://sv.gnu.org/people/viewgpg.php?user_id=127547 \ -qO - | gpg --import -
再次运行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-1.3.0.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-1.3.0.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
.
See 在虚拟机里安装 Guix, if, instead, you would like to install Guix System in a virtual machine (VM).
Once you have booted, you can use the guided graphical installer, which makes it easy to get started (see 指导的图形安装). 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 (see 手动安装).
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 (see 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.
注: Installation requires access to the Internet so that any missing dependencies of your system configuration can be downloaded. See the “Networking” section below.
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 (see 使用配置系统). At that point you can hit “OK” and installation will proceed. On success, you can reboot into the new system and enjoy. See 系统安装之后, for what’s next!
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 (see 指导的图形安装).
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 it is also a full-blown
Guix System, which means that you can install additional packages, should
you need it, using guix package
(see 调用guix package).
• 键盘布局、网络和分区 | 初始设置。 | |
• 继续安装步骤 | 安装。 |
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.
安装镜像使用的是美国的 qwerty 键盘布局,如果想更改,可以使用 loadkeys
命令。 例如,用以下命令选择 Dvorak
键盘布局:
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.
运行以下命令查看你的网络接口的名称:
ifconfig -a
… 或者,使用 GNU/Linux 特有的 ip
命令:
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
… 或者,使用 GNU/Linux 特有的 ip
命令:
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
(see Overview in 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 (see BIOS installation in 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
注: 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
. See 引导设置, 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)8. 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 (see deduplication).
Preferably, assign file systems a label so that you can easily and reliably
refer to them in file-system
declarations (see 文件系统).
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 would be along
these lines:
cryptsetup luksFormat /dev/sda2 cryptsetup open --type luks /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 (see swap space in The GNU C Library Reference Manual), 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 run9:
# 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.
Previous: 键盘布局、网络和分区, Up: 手动安装 [Contents][Index]
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 (see GNU nano
Manual), which supports syntax highlighting and parentheses matching; other
editors include GNU Zile (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.
See 使用配置系统, 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 target 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 target
field names a
device, like /dev/sda
; for UEFI systems it names a path to a mounted
EFI partition, like /boot/efi
; do make sure the path is 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 (see 映射的设备).
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, see 调用guix system. This command may trigger downloads or builds of missing packages, which can take some time.
Once that command has completed—and hopefully succeeded!—you can run
reboot
and boot into the new system. The root
password in
the new system is initially empty; other users’ passwords need to be
initialized by running the passwd
command as root
, unless
your configuration specifies otherwise (see user
account passwords). See 系统安装之后, for what’s next!
Next: 在虚拟机里安装 Guix, Previous: 手动安装, Up: 系统安装 [Contents][Index]
Success, you’ve now booted into Guix System! From then on, you can update the system whenever you want by running, say:
guix pull sudo guix system reconfigure /etc/config.scm
This builds a new system generation with the latest packages and services (see 调用guix system). We recommend doing that regularly so that your system includes the latest security updates (see 安全更新).
注: Note that
sudo guix
runs your user’sguix
command and not root’s, becausesudo
leavesPATH
unchanged. To explicitly run root’sguix
, typesudo -i guix …
.The difference matters here, because
guix pull
updates theguix
command and package definitions only for the user it is run as. This means that if you choose to useguix system reconfigure
in root’s login shell, you’ll need toguix pull
separately.
Now, see 入门, and join us on #guix
on the Libera Chat
IRC network or on guix-devel@gnu.org to share your experience!
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,file=guix-system-install-1.3.0.system.iso
-enable-kvm
is optional, but significantly improves performance,
see 在虚拟机里运行Guix.
Once installation is complete, you can boot the system that’s on your guix-system.img image. See 在虚拟机里运行Guix, for how to do that.
Previous: 在虚拟机里安装 Guix, Up: 系统安装 [Contents][Index]
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 调用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.
Presumably, you’ve reached this section because either you have installed Guix on top of another distribution (see 安装), or you’ve installed the standalone Guix System (see 系统安装). 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 (see substitutes, 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,
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
现在你知道包管理的基本知识了吧!
Going further: See 软件包管理, 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, see 开发 for additional tools. And if you’re curious, see 功能, to peek under the hood.
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.
Going further: See 调用guix pull, for more information. See 通道, on how to specify additional channels to pull packages from, how to replicate Guix, and more. You may also find
time-machine
handy (see Invoking guix 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. When you eventually reboot, you’ll notice a sub-menu in the bootloader that reads “Old system generations”: it’s what allows you to boot an older generation of your system, should the latest generation be “broken” or otherwise unsatisfying. Just like for packages, you can always roll back to a previous generation of the whole system:
sudo guix system roll-back
There are many things you’ll probably want to tweak on your system: adding new user accounts, adding new system services, fiddling with the configuration of those services, etc. The system configuration is entirely described in the /etc/config.scm file. See 使用配置系统, to learn how to change it.
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:
- See 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.
- See 文档, 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 (see guix package
), you
may also use the Emacs-Guix interface (see 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怎样让你的生活更美好。 | |
• 调用guix package | 软件包安装,移除等。 | |
• substitutes | 下载构建好的二进制文件。 | |
• 有多个输出的软件包 | 单个输入多个输出的软件包。 | |
• 调用guix gc | 运行垃圾回收器。 | |
• 调用guix pull | 获取最新的Guix和发行版。 | |
• Invoking guix time-machine | Running an older revision of Guix. | |
• Inferiors | 和其它版本的Guix交互。 | |
• 调用guix describe | 显示你的Guix版本信息。 | |
• 调用guix archive | 导出和导入仓库文件。 |
Next: 调用guix package, Up: 软件包管理 [Contents][Index]
Here we assume you’ve already made your first steps with Guix (see 入门) 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
(see 调用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 (see 使用配置系统).
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 (see 调用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 (see 介绍). 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 (see 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 (see substitutes). 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 (see 调用guix challenge).
Control over the build environment is a feature that is also useful for
developers. The guix environment
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 (see 调用guix environment).
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 (see 调用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.
Next: substitutes, Previous: 功能, Up: 软件包管理 [Contents][Index]
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 (see 功能). Its
syntax is:
guix package options
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 (see --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 (see Bash Startup Files in 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
(see 调用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 either a simple package name, such as
guile
, or a package name followed by an at-sign and version number,
such as guile@1.8.8
or simply guile@1.8
(in the latter case,
the newest version prefixed by 1.8
is selected).
If no version number is specified, the newest available version will be
selected. In addition, package 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
(see 有多个输出的软件包).
Packages with a corresponding name (and optionally version) are searched for
among the GNU distribution modules (see 软件包模块).
Sometimes packages have propagated inputs: these are dependencies that
automatically get installed along with the required package
(see 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
base) 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 file
Install the package that the code within file evaluates to.
As an example, file might contain a definition like this (see 定义软件包):
(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 (see 调用guix environment).
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": "https://example.com/greeter-1.0.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 package …
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
(see 调用guix pull).
When upgrading, package transformations that were originally applied when creating the profile are automatically re-applied (see 软件包变换选项。). 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=file
-m file
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 ;; Use a specific package output. (list guile-2.0 "debug")))
In this example we have to know which modules define the emacs
and
guile-2.0
variables to provide the right use-package-modules
line, which can be cumbersome. We can instead provide regular package
specifications and let specifications->manifest
look up the
corresponding package objects, like this:
(specifications->manifest
'("emacs" "guile@2.2" "guile@2.2:debug"))
See --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=pattern
-S pattern
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[=kind]
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 (see Environment Variables in 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.
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=profile
-p profile
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 (see GNU recutils databases in 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
See Selection Expressions in 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 (see GNU recutils databases in GNU recutils manual).
$ guix package --show=python | recsel -p name,version name: python version: 2.7.6 name: python version: 3.3.5
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 python@3.4 | recsel -p name,version name: python version: 3.4.3
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 (see 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 (see 有多个输出的软件包), 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 (see 有多个输出的软件包), 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
(see 通道).
Together with --export-manifest, this option provides information allowing you to replicate the current profile (see 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 (see Inferiors).
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 (see 普通的构建选项). It
also supports package transformation options, such as
--with-source, and preserves them across upgrades (see 软件包变换选项。).
Next: 有多个输出的软件包, Previous: 调用guix package, Up: 软件包管理 [Contents][Index]
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 (see Derivations). 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.
• 官方的substitute服务器 | substitute的一个特殊来源。 | |
• 授权substitute服务器。 | 怎么开启或关闭substitute。 | |
• Getting Substitutes from Other Servers | Substitute diversity. | |
• 验证substitute | Guix怎样验证substitute。 | |
• 代理设置 | 怎样通过代理获取substitute。 | |
• substitute失败 | 当substitute失败时会发生什么。 | |
• 关于信任二进制文件 | 你怎么能信任二进制的 blob 呢? |
Next: 授权substitute服务器。, Up: substitutes [Contents][Index]
The ci.guix.gnu.org
server is a front-end to an official
build farm that builds packages from Guix continuously for some
architectures, and makes them available as substitutes. This is the default
source of substitutes; it can be overridden by passing the
--substitute-urls option either to guix-daemon
(see guix-daemon --substitute-urls
) or
to client tools such as guix package
(see 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 farm are enabled by default when using Guix System (see 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 (see 安装). 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.
Next: Getting Substitutes from Other Servers, Previous: 官方的substitute服务器, Up: substitutes [Contents][Index]
To allow Guix to download substitutes from ci.guix.gnu.org
or a mirror thereof, you must add its public key to the access control list
(ACL) of archive imports, using the guix archive
command
(see 调用guix archive). Doing so implies that you trust
ci.guix.gnu.org
to not be compromised and to serve genuine
substitutes.
注: If you are using Guix System, you can skip this section: Guix System authorizes substitutes from
ci.guix.gnu.org
by default.
The public key for ci.guix.gnu.org
is installed along with
Guix, in prefix/share/guix/ci.guix.gnu.org.pub
, where
prefix is the installation prefix of Guix. If you installed Guix from
source, make sure you checked the GPG signature of
guix-1.3.0.tar.gz, which contains this public key file.
Then, you can run something like this:
# 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
ci.guix.gnu.org
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 (see 调用guix-daemon). It can also be disabled temporarily by passing the
--no-substitutes option to guix package
, guix
build
, and other command-line tools.
Next: 验证substitute, Previous: 授权substitute服务器。, Up: substitutes [Contents][Index]
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 (see 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 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 (see guix-daemon --substitute-urls
):
… --substitute-urls='https://guix.example.org https://ci.guix.gnu.org'
systemctl daemon-reload systemctl restart guix-daemon.service
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 ci.guix.gnu.org
as a
fallback. 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.
Note that there are also situations where one may want to add the URL of a substitute server without authorizing its key. See 验证substitute, to understand this fine point.
Next: 代理设置, Previous: Getting Substitutes from Other Servers, Up: substitutes [Contents][Index]
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).
Next: substitute失败, Previous: 验证substitute, Up: substitutes [Contents][Index]
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.
Next: 关于信任二进制文件, Previous: 代理设置, Up: substitutes [Contents][Index]
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 (see 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 (see 调用guix weather).
This command provides statistics on the substitutes provided by a server.
Previous: substitute失败, Up: substitutes [Contents][Index]
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 ci.guix.gnu.org
substitutes can be convenient, we
encourage users to also build on their own, or even run their own build
farm, such that ci.guix.gnu.org
is 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 (see 调用guix publish).
Guix has the foundations to maximize build reproducibility
(see 功能). 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 (see 调用guix challenge).
Similarly, the --check option of guix build
allows users
to check whether previously-installed substitutes are genuine by rebuilding
them locally (see 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.
Next: 调用guix gc, Previous: substitutes, Up: 软件包管理 [Contents][Index]
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
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 (see 调用guix size). guix
graph
can also be helpful (see 调用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 (see 安装调试文件). The outputs
of a packages are listed in the third column of the output of guix
package --list-available
(see 调用guix package).
Next: 调用guix pull, Previous: 有多个输出的软件包, Up: 软件包管理 [Contents][Index]
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 (see 调用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
(see 调用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
(see 执行计划任务, 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 (see size specifications in 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[=duration]
-d [duration]
Before starting the garbage collection process, delete all the generations older than duration, for all the user profiles; 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 (see --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.
See 调用guix size, for a tool to profile the size of the closure of an element. See 调用guix graph, for a tool to visualize the graph of references.
--derivers
Return the derivation(s) leading to the given store items (see Derivations).
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 (see substitutes). 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
(see 调用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 (see --disable-deduplication). Thus, this option is primarily useful when the daemon was running with --disable-deduplication.
Next: Invoking guix time-machine, Previous: 调用guix gc, Up: 软件包管理 [Contents][Index]
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
(see 通道) specified by one of the followings, in this order:
%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. Thus, make sure
to add it to the beginning of your search path so that you use the latest
version, and similarly for the Info manual (see 文档):
export PATH="$HOME/.config/guix/current/bin:$PATH" export INFOPATH="$HOME/.config/guix/current/share/info:$INFOPATH"
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 2 new packages: keepalived, libnfnetlink 6 packages upgraded: emacs-nix-mode@2.0.4, guile2.0-guix@0.14.0-12.77a1aac, guix@0.14.0-12.77a1aac, heimdal@7.5.0, milkytracker@1.02.00, nix@2.0.4 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 28 new packages: emacs-helm-ls-git, emacs-helm-mu, … 69 packages upgraded: borg@1.1.6, cheese@3.28.0, …
See 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
(see 调用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
(see 调用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=branch
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 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 file
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. See 通道, for more information.
--news
-N
Display the list of packages added or upgraded since the previous generation, as well as, occasionally, news written by channel authors for their users (see Writing Channel News).
The package information is the same as displayed upon guix pull
completion, but without ellipses; it is also similar to the output of
guix pull -l
for the last generation (see below).
--list-generations[=pattern]
-l [pattern]
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
(see 调用guix package).
--roll-back
Roll back to the previous generation of ~/.config/guix/current—i.e., undo the last transaction.
--switch-generation=pattern
-S pattern
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.
See 调用guix describe, for a way to display information about the current generation only.
--profile=profile
-p profile
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.
注: 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.
注: Make sure you understand its security implications before using --disable-authentication.
--system=system
-s system
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.
See 通道, for more information.
In addition, guix pull
supports all the common build options
(see 普通的构建选项).
Next: Inferiors, Previous: 调用guix pull, Up: 软件包管理 [Contents][Index]
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
(see 调用guix describe).
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
(see 调用guix pull):
--url=url
--commit=commit
--branch=branch
Use the guix
channel from the specified url, at the given
commit (a valid Git commit ID represented as a hexadecimal string), or
branch.
--channels=file
-C file
Read the list of channels from file. file must contain Scheme code that evaluates to a list of channel objects. See 通道 for more information.
As for guix pull
, the absence of any options means that the latest
commit on the master branch will be used. The command
guix time-machine -- build hello
will thus build the package hello
as defined in the master branch,
which is in general a newer revision of Guix than you have installed. Time
travel works in both directions!
Note that guix time-machine
can trigger builds of channels and
their dependencies, and these are controlled by the standard build options
(see 普通的构建选项).
Next: 调用guix describe, Previous: Invoking guix time-machine, Up: 软件包管理 [Contents][Index]
注: The functionality described here is a “technology preview” as of version 1.3.0. 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 (see 调用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 (see 通道), 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
(see 调用guix package); 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:
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.
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.
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 (see 软件包引用). 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 (see G-表达式). They are also
transparently handled by the packages->manifest
procedure, which is
commonly used in manifests (see 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.
Next: 调用guix archive, Previous: Inferiors, Up: 软件包管理 [Contents][Index]
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 (see 通道):
$ 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 (see 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 (see 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 (see 调用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 (see 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=profile
-p profile
Display information about profile.
Previous: 调用guix describe, Up: 软件包管理 [Contents][Index]
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.
注: If you’re looking for a way to produce archives in a format suitable for tools other than Guix, see 调用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
(see 调用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 (see 普通的构建选项).
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 (see 调用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 (see gcry_pk_genkey
in The Libgcrypt
Reference Manual).
--authorize
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 (see substitutes) 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 ci.guix.gnu.org
to /tmp/emacs:
$ wget -O - \ https://ci.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 (see 调用guix challenge).
--list
-t
Read a single-item archive as served by substitute servers (see substitutes) and print the list of files it contains, as in this example:
$ wget -O - \ https://ci.guix.gnu.org/nar/lzip/…-emacs-26.3 \ | lzip -d | guix archive -t
Guix and its package collection are updated by running guix pull
(see 调用guix pull). By default guix pull
downloads and
deploys Guix itself from the official GNU Guix repository. This can be
customized by defining channels in the
~/.config/guix/channels.scm file. A channel specifies a 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.
• Specifying Additional Channels | 拓展软件包集合。 | |
• Using a Custom Guix Channel | Using a customized Guix. | |
• Replicating Guix | Running the exact same Guix. | |
• Channel Authentication | How Guix verifies what it fetches. | |
• Channels with Substitutes | Using channels with available substitutes. | |
• 创建一个频道 | How to write your custom channel. | |
• Package Modules in a Sub-directory | Specifying the channel’s package modules location. | |
• Declaring Channel Dependencies | How to depend on other channels. | |
• Specifying Channel Authorizations | Defining channel authors authorizations. | |
• Primary URL | Distinguishing mirror to original. | |
• Writing Channel News | Communicating information to channel’s users. |
Next: Using a Custom Guix Channel, Up: 通道 [Contents][Index]
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 (see cons
and lists in 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 pull --list-generations … 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 11 new packages: variant-gimp, variant-emacs-with-cool-features, … 4 packages upgraded: emacs-racket-mode@0.0.2-2.1b78827, …
The output of guix pull
above shows that Generation 19
includes both Guix and packages from the variant-personal-packages
channel. Among the new and upgraded packages that are listed, some like
variant-gimp
and variant-emacs-with-cool-features
might come
from variant-packages
, while others come from the Guix default
channel.
Next: Replicating Guix, Previous: Specifying Additional Channels, Up: 通道 [Contents][Index]
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 ((see Channel Authentication).
Next: Channel Authentication, Previous: Using a Custom Guix Channel, Up: 通道 [Contents][Index]
The guix pull --list-generations
output above shows precisely
which commits were used to build this instance of Guix. We can thus
replicate it, say, on another machine, by providing a channel specification
in ~/.config/guix/channels.scm that is “pinned” to these commits:
;; 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")))
The guix describe --format=channels
command can even generate this
list of channels directly (see 调用guix describe). The resulting
file can be used with the -C options of guix pull
(see 调用guix pull) or guix time-machine
(see Invoking guix time-machine).
At this point the two machines run the exact same Guix, with access
to the exact same packages. The output of guix build gimp
on one machine will be exactly the same, bit for bit, as the output of the
same command on the other machine. It also means both machines have access
to all the source code of Guix and, transitively, to all the source code of
every package it defines.
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. See Inferiors, for another way to take advantage of these super powers.
Next: Channels with Substitutes, Previous: Replicating Guix, Up: 通道 [Contents][Index]
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!
Next: 创建一个频道, Previous: Channel Authentication, Up: 通道 [Contents][Index]
When running guix pull
, Guix will first compile the definitions of
every available package. This is an expensive operation for which
substitutes (see substitutes) 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.
Next: Package Modules in a Sub-directory, Previous: Channels with Substitutes, Up: 通道 [Contents][Index]
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. You would first write modules containing those package definitions (see 软件包模块), maintain them in a Git repository, and then you and anyone else can use it as an additional channel to get packages from. Neat, no?
Warning: Before you, dear user, shout—“woow this is soooo coool!”—and publish your personal channel to the world, we would like to share a few words of caution:
- Before publishing a channel, please consider contributing your package definitions to Guix proper (see 贡献). 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.
- When you maintain package definitions outside Guix, we, Guix developers, consider that the compatibility burden is on you. Remember that package modules and package definitions are just Scheme code that uses various programming interfaces (APIs). We want to remain free to change these APIs to keep improving Guix, possibly in ways that break your channel. We never change APIs gratuitously, but we will not commit to freezing APIs either.
- 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.
To create a channel, create a Git repository containing your own package
modules and make it available. The repository can contain anything, but a
useful channel will contain Guile modules that export packages. Once you
start using a channel, Guix will behave as if the root directory of that
channel’s Git repository has been added to the Guile load path (see Load Paths in GNU Guile Reference Manual). For example, if your channel
contains a file at my-packages/my-tools.scm that defines a Guile
module, then the module will be available under the name (my-packages
my-tools)
, and you will be able to use it like any other module
(see 模块 in GNU Guile Reference Manual).
As a channel author, consider bundling authentication material with your channel so that users can authenticate it. See Channel Authentication, and Specifying Channel Authorizations, for info on how to do it.
Next: Declaring Channel Dependencies, Previous: 创建一个频道, Up: 通道 [Contents][Index]
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"))
Next: Specifying Channel Authorizations, Previous: Package Modules in a Sub-directory, Up: 通道 [Contents][Index]
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.
Next: Primary URL, Previous: Declaring Channel Dependencies, Up: 通道 [Contents][Index]
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)10 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.
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. See 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.
Next: Writing Channel News, Previous: Specifying Channel Authorizations, Up: 通道 [Contents][Index]
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.
Previous: Primary URL, Up: 通道 [Contents][Index]
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 (see Overview in 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
(see xgettext Invocation in 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.
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 environment
command provides a convenient way to set up
development environments containing all the dependencies and tools
necessary to work on the software package of your choice. The guix
pack
command allows you to create application bundles that can be
easily distributed to users who do not run Guix.
• 调用guix environment | 设置开发环境。 | |
• 调用guix pack | 创建软件bundle。 | |
• The GCC toolchain | Working with languages supported by GCC. | |
• Invoking guix git authenticate | Authenticating Git repositories. |
Next: 调用guix pack, Up: 开发 [Contents][Index]
guix environment
The purpose of guix environment
is to assist hackers in creating
reproducible development environments without polluting their package
profile. The guix environment
tool takes one or more packages,
builds all of their inputs, and creates a shell environment to use them.
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 option11.
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 (see 调用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 (see Bash Startup Files in 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 2.7 and NumPy:
guix environment --ad-hoc python2-numpy python-2.7 -- python
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
注: 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.
--root=file
-r file
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. See 调用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=file
-l file
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 (see 定义软件包):
(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 `(("autoconf" ,autoconf-2.64) ("automake" ,automake) ("texinfo" ,texinfo) ,@(package-native-inputs gdb))))
--manifest=file
-m file
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
(see --manifest) and uses the same manifest
files.
--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
(see 有多个输出的软件包).
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.
--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 system
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;12 --link-profile allows these programs to behave as expected within the environment.
--user=user
-u user
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=source[=target]
--share=source[=target]
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
guix environment
also supports all of the common build options
that guix build
supports (see 普通的构建选项) as well as
package transformation options (see 软件包变换选项。).
Next: The GCC toolchain, Previous: 调用guix environment, Up: 开发 [Contents][Index]
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.
注: If you are looking for ways to exchange binaries among machines that already run Guix, see 调用guix copy, 调用guix publish, and 调用guix 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 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 (see 二进制文件安装).
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 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 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 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. 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.
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.
注: 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.
--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 twice13, 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.
注: 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
--expression=expr
-e expr
Consider the package expr evaluates to.
This has the same purpose as the same-named option in guix build
(see --expression in guix
build
).
--manifest=file
-m file
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
(see --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.
--system=system
-s system
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"
(see GNU
configuration triplets in 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 (see 通道).
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=file
-r file
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 (see 仓库) as well as garbage-collector roots (see 调用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 (see 二进制文件安装).
--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
(see 普通的构建选项) and all the package transformation options
(see 软件包变换选项。).
Next: Invoking guix git authenticate, Previous: 调用guix pack, Up: 开发 [Contents][Index]
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’ (see Invoking guix package).
Previous: The GCC toolchain, Up: 开发 [Contents][Index]
guix git authenticate
The guix git authenticate
command authenticates a Git checkout
following the same rule as for channels (see 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” (see channel introduction). The options 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
.
--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 (see .guix-authorizations format).
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.
• 软件包模块 | 从程序员的角度看软件包。 | |
• 定义软件包 | 定义新软件包。 | |
• Defining Package Variants | Customizing packages. | |
• 构建系统 | 指定如何构建软件包。 | |
• Build Phases | Phases of the build process of a package. | |
• Build Utilities | Helpers for your package definitions and more. | |
• 仓库 | 操纵软件包仓库。 | |
• Derivations | 软件包derivation的底层接口。 | |
• 仓库monad | 仓库的纯函数式接口。 | |
• G-表达式 | 操纵构建表达式。 | |
• 调用guix repl | Programming Guix in Guile |
From a programming viewpoint, the package definitions of the GNU
distribution are provided by Guile modules in the (gnu packages
…)
name space14
(see Guile modules in GNU Guile Reference Manual). For
instance, the (gnu packages emacs)
module exports a variable named
emacs
, which is bound to a <package>
object (see 定义软件包).
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)
15. There are two ways to make these package definitions visible to
the user interfaces:
-L
flag of guix package
and other commands
(see 普通的构建选项), 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. See 通道, 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, see 引导.
Next: Defining Package Variants, Previous: 软件包模块, Up: 编程接口 [Contents][Index]
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 `(("gawk" ,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 (see Scheme records in 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 (see 调用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 (see 软件包模块).
There are a few points worth noting in the above package definition:
source
field of the package is an <origin>
object
(see origin参考手册, 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
(see 调用guix download) and guix hash
(see 调用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
(see 构建系统). 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. See Build Utilities, for more on this.
arguments
field specifies options for the build system
(see 构建系统). 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
.
See quoting in 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
(see apply
in GNU Guile Reference Manual).
The hash-colon (#:
) sequence defines a Scheme keyword
(see Keywords in GNU Guile Reference Manual), and
#:configure-flags
is a keyword used to pass a keyword argument to the
build system (see Coding With Keywords in 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 define an
input called "gawk"
whose value is that of the gawk
variable;
gawk
is itself bound to a <package>
object.
Again, `
(a backquote, synonymous with quasiquote
) allows us
to introduce a literal list in the inputs
field, while ,
(a
comma, synonymous with unquote
) allows us to insert a value in that
list (see unquote in GNU Guile Reference
Manual).
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 (see 构建系统).
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.
See 软件包引用, for a full description of possible fields.
Once a package definition is in place, the package may actually be built
using the guix build
command-line tool (see 调用guix build),
troubleshooting any build failures you encounter (see 调试构建错误). You can easily jump back to the package definition using the
guix edit
command (see 调用guix edit。). See 打包指导, for more information on how to test package definitions, and
调用guix lint, for information on how to check a definition for
style conformance.
Lastly, see 通道, 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 (see 调用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 (see 仓库).
Return the <derivation>
object of package for system
(see Derivations).
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 (see 仓库).
Similarly, it is possible to compute a derivation that cross-builds a package for some other system:
<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"
(see Specifying Target Triplets in Autoconf).
Once you have package definitions, you can easily define variants of those packages. See Defining Package Variants, for more on that.
• 软件包引用 | 软件包数据类型。 | |
• origin参考手册 | origin数据类型。 |
Next: origin参考手册, Up: 定义软件包 [Contents][Index]
package
ReferenceThis section summarizes all the options available in package
declarations (see 定义软件包).
This is the data type representing a package recipe.
名字
The name of the package, as a string.
version
The version of the package, as a string.
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 (see origin参考手册). It can also be any
other “file-like” object such as a local-file
, which denotes a file
from the local file system (see local-file
).
build-system
The build system that should be used to build the package (see 构建系统).
arguments
(default: '()
)The arguments that should be passed to the build system. This is a list, typically containing sequential keyword-value pairs.
inputs
(default: '()
)native-inputs
(default: '()
)propagated-inputs
(default: '()
)These fields list dependencies of the package. Each one is 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"
(see 有多个输出的软件包, for more
on package outputs). For example, the list below specifies three inputs:
`(("libffi" ,libffi) ("libunistring" ,libunistring) ("glib:bin" ,glib "bin")) ;the "bin" output of Glib
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
(see 调用guix lint).
Lastly, propagated-inputs
is similar to inputs
, but the
specified packages will be automatically installed to profiles
(see the role of profiles in Guix) alongside the package they
belong to (see 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. See 有多个输出的软件包, 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.
replacement
(default: #f
)This must be either #f
or a package object that will be used as a
replacement for this package. See grafts, for
details.
synopsis
A one-line description of the package.
description
A more elaborate description of the package.
license
The license of the package; a value from (guix licenses)
, or a list
of such values.
home-page
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)
`(("self" ,this-package))
'())))
It is an error to refer to this-package
outside a package definition.
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. 构建系统, for more on build systems.
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 (see 定义软件包). 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 (see 仓库monad);
most methods return a fixed-output derivation (see Derivations).
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
The content-hash
object of the source—see below for how to use
content-hash
.
You can obtain this information using guix download
(see 调用guix download) or guix hash
(see 调用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 (see 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 (see 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.
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 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, either the full SHA1 commit or a “short” commit string; the latter is not recommended) or the tag to fetch.
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.
<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 #false
.
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 (see 软件包变换选项。). This section describes how to define package variants in code. This can be useful in “manifests” (see --manifest) and in your own package collection (see 创建一个频道), 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 (see 软件包引用). 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-source package
transformation option does. 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' (srfi srfi-1)) ;for 'alist-delete' (define gdb-sans-guile (package (inherit gdb) (inputs (alist-delete "guile" (package-inputs gdb)))))
The alist-delete
call above removes the tuple from the inputs
field that has "guile"
as its first element (see SRFI-1 Association Lists in GNU Guile Reference Manual).
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 `(("lua" ,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.
See Procedures in 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 (see 软件包模块).
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 (see 软件包变换选项。):
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.
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 (see --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.
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.
Next: Build Phases, Previous: Defining Package Variants, Up: 编程接口 [Contents][Index]
Each package definition specifies a build system and arguments for
that build system (see 定义软件包). 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 (see Derivations). The package-with-c-toolchain
is an
example of a way to change the implicit inputs that a package’s build system
pulls in (see package-with-c-toolchain
).
Build systems accept an optional list of arguments. In package
definitions, these are passed via the arguments
field
(see 定义软件包). They are typically keyword arguments
(see keyword arguments in Guile in 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
(see Derivations).
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 (see configuration and makefile conventions in 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. See 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. See Build Phases, for more information.
#:configure-flags
This is a list of flags (strings) passed to the configure
script.
See 定义软件包, 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 (see --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.
This validation step consists in making sure that all the shared libraries
needed by an ELF binaries, 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. See -rpath in The GNU Linker, for more information on
RUNPATH
.
#:substitutable?
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 (see substitutes).
#: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 (see 调用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 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 (see 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.
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.
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.
check
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.
install
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 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 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.
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
(see Compilation in 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 is read from the file Project.toml. This
value can be overridden by passing the argument #:julia-package-name
(which must be correctly capitalized).
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 (see 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-apache") "\")\n"))))
;; There's a Julia file for each platform, override them all.
(find-files "src/wrappers/" "\\.jl$"))))
Some older packages that aren’t using Package.toml yet, will require
this file to be created, too. The function julia-create-package-toml
helps creating the file. You need to pass the outputs and the source of the
package, it’s name (the same as the file-name
parameter), the package
uuid, the package version, and a list of dependencies specified by their
name and their uuid.
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 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 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 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
.
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 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 runs luatex
on all files ending on ins
. A
different engine and format can be specified with the #:tex-format
argument. Different build targets can be specified with the
#:build-targets
argument, which expects a list of file names. The
build system adds only texlive-bin
and texlive-latex-base
(both from (gnu packages tex
) to the inputs. Both can be overridden
with the arguments #:texlive-bin
and #:texlive-latex-base
,
respectively.
The #:tex-directory
parameter tells the build system where to install
the built files under the texmf tree.
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 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 (see Packages in 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. The default Meson is meson-for-build
,
which is special because it doesn’t clear the RUNPATH
of binaries and
libraries when they are installed.
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?
.
check
The phase runs ninja
with the target specified in
#:test-target
, which is "test"
by default.
install
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-for-build
, 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.
install
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
.
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
(see build-expression->derivation
).
Next: Build Utilities, Previous: 构建系统, Up: 编程接口 [Contents][Index]
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
(see 构建系统).
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:
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
.
check
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
.
install
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
(see 安装调试文件).
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 (see 调用guix-daemon).
Build phases are represented as association lists or “alists” (see Association Lists in 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
phases16:
;; 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 (see Pairs in 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 (see Optional Arguments in 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 (see 有多个输出的软件包). 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 (see configuration and makefile conventions in 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
(see SRFI-1 Association Lists in GNU Guile Reference Manual); however, it is
more convenient to do so with modify-phases
(see 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
'(#:phases (modify-phases %standard-phases
(delete 'configure)
(add-before 'build 'set-prefix-in-makefile
(lambda* (#:key outputs #:allow-other-keys)
;; Modify the makefile so that its
;; 'PREFIX' variable points to "out".
(let ((out (assoc-ref outputs "out")))
(substitute* "Makefile"
(("PREFIX =.*")
(string-append "PREFIX = "
out "\n")))
#true))))))))
The new phase that is inserted is written as an anonymous procedure,
introduced with lambda*
; it honors the outputs
parameter we
have seen before. See Build Utilities, for more about the helpers used
by this phase, and for more examples of modify-phases
.
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. See G-表达式, for an explanation
of code staging and the code strata involved.
Next: 仓库, Previous: Build Phases, Up: 编程接口 [Contents][Index]
As soon as you start writing non-trivial package definitions
(see 定义软件包) or other build actions (see 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)
(see 构建系统).
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 (see Using Guile Modules in 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
(see POSIX in 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
(see Processes in 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 source directory to destination. Follow symlinks if follow-symlinks? is true; otherwise, just preserve them. When keep-mtime? is true, keep the modification time of the files in source on those of destination. Write verbose output to the log port.
rm -rf
,without following symlinks. Don’t follow mount points either, unless follow-mounts? is true. Report but ignore errors.
regexp in 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" letter 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.
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.
The (guix build utils)
also contains tools to manipulate build phases
as used by build systems (see 构建系统). Build phases are
represented as association lists or “alists” (see Association Lists in GNU Guile Reference Manual) where each key is a symbol naming the
phase and the associated value is a procedure (see 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 (see Optional Arguments in 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")))
#t))))
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)
#t))))
Next: Derivations, Previous: Build Utilities, Up: 编程接口 [Contents][Index]
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 (see 调用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.
注: Users must never modify files under /gnu/store directly. This would lead to inconsistencies and break the immutability assumptions of Guix’s functional model (see 介绍).
See
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 (see --listen).
ssh
These URIs allow you to connect to a remote daemon over SSH. This feature
requires Guile-SSH (see 需求) 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 (see 调用guix copy).
Additional URI schemes may be supported in the future.
注: The ability to connect to remote build daemons is considered experimental as of 1.3.0. Please get in touch with us to share any problems or suggestions you may have (see 贡献).
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.
<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 (see 仓库monad).
This section is currently incomplete.
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 (see 仓库).
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 (see 调用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:
#f] [#: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 (see 下发工作给后台进程的设置). 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 (see substitutes). 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,
see 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
.
[#: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 => …>
Next: G-表达式, Previous: Derivations, Up: 编程接口 [Contents][Index]
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
(see 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 “meta-commands” to make it easier to deal with monadic procedures:
run-in-store
, and enter-store-monad
. 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.
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…17. 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
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
(see Local Bindings in 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).
Run mval, a monadic 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
(see 定义软件包).
Next: 调用guix repl, Previous: 仓库monad, Up: 编程接口 [Contents][Index]
So we have “derivations”, which represent a sequence of build actions to be performed to produce an item in the store (see Derivations). These build actions are performed when asking the daemon to actually build the derivations; they are run by the daemon in a container (see 调用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
code18: 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 (see 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 (see quasiquote
in 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 vm))) (gexp->derivation "something-with-vms" #~(begin (use-modules (guix build utils) (gnu build vm)) …)))
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:output
(ungexp obj output)
This is like the form above, but referring explicitly to the output of obj—this is useful when obj produces multiple outputs (see 有多个输出的软件包).
#+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[:output]
(ungexp output [output])
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 (see 仓库monad, 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 package) (file-name package output) (file-name derivation) (file-name derivation output) (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
(see Derivations).
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.
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.
This is the declarative counterpart of the interned-file
monadic
procedure (see 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
.
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 (see 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")
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.
Scheme file name that contains exp.
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 (see Parameters in 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
.
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>
.
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 (see Using Guile Interactively in GNU Guile Reference
Manual), or by running Guile scripts (see Running Guile Scripts in 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 --
!#
Without a file name argument, a Guile REPL is started:
$ 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:
--type=type
-t type
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.
--load-path=directory
-L directory
Add directory to the front of the package module search path (see 软件包模块).
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.
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 | 下载一个文件并打印它的hash。 | |
• 调用guix hash | 计算一个文件的密码学hash。 | |
• 调用guix import | 导入软件包定义。 | |
• 调用guix refresh | 更新软件包定义。 | |
• 调用guix lint | 从软件包定义里寻找错误。 | |
• 调用guix size | 分析硬盘使用情况。 | |
• 调用guix graph | 展示软件包的关系图。 | |
• 调用guix publish | 分享substitute。 | |
• 调用guix challenge | 挑战subtitute服务器。 | |
• 调用guix copy | 复制到远程的仓库,或从远程的仓库复制。 | |
• 调用guix container | 进程隔离。 | |
• 调用guix weather | 评估substitute的可用性。 | |
• 调用guix processes | 列出客户端进程。 |
Next: 调用guix edit。, Up: 工具 [Contents][Index]
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 (see 调用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 | cut -f1,2 --output-delimiter=@)
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 (see 软件包模块).
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.
• 普通的构建选项 | 大部分命令的构建选项。 | |
• 软件包变换选项。 | 创建软件包的变体。 | |
• 额外的构建选项 | 只属于’guix build’的选项。 | |
• 调试构建错误 | 真实的打包经验。 |
Next: 软件包变换选项。, Up: 调用guix build [Contents][Index]
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 directory
Add directory to the front of the package module search path (see 软件包模块).
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. See 调试构建错误, 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 (see 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 (see substitute失败).
--substitute-urls=urls
Consider urls the whitespace-separated list of substitute source URLs,
overriding the default list of URLs of guix-daemon
(see guix-daemon
URLs).
This means that substitutes may be downloaded from urls, provided they are signed by a key authorized by the system administrator (see substitutes).
When urls is the empty string, substitutes are effectively disabled.
--no-substitutes
不要为构建商品使用substitute。即,总是在本地构建,而不是下载预构建的二进制文件(see substitutes)。
--no-grafts
Do not “graft” packages. In practice, this means that package updates available as grafts are not applied. See 安全更新, 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. See 调用guix challenge, for more.
当和--keep-failed一起使用时,不同的输出保存在/gnu/store/…-check。这让检查两个结果的区别更容易。
--no-offload
Do not use offload builds to other machines (see 下发工作给后台进程的设置). That is, always build things locally instead of offloading builds to remote machines.
--max-silent-time=seconds
当构建或substitution进程超过seconds秒仍然保持静默,就把它结束掉并报告构建失败。
By default, the daemon’s setting is honored (see --max-silent-time).
--timeout=seconds
类似地,当构建或substitution进程执行超过seconds秒,就把它结束掉并报告构建失败。
By default, the daemon’s setting is honored (see --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. See --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.
Next: 额外的构建选项, Previous: 普通的构建选项, Up: 调用guix build [Contents][Index]
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 (see 定义软件包).
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).
--with-source=source
--with-source=package=source
--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
(see 调用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.7.tar.gz
As a developer, --with-source makes it easy to test release candidates:
guix build guile --with-source=../guile-2.0.9.219-e1bb7.tar.xz
… 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=package=replacement
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.0
:
guix build --with-input=guile=guile@2.0 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.0
.
This is implemented using the package-input-rewriting
Scheme
procedure (see package-input-rewriting
).
--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. See 安全更新, 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 (see 安装调试文件).
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. See 安装调试文件, for more info.
注: Under the hood, this option works by passing the ‘#:strip-binaries? #f’ to the build system of the package of interest (see 构建系统). 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
注: 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=package=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=package=branch
Build package from the latest commit of branch. If the
source
field of package is an origin with the git-fetch
method (see origin参考手册) 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=package=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 or a tag.
--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 (see origin参考手册), which by
default includes -p1
(see patch Directories in 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-latest=package
So you like living on the bleeding edge? This option is for you! It replaces
occurrences of package in the dependency graph with its latest
upstream version, as reported by guix refresh
(see 调用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
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! In all the other cases, 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 (see 贡献).
--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 (see 构建系统). 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? See Defining Package Variants, for an overview of the programming interfaces available.
Next: 调试构建错误, Previous: 软件包变换选项。, Up: 调用guix build [Contents][Index]
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 file
Build the package, derivation, or other file-like object that the code within file evaluates to (see file-like objects).
As an example, file might contain a package definition like this (see 定义软件包):
(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": "https://example.com/greeter-1.0.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 (see --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
(see G-表达式).
Lastly, expr may refer to a zero-argument monadic procedure
(see 仓库monad). 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
(see 定义软件包).
As with other derivations, the result of building a source derivation can be verified using the --check option (see 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:
package
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 system
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.
注: 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.
注: 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 (see 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. See 下发工作给后台进程的设置, for more information on offloading.
--target=triplet
Cross-build for triplet, which must be a valid GNU triplet, such as
"aarch64-linux-gnu"
(see GNU
configuration triplets in Autoconf).
--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 (see substitutes), or whether the build result of a package is deterministic. See 调用guix challenge, for more background information and tools.
当和--keep-failed一起使用时,不同的输出保存在/gnu/store/…-check。这让检查两个结果的区别更容易。
--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=file
-r file
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. See 调用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 (as specified with --substitute-urls).
So for instance, imagine you want to see the build log of GDB on MIPS, but
you are actually on an x86_64
machine:
$ guix build --log-file gdb -s aarch64-linux https://ci.guix.gnu.org/log/…-gdb-7.10
You can freely access a huge library of build logs!
Previous: 额外的构建选项, Up: 调用guix build [Contents][Index]
When defining a new package (see 定义软件包), 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
(see --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. (see 设置构建环境).
In such cases, you may need to run 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 environment --no-grafts -C foo --ad-hoc strace gdb [env]# source ./environment-variables [env]# cd foo-1.2
Here, guix environment -C
creates a container and spawns a new
shell in it (see 调用guix environment). The --ad-hoc
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 (see 安全更新, 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 environment
.)
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.
Next: 调用guix download, Previous: 调用guix build, Up: 工具 [Contents][Index]
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 (see 从Git构建), or have
created your own packages on GUIX_PACKAGE_PATH
(see 软件包模块), 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.
Next: 调用guix hash, Previous: 调用guix edit。, Up: 工具 [Contents][Index]
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 (see 定义软件包). 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 (see 调用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. See how to install
the GnuTLS bindings for Guile in 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 (see X.509证书), unless
--no-check-certificate is used.
The following options are available:
--hash=algorithm
-H algorithm
Compute a hash using the specified algorithm. See 调用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, see 调用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=file
-o file
Save the downloaded file to file instead of adding it to the store.
Next: 调用guix import, Previous: 调用guix download, Up: 工具 [Contents][Index]
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 a file, which can be used in the
definition of a package (see 定义软件包).
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 the name of a cryptographic hash algorithm supported by
Libgcrypt via Guile-Gcrypt—e.g., sha512
or sha3-256
(see Hash Functions in 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
Compute the hash on file recursively.
In this case, the hash is computed on an archive 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 has no impact on the hash (see 调用guix archive).
--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 (see origin参考手册):
$ git clone http://example.org/foo.git $ cd foo $ guix hash -rx .
Next: 调用guix refresh, Previous: 调用guix hash, Up: 工具 [Contents][Index]
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 (see 定义软件包).
The general syntax is:
guix import importer options…
importer specifies the source from which to import package metadata, and options specifies a package identifier and other options specific to importer.
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. See --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 itsdangerous
Python
package:
guix import pypi itsdangerous
--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
--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 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 command below imports metadata for the Cairo R package:
guix import cran Cairo
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 --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 metadata from CTAN, the comprehensive TeX archive network for TeX packages that are part of the TeX Live distribution.
Information about the package is obtained through the XML API provided by CTAN, while the source code is downloaded from the SVN repository of the Tex Live project. This is done because the CTAN does not keep versioned archives.
The command command below imports metadata for the fontspec
TeX
package:
guix import texlive fontspec
When --archive=directory is added, the source code is downloaded not from the latex sub-directory of the texmf-dist/source tree in the TeX Live SVN repository, but from the specified sibling directory under the same root.
The command below imports metadata for the ifxetex
package from CTAN
while fetching the sources from the directory texmf/source/generic:
guix import texlive --archive=generic ifxetex
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
(See 定义软件包). 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=version
-l version
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 (see Packages in 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 (see ELPA
package signatures in The GNU Emacs Manual).
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.
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.
--repo
Select the given repository (a repository name). Possible values include:
opam
, the default opam repository,
coq
or coq-released
, the stable repository for coq packages,
coq-core-dev
, the repository that contains development versions of coq,
coq-extra-dev
, the repository that contains development versions
of coq packages.
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.
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 (see 贡献).
Next: 调用guix lint, Previous: 调用guix import, Up: 工具 [Contents][Index]
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
(see --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 …
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 tarball hashes of those package
recipes (see 定义软件包). 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 recipes) in place. This is usually run from a checkout of the Guix source tree (see 在安装之前运行Guix):
$ ./pre-inst-env guix refresh -s non-core -u
See 定义软件包, for more information on package definitions.
--select=[subset]
-s subset
Select all the packages in subset, one of core
or
non-core
.
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.
--manifest=file
-m file
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;
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.
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
-L
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.
See 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 geiser@0.4 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
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
(see kbxutil
in 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 27D586A4F8900854329FF09F1260E46482E63562
See --keyring in 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
Add directory to the front of the package module search path (see 软件包模块).
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.
Next: 调用guix size, Previous: 调用guix refresh, Up: 工具 [Contents][Index]
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
home-page
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
(see origin参考手册).
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 (see Derivations).
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.
See 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.
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.
--no-network
-n
Only enable the checkers that do not depend on Internet access.
--load-path=directory
-L directory
Add directory to the front of the package module search path (see 软件包模块).
This allows users to define their own packages and make them visible to the command-line tools.
Next: 调用guix graph, Previous: 调用guix lint, Up: 工具 [Contents][Index]
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 (see 有多个输出的软件包). 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
store19, guix size
queries the daemon to determine its
dependencies, and measures its size in the store, similar to du -ms
--apparent-size
(see du invocation in GNU Coreutils).
When the given packages are not in the store, guix size
reports information based on the available substitutes
(see substitutes). This makes it possible it to profile 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 (see 调用guix graph).
The available options are:
Use substitute information from urls. See the same option for guix build
.
Sort lines according to key, one of the following options:
self
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 (see 软件包模块).
This allows users to define their own packages and make them visible to the command-line tools.
Next: 调用guix publish, Previous: 调用guix size, Up: 工具 [Contents][Index]
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:
package
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
(see --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 (see gnu-build-system
).
Now, note that the dependencies of these implicit inputs—that is, the bootstrap dependencies (see 引导)—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 (see Derivations) 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)
模块
This is the graph of package modules (see 软件包模块). 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
(see 调用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
(see 调用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
The available options are the following:
Produce a graph output of type, where type must be one of the values listed above.
List the supported graph types.
Produce a graph using the selected backend.
List the supported graph backends.
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 (see 软件包模块).
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 (see 软件包变换选项。). 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!
Next: 调用guix challenge, Previous: 调用guix graph, Up: 工具 [Contents][Index]
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
(see substitutes).
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
ci.guix.gnu.org
build farm.
For security, each substitute is signed, allowing recipients to check their
authenticity and integrity (see substitutes). 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
(see 调用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 (see 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
Once a publishing server has been authorized, the daemon may download substitutes from it. See 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 (see 调用guix weather).
As a bonus, guix publish
also serves as a content-addressed mirror
for source files referenced in origin
records (see origin参考手册). 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, see 调用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 (see 调用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=port
-p port
Listen for HTTP requests on port.
--listen=host
Listen on the network interface for host. The default is to accept connections from any interface.
--user=user
-u user
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.
--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 (see 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
(see 调用guix archive). By
default, /etc/guix/signing-key.pub and
/etc/guix/signing-key.sec are used.
--repl[=port]
-r [port]
Spawn a Guile REPL server (see REPL Servers in 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
(see 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
Next: 调用guix copy, Previous: 调用guix publish, Up: 工具 [Contents][Index]
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 (see substitutes), 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. (see 介绍). 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://ci.guix.gnu.org https://guix.example.org" updating list of substitutes from 'https://ci.guix.gnu.org'... 100.0% updating list of substitutes from 'https://guix.example.org'... 100.0% /gnu/store/…-openssl-1.0.2d contents differ: local hash: 0725l22r5jnzazaacncwsvp9kgf42266ayyp814v7djxs7nk963q https://ci.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://ci.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://ci.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 … 6,406 store items were analyzed: - 4,749 (74.1%) were identical - 525 (8.2%) differed - 1,132 (17.7%) were inconclusive
In this example, guix challenge
first scans the store to determine
the set of locally-built derivations—as opposed to store items that were
downloaded from a substitute server—and then queries all the substitute
servers. It then reports those store items for which the servers obtained a
result different from the local build.
As an example, guix.example.org
always gets a different answer.
Conversely, ci.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 (see 功能). 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://ci.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 (see 调用guix archive):
$ wget -q -O - https://ci.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
ci.guix.gnu.org
(see Comparing and Merging
Files in 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
ci.guix.gnu.org
and other substitute servers obtain the
same build result as you did with:
$ guix challenge package
where package is a package specification such as guile@2.0
or
glibc:debug
.
The general syntax is:
guix challenge options [packages…]
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.
none
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.
Next: 调用guix container, Previous: 调用guix challenge, Up: 工具 [Contents][Index]
guix copy
The guix copy
command copies items from the store of one machine
to that of another machine over a secure shell (SSH)
connection20. 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. See 调用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 (see 普通的构建选项).
Next: 调用guix weather, Previous: 调用guix copy, Up: 工具 [Contents][Index]
guix container
注: As of version 1.3.0, 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 environment
(see 调用guix environment) and guix system container
(see 调用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.
Next: 调用guix processes, Previous: 调用guix container, Up: 工具 [Contents][Index]
guix weather
Occasionally you’re grumpy because substitutes are lacking and you end up
building packages by yourself (see substitutes). 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
(see 调用guix publish).
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 list of 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 default set of substitute servers is queried.
--system=system
-s system
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=file
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
(see 调用guix package).
This option can be repeated several times, in which case the manifests are concatenated.
--coverage[=count]
-c [count]
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://ci.guix.gnu.org -c 10 computing 8,983 package derivations for x86_64-linux... looking for 9,343 store items on https://ci.guix.gnu.org... updating substitutes from 'https://ci.guix.gnu.org'... 100.0% https://ci.guix.gnu.org 64.7% substitutes available (6,047 out of 9,343) … 2502 packages are missing from '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
ci.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.
Previous: 调用guix weather, Up: 工具 [Contents][Index]
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 involved21. Here’s an example of the information it
returns:
$ sudo guix processes SessionPID: 19002 ClientPID: 19090 ClientCommand: guix environment --ad-hoc 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 environment
, 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 (see 下发工作给后台进程的设置).
The output is in Recutils format so we can use the handy recsel
command to select sessions of interest (see Selection Expressions in 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 (see Record Sets in 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
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 (see 功能). 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.
• 使用配置系统 | 定制你的GNU系统。 | |
• 操作系统参考 | 操作系统声明详情。 | |
• 文件系统 | 设置文件系统挂载。 | |
• 映射的设备 | 块设备额外的处理。 | |
• 用户帐号 | 指定用户帐号。 | |
• 键盘布局 | 系统怎样理解按键。 | |
• 区域 | 语言和文化惯例设置。 | |
• 服务 | 指定系统服务。 | |
• setuid程序 | 以root权限运行的程序。 | |
• X.509证书 | 认证HTTPS服务器。 | |
• Name Service Switch | 设置libc的name service switch。 | |
• 初始的内存虚拟硬盘 | Linux-Libre引导。 | |
• 引导设置 | 设置引导程序。 | |
• 调用guix system | 实例化一个系统配置。 | |
• 调用 guix deploy | Deploying a system configuration to a remote host. | |
• 在虚拟机里运行Guix | 怎样在虚拟机里运行Guix。 | |
• 定义服务 | 添加新的服务定义。 |
The operating system is configured by providing an operating-system
declaration in a file that can then be passed to the guix system
command (see 调用guix system). A simple setup, with the default
system services, the default Linux-Libre kernel, initial RAM disk, and boot
loader looks like this:
;; This is an operating system configuration template ;; for a "bare bones" setup, with no X11 display server. (use-modules (gnu)) (use-service-modules networking ssh) (use-package-modules screen ssh) (operating-system (host-name "komputilo") (timezone "Europe/Berlin") (locale "en_US.utf8") ;; Boot in "legacy" BIOS mode, assuming /dev/sdX is the ;; target hard disk, and "my-root" is the label of the target ;; root file system. (bootloader (bootloader-configuration (bootloader grub-bootloader) (target "/dev/sdX"))) (file-systems (cons (file-system (device (file-system-label "my-root")) (mount-point "/") (type "ext4")) %base-file-systems)) ;; This is where user accounts are specified. The "root" ;; account is implicit, and is initially created with the ;; empty password. (users (cons (user-account (name "alice") (comment "Bob's sister") (group "users") ;; Adding the account to the "wheel" group ;; makes it a sudoer. Adding it to "audio" ;; and "video" allows the user to play sound ;; and access the webcam. (supplementary-groups '("wheel" "audio" "video"))) %base-user-accounts)) ;; Globally-installed packages. (packages (cons screen %base-packages)) ;; Add services to the baseline: a DHCP client and ;; an SSH server. (services (append (list (service dhcp-client-service-type) (service openssh-service-type (openssh-configuration (openssh openssh-sans-x) (port-number 2222)))) %base-services)))
This example should be self-describing. Some of the fields defined above,
such as host-name
and bootloader
, are mandatory. Others, such
as packages
and services
, can be omitted, in which case they
get a default value.
Below we discuss the effect of some of the most important fields
(see 操作系统参考, for details about all the available
fields), and how to instantiate the operating system using
guix system
.
The bootloader
field describes the method that will be used to boot
your system. Machines based on Intel processors can boot in “legacy” BIOS
mode, as in the example above. However, more recent machines rely instead
on the Unified Extensible Firmware Interface (UEFI) to boot. In that
case, the bootloader
field should contain something along these
lines:
(bootloader-configuration
(bootloader grub-efi-bootloader)
(target "/boot/efi"))
See 引导设置, for more information on the available configuration options.
The packages
field lists packages that will be globally visible on
the system, for all user accounts—i.e., in every user’s PATH
environment variable—in addition to the per-user profiles (see 调用guix package). The %base-packages
variable provides all the tools
one would expect for basic user and administrator tasks—including the GNU
Core Utilities, the GNU Networking Utilities, the GNU Zile lightweight text
editor, find
, grep
, etc. The example above adds
GNU Screen to those, taken from the (gnu packages screen)
module
(see 软件包模块). The (list package output)
syntax can be
used to add a specific output of a package:
(use-modules (gnu packages)) (use-modules (gnu packages dns)) (operating-system ;; ... (packages (cons (list bind "utils") %base-packages)))
Referring to packages by variable name, like bind
above, has the
advantage of being unambiguous; it also allows typos and such to be
diagnosed right away as “unbound variables”. The downside is that one
needs to know which module defines which package, and to augment the
use-package-modules
line accordingly. To avoid that, one can use the
specification->package
procedure of the (gnu packages)
module,
which returns the best package for a given name or name and version:
(use-modules (gnu packages)) (operating-system ;; ... (packages (append (map specification->package '("tcpdump" "htop" "gnupg@2.0")) %base-packages)))
The services
field lists system services to be made available
when the system starts (see 服务). The operating-system
declaration above specifies that, in addition to the basic services, we want
the OpenSSH secure shell daemon listening on port 2222 (see openssh-service-type
). Under the hood,
openssh-service-type
arranges so that sshd
is started with
the right command-line options, possibly with supporting configuration files
generated as needed (see 定义服务).
Occasionally, instead of using the base services as is, you will want to
customize them. To do this, use modify-services
(see modify-services
) to modify the list.
For example, suppose you want to modify guix-daemon
and Mingetty (the
console log-in) in the %base-services
list (see %base-services
). To do that, you can write the following in your
operating system declaration:
(define %my-services ;; My very own list of services. (modify-services %base-services (guix-service-type config => (guix-configuration (inherit config) ;; Fetch substitutes from example.org. (substitute-urls (list "https://example.org/guix" "https://ci.guix.gnu.org")))) (mingetty-service-type config => (mingetty-configuration (inherit config) ;; Automatially log in as "guest". (auto-login "guest"))))) (operating-system ;; … (services %my-services))
This changes the configuration—i.e., the service parameters—of the
guix-service-type
instance, and that of all the
mingetty-service-type
instances in the %base-services
list.
Observe how this is accomplished: first, we arrange for the original
configuration to be bound to the identifier config
in the body,
and then we write the body so that it evaluates to the desired
configuration. In particular, notice how we use inherit
to create a
new configuration which has the same values as the old configuration, but
with a few modifications.
The configuration for a typical “desktop” usage, with an encrypted root partition, the X11 display server, GNOME and Xfce (users can choose which of these desktop environments to use at the log-in screen by pressing F1), network management, power management, and more, would look like this:
;; This is an operating system configuration template ;; for a "desktop" setup with GNOME and Xfce where the ;; root partition is encrypted with LUKS. (use-modules (gnu) (gnu system nss)) (use-service-modules desktop xorg) (use-package-modules certs gnome) (operating-system (host-name "antelope") (timezone "Europe/Paris") (locale "en_US.utf8") ;; Choose US English keyboard layout. The "altgr-intl" ;; variant provides dead keys for accented characters. (keyboard-layout (keyboard-layout "us" "altgr-intl")) ;; Use the UEFI variant of GRUB with the EFI System ;; Partition mounted on /boot/efi. (bootloader (bootloader-configuration (bootloader grub-efi-bootloader) (target "/boot/efi") (keyboard-layout keyboard-layout))) ;; Specify a mapped device for the encrypted root partition. ;; The UUID is that returned by 'cryptsetup luksUUID'. (mapped-devices (list (mapped-device (source (uuid "12345678-1234-1234-1234-123456789abc")) (target "my-root") (type luks-device-mapping)))) (file-systems (append (list (file-system (device (file-system-label "my-root")) (mount-point "/") (type "ext4") (dependencies mapped-devices)) (file-system (device (uuid "1234-ABCD" 'fat)) (mount-point "/boot/efi") (type "vfat"))) %base-file-systems)) ;; Create user `bob' with `alice' as its initial password. (users (cons (user-account (name "bob") (comment "Alice's brother") (password (crypt "alice" "$6$abc")) (group "users") (supplementary-groups '("wheel" "netdev" "audio" "video"))) %base-user-accounts)) ;; This is where we specify system-wide packages. (packages (append (list ;; for HTTPS access nss-certs ;; for user mounts gvfs) %base-packages)) ;; Add GNOME and Xfce---we can choose at the log-in screen ;; by clicking the gear. Use the "desktop" services, which ;; include the X11 log-in service, networking with ;; NetworkManager, and more. (services (append (list (service gnome-desktop-service-type) (service xfce-desktop-service-type) (set-xorg-configuration (xorg-configuration (keyboard-layout keyboard-layout)))) %desktop-services)) ;; Allow resolution of '.local' host names with mDNS. (name-service-switch %mdns-host-lookup-nss))
A graphical system with a choice of lightweight window managers instead of full-blown desktop environments would look like this:
;; This is an operating system configuration template ;; for a "desktop" setup without full-blown desktop ;; environments. (use-modules (gnu) (gnu system nss)) (use-service-modules desktop) (use-package-modules bootloaders certs emacs emacs-xyz ratpoison suckless wm xorg) (operating-system (host-name "antelope") (timezone "Europe/Paris") (locale "en_US.utf8") ;; Use the UEFI variant of GRUB with the EFI System ;; Partition mounted on /boot/efi. (bootloader (bootloader-configuration (bootloader grub-efi-bootloader) (target "/boot/efi"))) ;; Assume the target root file system is labelled "my-root", ;; and the EFI System Partition has UUID 1234-ABCD. (file-systems (append (list (file-system (device (file-system-label "my-root")) (mount-point "/") (type "ext4")) (file-system (device (uuid "1234-ABCD" 'fat)) (mount-point "/boot/efi") (type "vfat"))) %base-file-systems)) (users (cons (user-account (name "alice") (comment "Bob's sister") (group "users") (supplementary-groups '("wheel" "netdev" "audio" "video"))) %base-user-accounts)) ;; Add a bunch of window managers; we can choose one at ;; the log-in screen with F1. (packages (append (list ;; window managers ratpoison i3-wm i3status dmenu emacs emacs-exwm emacs-desktop-environment ;; terminal emulator xterm ;; for HTTPS access nss-certs) %base-packages)) ;; Use the "desktop" services, which include the X11 ;; log-in service, networking with NetworkManager, and more. (services %desktop-services) ;; Allow resolution of '.local' host names with mDNS. (name-service-switch %mdns-host-lookup-nss))
This example refers to the /boot/efi file system by its UUID,
1234-ABCD
. Replace this UUID with the right UUID on your system, as
returned by the blkid
command.
See 桌面服务, for the exact list of services provided by
%desktop-services
. See X.509证书, for background
information about the nss-certs
package that is used here.
Again, %desktop-services
is just a list of service objects. If you
want to remove services from there, you can do so using the procedures for
list filtering (see SRFI-1 Filtering and Partitioning in GNU Guile
Reference Manual). For instance, the following expression returns a list
that contains all the services in %desktop-services
minus the Avahi
service:
(remove (lambda (service)
(eq? (service-kind service) avahi-service-type))
%desktop-services)
Alternatively, the modify-services
macro can be used:
(modify-services %desktop-services
(delete avahi-service-type))
Assuming the operating-system
declaration is stored in the
my-system-config.scm file, the guix system reconfigure
my-system-config.scm
command instantiates that configuration, and makes it
the default GRUB boot entry (see 调用guix system).
The normal way to change the system configuration is by updating this file
and re-running guix system reconfigure
. One should never have to
touch files in /etc or to run commands that modify the system state
such as useradd
or grub-install
. In fact, you must
avoid that since that would not only void your warranty but also prevent you
from rolling back to previous versions of your system, should you ever need
to.
Speaking of roll-back, each time you run guix system reconfigure
,
a new generation of the system is created—without modifying or
deleting previous generations. Old system generations get an entry in the
bootloader boot menu, allowing you to boot them in case something went wrong
with the latest generation. Reassuring, no? The guix system
list-generations
command lists the system generations available on disk.
It is also possible to roll back the system via the commands guix
system roll-back
and guix system switch-generation
.
Although the guix system reconfigure
command will not modify
previous generations, you must take care when the current generation is not
the latest (e.g., after invoking guix system roll-back
), since the
operation might overwrite a later generation (see 调用guix system).
At the Scheme level, the bulk of an operating-system
declaration is
instantiated with the following monadic procedure (see 仓库monad):
Return a derivation that builds os, an operating-system
object
(see Derivations).
The output of the derivation is a single directory that refers to all the packages, configuration files, and other supporting files needed to instantiate os.
This procedure is provided by the (gnu system)
module. Along with
(gnu services)
(see 服务), this module contains the guts of
Guix System. Make sure to visit it!
operating-system
ReferenceThis section summarizes all the options available in operating-system
declarations (see 使用配置系统).
This is the data type representing an operating system configuration. By that, we mean all the global system configuration, not per-user configuration (see 使用配置系统).
kernel
(default: linux-libre
)The package object of the operating system kernel to use22.
hurd
(default: #f
)The package object of the Hurd to be started by the kernel. When this field
is set, produce a GNU/Hurd operating system. In that case, kernel
must also be set to the gnumach
package—the microkernel the Hurd
runs on.
Warning: This feature is experimental and only supported for disk images.
kernel-loadable-modules
(default: ’())A list of objects (usually packages) to collect loadable kernel modules
from–e.g. (list ddcci-driver-linux)
.
kernel-arguments
(default: %default-kernel-arguments
)List of strings or gexps representing additional arguments to pass on the
command-line of the kernel—e.g., ("console=ttyS0")
.
bootloader
The system bootloader configuration object. See 引导设置.
label
This is the label (a string) as it appears in the bootloader’s menu entry. The default label includes the kernel name and version.
keyboard-layout
(default: #f
)This field specifies the keyboard layout to use in the console. It can be
either #f
, in which case the default keyboard layout is used (usually
US English), or a <keyboard-layout>
record. See 键盘布局,
for more information.
This keyboard layout is in effect as soon as the kernel has booted. For
instance, it is the keyboard layout in effect when you type a passphrase if
your root file system is on a luks-device-mapping
mapped device
(see 映射的设备).
注: This does not specify the keyboard layout used by the bootloader, nor that used by the graphical display server. See 引导设置, for information on how to specify the bootloader’s keyboard layout. See X窗口, for information on how to specify the keyboard layout used by the X Window System.
initrd-modules
(default: %base-initrd-modules
)The list of Linux kernel modules that need to be available in the initial RAM disk. See 初始的内存虚拟硬盘.
initrd
(default: base-initrd
)A procedure that returns an initial RAM disk for the Linux kernel. This field is provided to support low-level customization and should rarely be needed for casual use. See 初始的内存虚拟硬盘.
firmware
(default: %base-firmware
)List of firmware packages loadable by the operating system kernel.
The default includes firmware needed for Atheros- and Broadcom-based WiFi
devices (Linux-libre modules ath9k
and b43-open
,
respectively). See 硬件的考虑, for more info on supported
hardware.
host-name
The host name.
hosts-file
A file-like object (see file-like objects) for use as
/etc/hosts (see Host Names in The GNU C Library Reference
Manual). The default is a file with entries for localhost
and
host-name.
mapped-devices
(default: '()
)A list of mapped devices. See 映射的设备.
file-systems
A list of file systems. See 文件系统.
swap-devices
(default: '()
)A list of UUIDs, file system labels, or strings identifying devices or files to be used for “swap space” (see Memory Concepts in The GNU C Library Reference Manual). Here are some examples:
(list (uuid "4dab5feb-d176-45de-b287-9b0a6e4c01cb"))
Use the swap partition with the given UUID. You can learn the UUID of a
Linux swap partition by running swaplabel device
, where
device is the /dev file name of that partition.
(list (file-system-label "swap"))
Use the partition with label swap
. Again, the swaplabel
command allows you to view and change the label of a Linux swap partition.
(list "/swapfile")
Use the file /swapfile as swap space.
(list "/dev/sda3" "/dev/sdb2")
Use the /dev/sda3 and /dev/sdb2 partitions as swap space. We recommend referring to swap devices by UUIDs or labels as shown above instead.
It is possible to specify a swap file in a file system on a mapped device (under /dev/mapper), provided that the necessary device mapping and file system are also specified. See 映射的设备 and 文件系统.
users
(default: %base-user-accounts
)groups
(default: %base-groups
)List of user accounts and groups. See 用户帐号.
If the users
list lacks a user account with UID 0, a “root”
account with UID 0 is automatically added.
skeletons
(default: (default-skeletons)
)A list of target file name/file-like object tuples (see file-like objects). These are the skeleton files that will be added to the home directory of newly-created user accounts.
For instance, a valid value may look like this:
`((".bashrc" ,(plain-file "bashrc" "echo Hello\n")) (".guile" ,(plain-file "guile" "(use-modules (ice-9 readline)) (activate-readline)")))
issue
(default: %default-issue
)A string denoting the contents of the /etc/issue file, which is displayed when users log in on a text console.
packages
(default: %base-packages
)A list of packages to be installed in the global profile, which is accessible at /run/current-system/profile. Each element is either a package variable or a package/output tuple. Here’s a simple example of both:
(cons* git ; the default "out" output (list git "send-email") ; another output of git %base-packages) ; the default set
The default set includes core utilities and it is good practice to install non-core utilities in user profiles (see 调用guix package).
timezone
A timezone identifying string—e.g., "Europe/Paris"
.
You can run the tzselect
command to find out which timezone string
corresponds to your region. Choosing an invalid timezone name causes
guix system
to fail.
locale
(default: "en_US.utf8"
)The name of the default locale (see Locale Names in The GNU C Library Reference Manual). See 区域, for more information.
locale-definitions
(default: %default-locale-definitions
)The list of locale definitions to be compiled and that may be used at run time. See 区域.
locale-libcs
(default: (list glibc)
)The list of GNU libc packages whose locale data and tools are used to build the locale definitions. See 区域, for compatibility considerations that justify this option.
name-service-switch
(default: %default-nss
)Configuration of the libc name service switch (NSS)—a
<name-service-switch>
object. See Name Service Switch, for
details.
services
(default: %base-services
)A list of service objects denoting system services. See 服务.
essential-services
(default: ...)The list of “essential services”—i.e., things like instances of
system-service-type
and host-name-service-type
(see 服务参考), which are derived from the operating system definition itself.
As a user you should never need to touch this field.
pam-services
(default: (base-pam-services)
)Linux pluggable authentication module (PAM) services.
setuid-programs
(default: %setuid-programs
)List of string-valued G-expressions denoting setuid programs. See setuid程序.
sudoers-file
(default: %sudoers-specification
)The contents of the /etc/sudoers file as a file-like object
(see local-file
and plain-file
).
This file specifies which users can use the sudo
command, what
they are allowed to do, and what privileges they may gain. The default is
that only root
and members of the wheel
group may use
sudo
.
When used in the lexical scope of an operating system field definition, this identifier resolves to the operating system being defined.
The example below shows how to refer to the operating system being defined
in the definition of the label
field:
(use-modules (gnu) (guix)) (operating-system ;; ... (label (package-full-name (operating-system-kernel this-operating-system))))
It is an error to refer to this-operating-system
outside an operating
system definition.
The list of file systems to be mounted is specified in the
file-systems
field of the operating system declaration (see 使用配置系统). Each file system is declared using the
file-system
form, like this:
(file-system
(mount-point "/home")
(device "/dev/sda3")
(type "ext4"))
As usual, some of the fields are mandatory—those shown in the example above—while others can be omitted. These are described below.
Objects of this type represent file systems to be mounted. They contain the following members:
type
This is a string specifying the type of the file system—e.g.,
"ext4"
.
mount-point
This designates the place where the file system is to be mounted.
device
This names the “source” of the file system. It can be one of three things: a file system label, a file system UUID, or the name of a /dev node. Labels and UUIDs offer a way to refer to file systems without having to hard-code their actual device name23.
File system labels are created using the file-system-label
procedure,
UUIDs are created using uuid
, and /dev node are plain
strings. Here’s an example of a file system referred to by its label, as
shown by the e2label
command:
(file-system
(mount-point "/home")
(type "ext4")
(device (file-system-label "my-home")))
UUIDs are converted from their string representation (as shown by the
tune2fs -l
command) using the uuid
form24, like
this:
(file-system
(mount-point "/home")
(type "ext4")
(device (uuid "4dab5feb-d176-45de-b287-9b0a6e4c01cb")))
When the source of a file system is a mapped device (see 映射的设备), its device
field must refer to the mapped device
name—e.g., "/dev/mapper/root-partition". This is required so that
the system knows that mounting the file system depends on having the
corresponding device mapping established.
flags
(default: '()
)This is a list of symbols denoting mount flags. Recognized flags include
read-only
, bind-mount
, no-dev
(disallow access to
special files), no-suid
(ignore setuid and setgid bits),
no-atime
(do not update file access times), strict-atime
(update file access time), lazy-time
(only update time on the
in-memory version of the file inode), and no-exec
(disallow program
execution). See Mount-Unmount-Remount in The GNU C Library
Reference Manual, for more information on these flags.
options
(default: #f
)This is either #f
, or a string denoting mount options passed to the
file system driver. See Mount-Unmount-Remount in The GNU C Library
Reference Manual, for details and run man 8 mount
for options for
various file systems. Note that the file-system-options->alist
and
alist->file-system-options
procedures from (gnu system
file-systems)
can be used to convert file system options given as an
association list to the string representation, and vice-versa.
mount?
(default: #t
)This value indicates whether to automatically mount the file system when the
system is brought up. When set to #f
, the file system gets an entry
in /etc/fstab (read by the mount
command) but is not
automatically mounted.
needed-for-boot?
(default: #f
)This Boolean value indicates whether the file system is needed when booting. If that is true, then the file system is mounted when the initial RAM disk (initrd) is loaded. This is always the case, for instance, for the root file system.
check?
(default: #t
)This Boolean indicates whether the file system needs to be checked for errors before being mounted.
create-mount-point?
(default: #f
)When true, the mount point is created if it does not exist yet.
mount-may-fail?
(default: #f
)When true, this indicates that mounting this file system can fail but that
should not be considered an error. This is useful in unusual cases; an
example of this is efivarfs
, a file system that can only be mounted
on EFI/UEFI systems.
dependencies
(default: '()
)This is a list of <file-system>
or <mapped-device>
objects
representing file systems that must be mounted or mapped devices that must
be opened before (and unmounted or closed after) this one.
As an example, consider a hierarchy of mounts: /sys/fs/cgroup is a dependency of /sys/fs/cgroup/cpu and /sys/fs/cgroup/memory.
Another example is a file system that depends on a mapped device, for example for an encrypted partition (see 映射的设备).
This procedure returns an opaque file system label from str, a string:
(file-system-label "home") ⇒ #<file-system-label "home">
File system labels are used to refer to file systems by label rather than by device name. See above for examples.
The (gnu system file-systems)
exports the following useful variables.
These are essential file systems that are required on normal systems, such
as %pseudo-terminal-file-system
and %immutable-store
(see
below). Operating system declarations should always contain at least these.
This is the file system to be mounted as /dev/pts. It supports
pseudo-terminals created via openpty
and similar functions
(see Pseudo-Terminals in The GNU C Library Reference Manual).
Pseudo-terminals are used by terminal emulators such as xterm
.
This file system is mounted as /dev/shm and is used to support memory
sharing across processes (see shm_open
in The GNU C Library Reference Manual).
This file system performs a read-only “bind mount” of /gnu/store,
making it read-only for all the users including root
. This prevents
against accidental modification by software running as root
or by
system administrators.
The daemon itself is still able to write to the store: it remounts it read-write in its own “name space.”
The binfmt_misc
file system, which allows handling of arbitrary
executable file types to be delegated to user space. This requires the
binfmt.ko
kernel module to be loaded.
The fusectl
file system, which allows unprivileged users to mount and
unmount user-space FUSE file systems. This requires the fuse.ko
kernel module to be loaded.
The (gnu system uuid)
module provides tools to deal with file system
“unique identifiers” (UUIDs).
Return an opaque UUID (unique identifier) object of the given type (a symbol) by parsing str (a string):
(uuid "4dab5feb-d176-45de-b287-9b0a6e4c01cb") ⇒ #<<uuid> type: dce bv: …> (uuid "1234-ABCD" 'fat) ⇒ #<<uuid> type: fat bv: …>
type may be one of dce
, iso9660
, fat
,
ntfs
, or one of the commonly found synonyms for these.
UUIDs are another way to unambiguously refer to file systems in operating system configuration. See the examples above.
• Btrfs file system |
The Btrfs has special features, such as subvolumes, that merit being explained in more details. The following section attempts to cover basic as well as complex uses of a Btrfs file system with the Guix System.
In its simplest usage, a Btrfs file system can be described, for example, by:
(file-system
(mount-point "/home")
(type "btrfs")
(device (file-system-label "my-home")))
The example below is more complex, as it makes use of a Btrfs subvolume,
named rootfs
. The parent Btrfs file system is labeled
my-btrfs-pool
, and is located on an encrypted device (hence the
dependency on mapped-devices
):
(file-system
(device (file-system-label "my-btrfs-pool"))
(mount-point "/")
(type "btrfs")
(options "subvol=rootfs")
(dependencies mapped-devices))
Some bootloaders, for example GRUB, only mount a Btrfs partition at its top
level during the early boot, and rely on their configuration to refer to the
correct subvolume path within that top level. The bootloaders operating in
this way typically produce their configuration on a running system where the
Btrfs partitions are already mounted and where the subvolume information is
readily available. As an example, grub-mkconfig
, the
configuration generator command shipped with GRUB, reads
/proc/self/mountinfo to determine the top-level path of a subvolume.
The Guix System produces a bootloader configuration using the operating system configuration as its sole input; it is therefore necessary to extract the subvolume name on which /gnu/store lives (if any) from that operating system configuration. To better illustrate, consider a subvolume named ’rootfs’ which contains the root file system data. In such situation, the GRUB bootloader would only see the top level of the root Btrfs partition, e.g.:
/ (top level) ├── rootfs (subvolume directory) ├── gnu (normal directory) ├── store (normal directory) [...]
Thus, the subvolume name must be prepended to the /gnu/store path of the kernel, initrd binaries and any other files referred to in the GRUB configuration that must be found during the early boot.
The next example shows a nested hierarchy of subvolumes and directories:
/ (top level) ├── rootfs (subvolume) ├── gnu (normal directory) ├── store (subvolume) [...]
This scenario would work without mounting the ’store’ subvolume. Mounting
’rootfs’ is sufficient, since the subvolume name matches its intended mount
point in the file system hierarchy. Alternatively, the ’store’ subvolume
could be referred to by setting the subvol
option to either
/rootfs/gnu/store
or rootfs/gnu/store
.
Finally, a more contrived example of nested subvolumes:
/ (top level) ├── root-snapshots (subvolume) ├── root-current (subvolume) ├── guix-store (subvolume) [...]
Here, the ’guix-store’ subvolume doesn’t match its intended mount point, so
it is necessary to mount it. The subvolume must be fully specified, by
passing its file name to the subvol
option. To illustrate, the
’guix-store’ subvolume could be mounted on /gnu/store by using a file
system declaration such as:
(file-system
(device (file-system-label "btrfs-pool-1"))
(mount-point "/gnu/store")
(type "btrfs")
(options "subvol=root-snapshots/root-current/guix-store,\
compress-force=zstd,space_cache=v2"))
The Linux kernel has a notion of device mapping: a block device, such
as a hard disk partition, can be mapped into another device, usually
in /dev/mapper/
, with additional processing over the data that flows
through it25. A typical example is encryption
device mapping: all writes to the mapped device are encrypted, and all reads
are deciphered, transparently. Guix extends this notion by considering any
device or set of devices that are transformed in some way to create a
new device; for instance, RAID devices are obtained by assembling
several other devices, such as hard disks or partitions, into a new one that
behaves as one partition.
Mapped devices are declared using the mapped-device
form, defined as
follows; for examples, see below.
Objects of this type represent device mappings that will be made when the system boots up.
source
This is either a string specifying the name of the block device to be
mapped, such as "/dev/sda3"
, or a list of such strings when several
devices need to be assembled for creating a new one. In case of LVM this is
a string specifying name of the volume group to be mapped.
target
This string specifies the name of the resulting mapped device. For kernel
mappers such as encrypted devices of type luks-device-mapping
,
specifying "my-partition"
leads to the creation of the
"/dev/mapper/my-partition"
device. For RAID devices of type
raid-device-mapping
, the full device name such as "/dev/md0"
needs to be given. LVM logical volumes of type lvm-device-mapping
need to be specified as "VGNAME-LVNAME"
.
targets
This list of strings specifies names of the resulting mapped devices in case there are several. The format is identical to target.
type
This must be a mapped-device-kind
object, which specifies how
source is mapped to target.
This defines LUKS block device encryption using the cryptsetup
command from the package with the same name. It relies on the
dm-crypt
Linux kernel module.
This defines a RAID device, which is assembled using the mdadm
command from the package with the same name. It requires a Linux kernel
module for the appropriate RAID level to be loaded, such as raid456
for RAID-4, RAID-5 or RAID-6, or raid10
for RAID-10.
This defines one or more logical volumes for the Linux
Logical Volume Manager (LVM). The
volume group is activated by the vgchange
command from the
lvm2
package.
The following example specifies a mapping from /dev/sda3 to
/dev/mapper/home using LUKS—the
Linux Unified Key Setup, a
standard mechanism for disk encryption. The /dev/mapper/home device
can then be used as the device
of a file-system
declaration
(see 文件系统).
(mapped-device
(source "/dev/sda3")
(target "home")
(type luks-device-mapping))
Alternatively, to become independent of device numbering, one may obtain the LUKS UUID (unique identifier) of the source device by a command like:
cryptsetup luksUUID /dev/sda3
and use it as follows:
(mapped-device
(source (uuid "cb67fc72-0d54-4c88-9d4b-b225f30b0f44"))
(target "home")
(type luks-device-mapping))
It is also desirable to encrypt swap space, since swap space may contain sensitive data. One way to accomplish that is to use a swap file in a file system on a device mapped via LUKS encryption. In this way, the swap file is encrypted because the entire device is encrypted. See Disk Partitioning, for an example.
A RAID device formed of the partitions /dev/sda1 and /dev/sdb1 may be declared as follows:
(mapped-device
(source (list "/dev/sda1" "/dev/sdb1"))
(target "/dev/md0")
(type raid-device-mapping))
The /dev/md0 device can then be used as the device
of a
file-system
declaration (see 文件系统). Note that the RAID
level need not be given; it is chosen during the initial creation and
formatting of the RAID device and is determined automatically later.
LVM logical volumes “alpha” and “beta” from volume group “vg0” can be declared as follows:
(mapped-device
(source "vg0")
(targets (list "vg0-alpha" "vg0-beta"))
(type lvm-device-mapping))
Devices /dev/mapper/vg0-alpha and /dev/mapper/vg0-beta can
then be used as the device
of a file-system
declaration
(see 文件系统).
User accounts and groups are entirely managed through the
operating-system
declaration. They are specified with the
user-account
and user-group
forms:
(user-account
(name "alice")
(group "users")
(supplementary-groups '("wheel" ;allow use of sudo, etc.
"audio" ;sound card
"video" ;video devices such as webcams
"cdrom")) ;the good ol' CD-ROM
(comment "Bob's sister"))
Here’s a user account that uses a different shell and a custom home directory (the default would be "/home/bob"):
(user-account
(name "bob")
(group "users")
(comment "Alice's bro")
(shell (file-append zsh "/bin/zsh"))
(home-directory "/home/robert"))
When booting or upon completion of guix system reconfigure
, the
system ensures that only the user accounts and groups specified in the
operating-system
declaration exist, and with the specified
properties. Thus, account or group creations or modifications made by
directly invoking commands such as useradd
are lost upon
reconfiguration or reboot. This ensures that the system remains exactly as
declared.
Objects of this type represent user accounts. The following members may be specified:
名字
The name of the user account.
group
This is the name (a string) or identifier (a number) of the user group this account belongs to.
supplementary-groups
(default: '()
)Optionally, this can be defined as a list of group names that this account belongs to.
uid
(default: #f
)This is the user ID for this account (a number), or #f
. In the
latter case, a number is automatically chosen by the system when the account
is created.
comment
(default: ""
)A comment about the account, such as the account owner’s full name.
home-directory
This is the name of the home directory for the account.
create-home-directory?
(default: #t
)Indicates whether the home directory of this account should be created if it does not exist yet.
shell
(default: Bash)This is a G-expression denoting the file name of a program to be used as the shell (see G-表达式). For example, you would refer to the Bash executable like this:
(file-append bash "/bin/bash")
... and to the Zsh executable like that:
(file-append zsh "/bin/zsh")
system?
(default: #f
)This Boolean value indicates whether the account is a “system” account. System accounts are sometimes treated specially; for instance, graphical login managers do not list them.
password
(default: #f
)You would normally leave this field to #f
, initialize user passwords
as root
with the passwd
command, and then let users change
it with passwd
. Passwords set with passwd
are of course
preserved across reboot and reconfiguration.
If you do want to set an initial password for an account, then this
field must contain the encrypted password, as a string. You can use the
crypt
procedure for this purpose:
(user-account
(name "charlie")
(group "users")
;; Specify a SHA-512-hashed initial password.
(password (crypt "InitialPassword!" "$6$abc")))
注: The hash of this initial password will be available in a file in /gnu/store, readable by all the users, so this method must be used with care.
See Passphrase Storage in The GNU C Library Reference Manual, for
more information on password encryption, and Encryption in GNU
Guile Reference Manual, for information on Guile’s crypt
procedure.
User group declarations are even simpler:
(user-group (name "students"))
This type is for, well, user groups. There are just a few fields:
名字
The name of the group.
id
(default: #f
)The group identifier (a number). If #f
, a new number is
automatically allocated when the group is created.
system?
(default: #f
)This Boolean value indicates whether the group is a “system” group. System groups have low numerical IDs.
password
(default: #f
)What, user groups can have a password? Well, apparently yes. Unless
#f
, this field specifies the password of the group.
For convenience, a variable lists all the basic user groups one may expect:
This is the list of basic user groups that users and/or packages expect to be present on the system. This includes groups such as “root”, “wheel”, and “users”, as well as groups used to control access to specific devices such as “audio”, “disk”, and “cdrom”.
This is the list of basic system accounts that programs may expect to find on a GNU/Linux system, such as the “nobody” account.
Note that the “root” account is not included here. It is a special-case and is automatically added whether or not it is specified.
To specify what each key of your keyboard does, you need to tell the operating system what keyboard layout you want to use. The default, when nothing is specified, is the US English QWERTY layout for 105-key PC keyboards. However, German speakers will usually prefer the German QWERTZ layout, French speakers will want the AZERTY layout, and so on; hackers might prefer Dvorak or bépo, and they might even want to further customize the effect of some of the keys. This section explains how to get that done.
There are three components that will want to know about your keyboard layout:
keyboard-layout
). This is useful
if you want, for instance, to make sure that you can type the passphrase of
your encrypted root partition using the right layout.
keyboard-layout
).
keyboard-layout
).
Guix allows you to configure all three separately but, fortunately, it allows you to share the same keyboard layout for all three components.
Keyboard layouts are represented by records created by the
keyboard-layout
procedure of (gnu system keyboard)
. Following
the X Keyboard extension (XKB), each layout has four attributes: a name
(often a language code such as “fi” for Finnish or “jp” for Japanese),
an optional variant name, an optional keyboard model name, and a possibly
empty list of additional options. In most cases the layout name is all you
care about.
name and variant.
name must be a string such as "fr"
; variant must be a
string such as "bepo"
or "nodeadkeys"
. See the
xkeyboard-config
package for valid options.
Here are a few examples:
;; The German QWERTZ layout. Here we assume a standard ;; "pc105" keyboard model. (keyboard-layout "de") ;; The bépo variant of the French layout. (keyboard-layout "fr" "bepo") ;; The Catalan layout. (keyboard-layout "es" "cat") ;; Arabic layout with "Alt-Shift" to switch to US layout. (keyboard-layout "ar,us" #:options '("grp:alt_shift_toggle")) ;; The Latin American Spanish layout. In addition, the ;; "Caps Lock" key is used as an additional "Ctrl" key, ;; and the "Menu" key is used as a "Compose" key to enter ;; accented letters. (keyboard-layout "latam" #:options '("ctrl:nocaps" "compose:menu")) ;; The Russian layout for a ThinkPad keyboard. (keyboard-layout "ru" #:model "thinkpad") ;; The "US international" layout, which is the US layout plus ;; dead keys to enter accented characters. This is for an ;; Apple MacBook keyboard. (keyboard-layout "us" "intl" #:model "macbook78")
See the share/X11/xkb directory of the xkeyboard-config
package for a complete list of supported layouts, variants, and models.
Let’s say you want your system to use the Turkish keyboard layout throughout your system—bootloader, console, and Xorg. Here’s what your system configuration would look like:
;; Using the Turkish layout for the bootloader, the console, ;; and for Xorg. (operating-system ;; ... (keyboard-layout (keyboard-layout "tr")) ;for the console (bootloader (bootloader-configuration (bootloader grub-efi-bootloader) (target "/boot/efi") (keyboard-layout keyboard-layout))) ;for GRUB (services (cons (set-xorg-configuration (xorg-configuration ;for Xorg (keyboard-layout keyboard-layout))) %desktop-services)))
In the example above, for GRUB and for Xorg, we just refer to the
keyboard-layout
field defined above, but we could just as well refer
to a different layout. The set-xorg-configuration
procedure
communicates the desired Xorg configuration to the graphical log-in manager,
by default GDM.
We’ve discussed how to specify the default keyboard layout of your system when it starts, but you can also adjust it at run time:
setxkbmap
command (from the same-named package)
allows you to change the current layout. For example, this is how you would
change the layout to US Dvorak:
setxkbmap us dvorak
loadkeys
command changes the keyboard layout in effect in the
Linux console. However, note that loadkeys
does not use the
XKB keyboard layout categorization described above. The command below loads
the French bépo layout:
loadkeys fr-bepo
A locale defines cultural conventions for a particular language and
region of the world (see 区域 in The GNU C Library Reference
Manual). Each locale has a name that typically has the form
language_territory.codeset
—e.g.,
fr_LU.utf8
designates the locale for the French language, with
cultural conventions from Luxembourg, and using the UTF-8 encoding.
Usually, you will want to specify the default locale for the machine using
the locale
field of the operating-system
declaration
(see locale
).
The selected locale is automatically added to the locale definitions
known to the system if needed, with its codeset inferred from its
name—e.g., bo_CN.utf8
will be assumed to use the UTF-8
codeset. Additional locale definitions can be specified in the
locale-definitions
slot of operating-system
—this is useful,
for instance, if the codeset could not be inferred from the locale name.
The default set of locale definitions includes some widely used locales, but
not all the available locales, in order to save space.
For instance, to add the North Frisian locale for Germany, the value of that field may be:
(cons (locale-definition
(name "fy_DE.utf8") (source "fy_DE"))
%default-locale-definitions)
Likewise, to save space, one might want locale-definitions
to list
only the locales that are actually used, as in:
(list (locale-definition
(name "ja_JP.eucjp") (source "ja_JP")
(charset "EUC-JP")))
The compiled locale definitions are available at
/run/current-system/locale/X.Y, where X.Y
is the libc version,
which is the default location where the GNU libc provided by Guix looks
for locale data. This can be overridden using the LOCPATH
environment
variable (see LOCPATH
and locale packages).
The locale-definition
form is provided by the (gnu system
locale)
module. Details are given below.
This is the data type of a locale definition.
名字
The name of the locale. See Locale Names in The GNU C Library Reference Manual, for more information on locale names.
source
The name of the source for that locale. This is typically the
language_territory
part of the locale name.
charset
(default: "UTF-8"
)The “character set” or “code set” for that locale, as defined by IANA.
A list of commonly used UTF-8 locales, used as the default value of the
locale-definitions
field of operating-system
declarations.
These locale definitions use the normalized codeset for the part that
follows the dot in the name (see normalized
codeset in The GNU C Library Reference Manual). So for instance it
has uk_UA.utf8
but not, say, uk_UA.UTF-8
.
operating-system
declarations provide a locale-libcs
field to
specify the GNU libc packages that are used to compile locale
declarations (see 操作系统参考). “Why would I care?”,
you may ask. Well, it turns out that the binary format of locale data is
occasionally incompatible from one libc version to another.
For instance, a program linked against libc version 2.21 is unable to read
locale data produced with libc 2.22; worse, that program aborts
instead of simply ignoring the incompatible locale data26. Similarly, a program linked
against libc 2.22 can read most, but not all, of the locale data from libc
2.21 (specifically, LC_COLLATE
data is incompatible); thus calls to
setlocale
may fail, but programs will not abort.
The “problem” with Guix is that users have a lot of freedom: They can choose whether and when to upgrade software in their profiles, and might be using a libc version different from the one the system administrator used to build the system-wide locale data.
Fortunately, unprivileged users can also install their own locale data and
define GUIX_LOCPATH
accordingly (see GUIX_LOCPATH
and locale packages).
Still, it is best if the system-wide locale data at
/run/current-system/locale is built for all the libc versions
actually in use on the system, so that all the programs can access it—this
is especially crucial on a multi-user system. To do that, the administrator
can specify several libc packages in the locale-libcs
field of
operating-system
:
(use-package-modules base) (operating-system ;; … (locale-libcs (list glibc-2.21 (canonical-package glibc))))
This example would lead to a system containing locale definitions for both libc 2.21 and the current version of libc in /run/current-system/locale.
An important part of preparing an operating-system
declaration is
listing system services and their configuration (see 使用配置系统). System services are typically daemons launched when
the system boots, or other actions needed at that time—e.g., configuring
network access.
Guix has a broad definition of “service” (see 合成服务),
but many services are managed by the GNU Shepherd (see Shepherd服务). On a running system, the herd
command allows you to
list the available services, show their status, start and stop them, or do
other specific operations (see Jump Start in The GNU Shepherd
Manual). For example:
# herd status
The above command, run as root
, lists the currently defined
services. The herd doc
command shows a synopsis of the given
service and its associated actions:
# herd doc nscd Run libc's name service cache daemon (nscd). # herd doc nscd action invalidate invalidate: Invalidate the given cache--e.g., 'hosts' for host name lookups.
The start
, stop
, and restart
sub-commands have
the effect you would expect. For instance, the commands below stop the nscd
service and restart the Xorg display server:
# herd stop nscd Service nscd has been stopped. # herd restart xorg-server Service xorg-server has been stopped. Service xorg-server has been started.
The following sections document the available services, starting with the
core services, that may be used in an operating-system
declaration.
• 基础服务 | 必要的系统服务。 | |
• 执行计划任务 | mcron服务。 | |
• 日志轮替 | rottlog服务。 | |
• 网络服务 | 网络设置,SSH后台进程,等 | |
• Unattended Upgrades | Automated system upgrades. | |
• X窗口 | 图形显示器。 | |
• 打印服务 | 本地和远程打印机的支持。 | |
• 桌面服务 | D-Bus和桌面服务。 | |
• 声音服务 | ALSA和Pulseaudio服务。 | |
• 数据库服务 | SQL数据库,键值仓库,等 | |
• 邮件服务 | IMAP,POP3,SMTP,等 | |
• 消息服务 | 消息服务。 | |
• 电话服务 | 电话服务。 | |
• File-Sharing Services | File-sharing services. | |
• 监控服务 | 监控服务。 | |
• Kerberos服务 | Kerberos服务。 | |
• LDAP Services | LDAP services. | |
• Web服务 | Web服务。 | |
• 证书服务 | Let’s Encrypt TLS证书。 | |
• DNS服务 | DNS后台进程。 | |
• VPN服务 | VPN后台进程。 | |
• 网络文件系统 | 网络文件系统相关的服务。 | |
• 持续集成 | Cuirass and Laminar services. | |
• 电源管理服务 | 延长电池寿命。 | |
• 音频服务 | MPD。 | |
• 虚拟化服务 | 虚拟化服务。 | |
• 版本控制服务 | 远程访问Git仓库。 | |
• 游戏服务 | 游戏服务器。 | |
• PAM Mount Service | Service to mount volumes when logging in. | |
• Guix Services | Services relating specifically to Guix. | |
• Linux Services | Services tied to the Linux kernel. | |
• Hurd Services | Services specific for a Hurd System. | |
• 其它各种服务 | 其它服务。 |
The (gnu services base)
module provides definitions for the basic
services that one expects from the system. The services exported by this
module are listed below.
This variable contains a list of basic services (see 服务类型和服务, for more information on service objects) one would expect from the system: a login service (mingetty) on each tty, syslogd, the libc name service cache daemon (nscd), the udev device manager, and more.
This is the default value of the services
field of
operating-system
declarations. Usually, when customizing a system,
you will want to append services to %base-services
, like this:
(append (list (service avahi-service-type)
(service openssh-service-type))
%base-services)
This is the service that sets up “special files” such as /bin/sh;
an instance of it is part of %base-services
.
The value associated with special-files-service-type
services must be
a list of tuples where the first element is the “special file” and the
second element is its target. By default it is:
`(("/bin/sh" ,(file-append bash "/bin/sh")))
If you want to add, say, /usr/bin/env
to your system, you can change
it to:
`(("/bin/sh" ,(file-append bash "/bin/sh")) ("/usr/bin/env" ,(file-append coreutils "/bin/env")))
Since this is part of %base-services
, you can use
modify-services
to customize the set of special files (see modify-services
). But the simple way to add a special
file is via the extra-special-file
procedure (see below).
Use target as the “special file” file.
For example, adding the following lines to the services
field of your
operating system declaration leads to a /usr/bin/env symlink:
(extra-special-file "/usr/bin/env"
(file-append coreutils "/bin/env"))
Return a service that sets the host name to name.
Install the given fonts on the specified ttys (fonts are per virtual console
on the kernel Linux). The value of this service is a list of tty/font
pairs. The font can be the name of a font provided by the kbd
package or any valid argument to setfont
, as in this example:
`(("tty1" . "LatGrkCyr-8x16") ("tty2" . ,(file-append font-tamzen "/share/kbd/consolefonts/TamzenForPowerline10x20.psf")) ("tty3" . ,(file-append font-terminus "/share/consolefonts/ter-132n"))) ; for HDPI
Return a service to run login according to config, a
<login-configuration>
object, which specifies the message of the day,
among other things.
This is the data type representing the configuration of login.
motd
A file-like object containing the “message of the day”.
allow-empty-passwords?
(default: #t
)Allow empty passwords by default so that first-time users can log in when the ’root’ account has just been created.
Return a service to run mingetty according to config, a
<mingetty-configuration>
object, which specifies the tty to run,
among other things.
This is the data type representing the configuration of Mingetty, which provides the default implementation of virtual console log-in.
tty
The name of the console this Mingetty runs on—e.g., "tty1"
.
auto-login
(default: #f
)When true, this field must be a string denoting the user name under which
the system automatically logs in. When it is #f
, a user name and
password must be entered to log in.
login-program
(default: #f
)This must be either #f
, in which case the default log-in program is
used (login
from the Shadow tool suite), or a gexp denoting the
name of the log-in program.
login-pause?
(default: #f
)When set to #t
in conjunction with auto-login, the user will
have to press a key before the log-in shell is launched.
clear-on-logout?
(default: #t
)When set to #t
, the screen will be cleared after logout.
mingetty
(default: mingetty)The Mingetty package to use.
Return a service to run agetty according to config, an
<agetty-configuration>
object, which specifies the tty to run, among
other things.
This is the data type representing the configuration of agetty, which
implements virtual and serial console log-in. See the agetty(8)
man
page for more information.
tty
The name of the console this agetty runs on, as a string—e.g.,
"ttyS0"
. This argument is optional, it will default to a reasonable
default serial port used by the kernel Linux.
For this, if there is a value for an option agetty.tty
in the kernel
command line, agetty will extract the device name of the serial port from it
and use that.
If not and if there is a value for an option console
with a tty in
the Linux command line, agetty will extract the device name of the serial
port from it and use that.
In both cases, agetty will leave the other serial device settings (baud rate etc.) alone—in the hope that Linux pinned them to the correct values.
baud-rate
(default: #f
)A string containing a comma-separated list of one or more baud rates, in descending order.
term
(default: #f
)A string containing the value used for the TERM
environment variable.
eight-bits?
(default: #f
)When #t
, the tty is assumed to be 8-bit clean, and parity detection
is disabled.
auto-login
(default: #f
)When passed a login name, as a string, the specified user will be logged in automatically without prompting for their login name or password.
no-reset?
(default: #f
)When #t
, don’t reset terminal cflags (control modes).
host
(default: #f
)This accepts a string containing the “login_host”, which will be written into the /var/run/utmpx file.
remote?
(default: #f
)When set to #t
in conjunction with host, this will add an
-r
fakehost option to the command line of the login program specified
in login-program.
flow-control?
(default: #f
)When set to #t
, enable hardware (RTS/CTS) flow control.
no-issue?
(default: #f
)When set to #t
, the contents of the /etc/issue file will not
be displayed before presenting the login prompt.
init-string
(default: #f
)This accepts a string that will be sent to the tty or modem before sending anything else. It can be used to initialize a modem.
no-clear?
(default: #f
)When set to #t
, agetty will not clear the screen before showing the
login prompt.
login-program
(default: (file-append shadow "/bin/login"))This must be either a gexp denoting the name of a log-in program, or unset,
in which case the default value is the login
from the Shadow tool
suite.
local-line
(default: #f
)Control the CLOCAL line flag. This accepts one of three symbols as
arguments, 'auto
, 'always
, or 'never
. If #f
,
the default value chosen by agetty is 'auto
.
extract-baud?
(default: #f
)When set to #t
, instruct agetty to try to extract the baud rate from
the status messages produced by certain types of modems.
skip-login?
(default: #f
)When set to #t
, do not prompt the user for a login name. This can be
used with login-program field to use non-standard login systems.
no-newline?
(default: #f
)When set to #t
, do not print a newline before printing the
/etc/issue file.
login-options
(default: #f
)This option accepts a string containing options that are passed to the login program. When used with the login-program, be aware that a malicious user could try to enter a login name containing embedded options that could be parsed by the login program.
login-pause
(default: #f
)When set to #t
, wait for any key before showing the login prompt.
This can be used in conjunction with auto-login to save memory by
lazily spawning shells.
chroot
(default: #f
)Change root to the specified directory. This option accepts a directory path as a string.
hangup?
(default: #f
)Use the Linux system call vhangup
to do a virtual hangup of the
specified terminal.
keep-baud?
(default: #f
)When set to #t
, try to keep the existing baud rate. The baud rates
from baud-rate are used when agetty receives a BREAK character.
timeout
(default: #f
)When set to an integer value, terminate if no user name could be read within timeout seconds.
detect-case?
(default: #f
)When set to #t
, turn on support for detecting an uppercase-only
terminal. This setting will detect a login name containing only uppercase
letters as indicating an uppercase-only terminal and turn on some
upper-to-lower case conversions. Note that this will not support Unicode
characters.
wait-cr?
(default: #f
)When set to #t
, wait for the user or modem to send a carriage-return
or linefeed character before displaying /etc/issue or login prompt.
This is typically used with the init-string option.
no-hints?
(default: #f
)When set to #t
, do not print hints about Num, Caps, and Scroll locks.
no-hostname?
(default: #f
)By default, the hostname is printed. When this option is set to #t
,
no hostname will be shown at all.
long-hostname?
(default: #f
)By default, the hostname is only printed until the first dot. When this
option is set to #t
, the fully qualified hostname by
gethostname
or getaddrinfo
is shown.
erase-characters
(default: #f
)This option accepts a string of additional characters that should be interpreted as backspace when the user types their login name.
kill-characters
(default: #f
)This option accepts a string that should be interpreted to mean “ignore all previous characters” (also called a “kill” character) when the user types their login name.
chdir
(default: #f
)This option accepts, as a string, a directory path that will be changed to before login.
delay
(default: #f
)This options accepts, as an integer, the number of seconds to sleep before opening the tty and displaying the login prompt.
nice
(default: #f
)This option accepts, as an integer, the nice value with which to run the
login
program.
extra-options
(default: '()
)This option provides an “escape hatch” for the user to provide arbitrary
command-line arguments to agetty
as a list of strings.
Return a service to run
kmscon according to
config, a <kmscon-configuration>
object, which specifies the
tty to run, among other things.
This is the data type representing the configuration of Kmscon, which implements virtual console log-in.
virtual-terminal
The name of the console this Kmscon runs on—e.g., "tty1"
.
login-program
(default: #~(string-append #$shadow "/bin/login")
)A gexp denoting the name of the log-in program. The default log-in program
is login
from the Shadow tool suite.
login-arguments
(default: '("-p")
)A list of arguments to pass to login
.
auto-login
(default: #f
)When passed a login name, as a string, the specified user will be logged in automatically without prompting for their login name or password.
hardware-acceleration?
(default: #f)Whether to use hardware acceleration.
font-engine
(default: "pango"
)Font engine used in Kmscon.
font-size
(default: 12
)Font size used in Kmscon.
kmscon
(default: kmscon)The Kmscon package to use.
daemon (nscd) with the given config—an <nscd-configuration>
object. See Name Service Switch, for an example.
For convenience, the Shepherd service for nscd provides the following actions:
invalidate
This invalidate the given cache. For instance, running:
herd invalidate nscd hosts
invalidates the host name lookup cache of nscd.
statistics
Running herd statistics nscd
displays information about nscd usage
and caches.
This is the default <nscd-configuration>
value (see below) used by
nscd-service
. It uses the caches defined by
%nscd-default-caches
; see below.
This is the data type representing the name service cache daemon (nscd) configuration.
name-services
(default: '()
)List of packages denoting name services that must be visible to the
nscd—e.g., (list nss-mdns)
.
glibc
(default: glibc)Package object denoting the GNU C Library providing the nscd
command.
log-file
(default: "/var/log/nscd.log"
)Name of the nscd log file. This is where debugging output goes when
debug-level
is strictly positive.
debug-level
(default: 0
)Integer denoting the debugging levels. Higher numbers mean that more debugging output is logged.
caches
(default: %nscd-default-caches
)List of <nscd-cache>
objects denoting things to be cached; see below.
Data type representing a cache database of nscd and its parameters.
database
This is a symbol representing the name of the database to be cached. Valid
values are passwd
, group
, hosts
, and services
,
which designate the corresponding NSS database (see NSS Basics in The GNU C Library Reference Manual).
positive-time-to-live
negative-time-to-live
(default: 20
)A number representing the number of seconds during which a positive or negative lookup result remains in cache.
check-files?
(default: #t
)Whether to check for updates of the files corresponding to database.
For instance, when database is hosts
, setting this flag
instructs nscd to check for updates in /etc/hosts and to take them
into account.
persistent?
(default: #t
)Whether the cache should be stored persistently on disk.
shared?
(default: #t
)Whether the cache should be shared among users.
max-database-size
(default: 32 MiB)Maximum size in bytes of the database cache.
List of <nscd-cache>
objects used by default by
nscd-configuration
(see above).
It enables persistent and aggressive caching of service and host name lookups. The latter provides better host name lookup performance, resilience in the face of unreliable name servers, and also better privacy—often the result of host name lookups is in local cache, so external name servers do not even need to be queried.
This data type represents the configuration of the syslog daemon.
syslogd
(default: #~(string-append #$inetutils "/libexec/syslogd")
)The syslog daemon to use.
config-file
(default: %default-syslog.conf
)The syslog configuration file to use.
Return a service that runs a syslog daemon according to config.
See syslogd invocation in GNU Inetutils, for more information on the configuration file syntax.
This is the type of the service that runs the build daemon,
guix-daemon
(see 调用guix-daemon). Its value must be a
guix-configuration
record as described below.
This data type represents the configuration of the Guix build daemon. See 调用guix-daemon, for more information.
guix
(default: guix)The Guix package to use.
build-group
(default: "guixbuild"
)Name of the group for build user accounts.
build-accounts
(default: 10
)Number of build user accounts to create.
authorize-key?
(default: #t
)Whether to authorize the substitute keys listed in
authorized-keys
—by default that of ci.guix.gnu.org
(see substitutes).
When authorize-key?
is true, /etc/guix/acl cannot be changed
by invoking guix archive --authorize
. You must instead adjust
guix-configuration
as you wish and reconfigure the system. This
ensures that your operating system configuration file is self-contained.
注: When booting or reconfiguring to a system where
authorize-key?
is true, the existing /etc/guix/acl file is backed up as /etc/guix/acl.bak if it was determined to be a manually modified file. This is to facilitate migration from earlier versions, which allowed for in-place modifications to /etc/guix/acl.
authorized-keys
(default: %default-authorized-guix-keys
)The list of authorized key files for archive imports, as a list of
string-valued gexps (see 调用guix archive). By default, it
contains that of ci.guix.gnu.org
(see substitutes).
See substitute-urls
below for an example on how to change it.
use-substitutes?
(default: #t
)Whether to use substitutes.
substitute-urls
(default: %default-substitute-urls
)The list of URLs where to look for substitutes by default.
Suppose you would like to fetch substitutes from guix.example.org
in
addition to ci.guix.gnu.org
. You will need to do two
things: (1) add guix.example.org
to substitute-urls
, and (2)
authorize its signing key, having done appropriate checks (see 授权substitute服务器。). The configuration below does exactly that:
(guix-configuration
(substitute-urls
(append (list "https://guix.example.org")
%default-substitute-urls))
(authorized-keys
(append (list (local-file "./guix.example.org-key.pub"))
%default-authorized-guix-keys)))
This example assumes that the file ./guix.example.org-key.pub
contains the public key that guix.example.org
uses to sign
substitutes.
max-silent-time
(default: 0
)timeout
(default: 0
)The number of seconds of silence and the number of seconds of activity, respectively, after which a build process times out. A value of zero disables the timeout.
log-compression
(default: 'bzip2
)The type of compression used for build logs—one of gzip
,
bzip2
, or none
.
discover?
(default: #f
)Whether to discover substitute servers on the local network using mDNS and DNS-SD.
extra-options
(default: '()
)List of extra command-line options for guix-daemon
.
log-file
(default: "/var/log/guix-daemon.log"
)File where guix-daemon
’s standard output and standard error are
written.
http-proxy
(default: #f
)The URL of the HTTP and HTTPS proxy used for downloading fixed-output derivations and substitutes.
It is also possible to change the daemon’s proxy at run time through the
set-http-proxy
action, which restarts it:
herd set-http-proxy guix-daemon http://localhost:8118
To clear the proxy settings, run:
herd set-http-proxy guix-daemon
tmpdir
(default: #f
)A directory path where the guix-daemon
will perform builds.
'()
]Run udev, which populates the /dev directory dynamically. udev
rules can be provided as a list of files through the rules variable.
The procedures udev-rule
, udev-rules-service
and
file->udev-rule
from (gnu services base)
simplify the creation
of such rule files.
The herd rules udev
command, as root, returns the name of the
directory containing all the active udev rules.
Return a udev-rule file named file-name containing the rules defined by the contents literal.
In the following example, a rule for a USB device is defined to be stored in the file 90-usb-thing.rules. The rule runs a script upon detecting a USB device with a given product identifier.
(define %example-udev-rule
(udev-rule
"90-usb-thing.rules"
(string-append "ACTION==\"add\", SUBSYSTEM==\"usb\", "
"ATTR{product}==\"Example\", "
"RUN+=\"/path/to/script\"")))
udev-service-type
with rules and account-service-type
with groups as system groups. This works by creating a singleton
service type name-udev-rules
, of which the returned service is
an instance.
Here we show how it can be used to extend udev-service-type
with the
previously defined rule %example-udev-rule
.
(operating-system
;; …
(services
(cons (udev-rules-service 'usb-thing %example-udev-rule)
%desktop-services)))
Return a udev file named file-name containing the rules defined within file, a file-like object.
The following example showcases how we can use an existing rule file.
(use-modules (guix download) ;for url-fetch (guix packages) ;for origin …) (define %android-udev-rules (file->udev-rule "51-android-udev.rules" (let ((version "20170910")) (origin (method url-fetch) (uri (string-append "https://raw.githubusercontent.com/M0Rf30/" "android-udev-rules/" version "/51-android.rules")) (sha256 (base32 "0lmmagpyb6xsq6zcr2w1cyx9qmjqmajkvrdbhjx32gqf1d9is003"))))))
Additionally, Guix package definitions can be included in rules in
order to extend the udev rules with the definitions found under their
lib/udev/rules.d sub-directory. In lieu of the previous
file->udev-rule example, we could have used the
android-udev-rules package which exists in Guix in the (gnu
packages android)
module.
The following example shows how to use the android-udev-rules package
so that the Android tool adb
can detect devices without root
privileges. It also details how to create the adbusers
group, which
is required for the proper functioning of the rules defined within the
android-udev-rules
package. To create such a group, we must define
it both as part of the supplementary-groups
of our
user-account
declaration, as well as in the groups of the
udev-rules-service
procedure.
(use-modules (gnu packages android) ;for android-udev-rules (gnu system shadow) ;for user-group …) (operating-system ;; … (users (cons (user-account ;; … (supplementary-groups '("adbusers" ;for adb "wheel" "netdev" "audio" "video"))))) ;; … (services (cons (udev-rules-service 'android android-udev-rules #:groups '("adbusers")) %desktop-services)))
Save some entropy in %random-seed-file
to seed /dev/urandom
when rebooting. It also tries to seed /dev/urandom from
/dev/hwrng while booting, if /dev/hwrng exists and is
readable.
This is the name of the file where some random bytes are saved by urandom-seed-service to seed /dev/urandom when rebooting. It defaults to /var/lib/random-seed.
This is the type of the service that runs GPM, the general-purpose mouse daemon, which provides mouse support to the Linux console. GPM allows users to use the mouse in the console, notably to select, copy, and paste text.
The value for services of this type must be a gpm-configuration
(see
below). This service is not part of %base-services
.
Data type representing the configuration of GPM.
options
(default: %default-gpm-options
)Command-line options passed to gpm
. The default set of options
instruct gpm
to listen to mouse events on /dev/input/mice.
See Command Line in gpm manual, for more information.
gpm
(default: gpm
)The GPM package to use.
This is the service type for guix publish
(see 调用guix publish). Its value must be a guix-publish-configuration
object, as
described below.
This assumes that /etc/guix already contains a signing key pair as
created by guix archive --generate-key
(see 调用guix archive). If that is not the case, the service will fail to start.
Data type representing the configuration of the guix publish
service.
guix
(default: guix
)The Guix package to use.
port
(default: 80
)The TCP port to listen for connections.
host
(default: "localhost"
)The host (and thus, network interface) to listen to. Use "0.0.0.0"
to listen on all the network interfaces.
advertise?
(default: #f
)When true, advertise the service on the local network via the DNS-SD protocol, using Avahi.
This allows neighboring Guix devices with discovery on (see
guix-configuration
above) to discover this guix publish
instance and to automatically download substitutes from it.
compression
(default: '(("gzip" 3) ("zstd" 3))
)This is a list of compression method/level tuple used when compressing substitutes. For example, to compress all substitutes with both lzip at level 7 and gzip at level 9, write:
'(("lzip" 7) ("gzip" 9))
Level 9 achieves the best compression ratio at the expense of increased CPU usage, whereas level 1 achieves fast compression. See 调用guix publish, for more information on the available compression methods and the tradeoffs involved.
An empty list disables compression altogether.
nar-path
(default: "nar"
)The URL path at which “nars” can be fetched. See --nar-path, for details.
cache
(default: #f
)When it is #f
, disable caching and instead generate archives on
demand. Otherwise, this should be the name of a directory—e.g.,
"/var/cache/guix/publish"
—where guix publish
caches
archives and meta-data ready to be sent. See --cache, for more information on the tradeoffs involved.
workers
(default: #f
)When it is an integer, this is the number of worker threads used for
caching; when #f
, the number of processors is used. See --workers, for more information.
cache-bypass-threshold
(default: 10 MiB)When cache
is true, this is the maximum size in bytes of a store item
for which guix publish
may bypass its cache in case of a cache
miss. See --cache-bypass-threshold, for
more information.
ttl
(default: #f
)When it is an integer, this denotes the time-to-live in seconds of the published archives. See --ttl, for more information.
rngd
program from rng-tools to add device to the kernel’s entropy pool. The service will fail if device does not exist.
'()
]Return a service that installs a configuration file for the
pam_limits
module. The procedure optionally takes a list of
pam-limits-entry
values, which can be used to specify ulimit
limits and nice
priority limits to user sessions.
The following limits definition sets two hard and soft limits for all login
sessions of users in the realtime
group:
(pam-limits-service
(list
(pam-limits-entry "@realtime" 'both 'rtprio 99)
(pam-limits-entry "@realtime" 'both 'memlock 'unlimited)))
The first entry increases the maximum realtime priority for non-privileged processes; the second entry lifts any restriction of the maximum address space that can be locked in memory. These settings are commonly used for real-time audio systems.
Another useful example is raising the maximum number of open file descriptors that can be used:
(pam-limits-service
(list
(pam-limits-entry "*" 'both 'nofile 100000)))
In the above example, the asterisk means the limit should apply to any
user. It is important to ensure the chosen value doesn’t exceed the maximum
system value visible in the /proc/sys/fs/file-max file, else the
users would be prevented from login in. For more information about the
Pluggable Authentication Module (PAM) limits, refer to the ‘pam_limits’
man page from the linux-pam
package.
The (gnu services mcron)
module provides an interface to
GNU mcron, a daemon to run jobs at scheduled times (see GNU mcron). GNU mcron is similar to the traditional Unix
cron
daemon; the main difference is that it is implemented in
Guile Scheme, which provides a lot of flexibility when specifying the
scheduling of jobs and their actions.
The example below defines an operating system that runs the
updatedb
(see Invoking updatedb in Finding Files) and
the guix gc
commands (see 调用guix gc) daily, as well as
the mkid
command on behalf of an unprivileged user (see mkid invocation in ID Database Utilities). It uses gexps to introduce
job definitions that are passed to mcron (see G-表达式).
(use-modules (guix) (gnu) (gnu services mcron)) (use-package-modules base idutils) (define updatedb-job ;; Run 'updatedb' at 3AM every day. Here we write the ;; job's action as a Scheme procedure. #~(job '(next-hour '(3)) (lambda () (execl (string-append #$findutils "/bin/updatedb") "updatedb" "--prunepaths=/tmp /var/tmp /gnu/store")))) (define garbage-collector-job ;; Collect garbage 5 minutes after midnight every day. ;; The job's action is a shell command. #~(job "5 0 * * *" ;Vixie cron syntax "guix gc -F 1G")) (define idutils-job ;; Update the index database as user "charlie" at 12:15PM ;; and 19:15PM. This runs from the user's home directory. #~(job '(next-minute-from (next-hour '(12 19)) '(15)) (string-append #$idutils "/bin/mkid src") #:user "charlie")) (operating-system ;; … ;; %BASE-SERVICES already includes an instance of ;; 'mcron-service-type', which we extend with additional ;; jobs using 'simple-service'. (services (cons (simple-service 'my-cron-jobs mcron-service-type (list garbage-collector-job updatedb-job idutils-job)) %base-services)))
For more complex jobs defined in Scheme where you need control over the top
level, for instance to introduce a use-modules
form, you can move
your code to a separate program using the program-file
procedure of
the (guix gexp)
module (see G-表达式). The example below
illustrates that.
(define %battery-alert-job
;; Beep when the battery percentage falls below %MIN-LEVEL.
#~(job
'(next-minute (range 0 60 1))
#$(program-file
"battery-alert.scm"
(with-imported-modules (source-module-closure
'((guix build utils)))
#~(begin
(use-modules (guix build utils)
(ice-9 popen)
(ice-9 regex)
(ice-9 textual-ports)
(srfi srfi-2))
(define %min-level 20)
(setenv "LC_ALL" "C") ;ensure English output
(and-let* ((input-pipe (open-pipe*
OPEN_READ
#$(file-append acpi "/bin/acpi")))
(output (get-string-all input-pipe))
(m (string-match "Discharging, ([0-9]+)%" output))
(level (string->number (match:substring m 1)))
((< level %min-level)))
(format #t "warning: Battery level is low (~a%)~%" level)
(invoke #$(file-append beep "/bin/beep") "-r5")))))))
See mcron job specifications in GNU mcron, for more information on mcron job specifications. Below is the reference of the mcron service.
On a running system, you can use the schedule
action of the service
to visualize the mcron jobs that will be executed next:
# herd schedule mcron
The example above lists the next five tasks that will be executed, but you can also specify the number of tasks to display:
# herd schedule mcron 10
This is the type of the mcron
service, whose value is an
mcron-configuration
object.
This service type can be the target of a service extension that provides it additional job specifications (see 合成服务). In other words, it is possible to define services that provide additional mcron jobs to run.
Data type representing the configuration of mcron.
mcron
(default: mcron)The mcron package to use.
jobs
This is a list of gexps (see G-表达式), where each gexp corresponds to an mcron job specification (see mcron job specifications in GNU mcron).
Log files such as those found in /var/log tend to grow endlessly, so
it’s a good idea to rotate them once in a while—i.e., archive their
contents in separate files, possibly compressed. The (gnu services
admin)
module provides an interface to GNU Rot[t]log, a log rotation
tool (see GNU Rot[t]log Manual).
This service is part of %base-services
, and thus enabled by default,
with the default settings, for commonly encountered log files. The example
below shows how to extend it with an additional rotation, should you
need to do that (usually, services that produce log files already take care
of that):
(use-modules (guix) (gnu)) (use-service-modules admin) (define my-log-files ;; Log files that I want to rotate. '("/var/log/something.log" "/var/log/another.log")) (operating-system ;; … (services (cons (simple-service 'rotate-my-stuff rottlog-service-type (list (log-rotation (frequency 'daily) (files my-log-files)))) %base-services)))
This is the type of the Rottlog service, whose value is a
rottlog-configuration
object.
Other services can extend this one with new log-rotation
objects (see
below), thereby augmenting the set of files to be rotated.
This service type can define mcron jobs (see 执行计划任务) to run the rottlog service.
Data type representing the configuration of rottlog.
rottlog
(default: rottlog
)The Rottlog package to use.
rc-file
(default: (file-append rottlog "/etc/rc")
)The Rottlog configuration file to use (see Mandatory RC Variables in GNU Rot[t]log Manual).
rotations
(default: %default-rotations
)A list of log-rotation
objects as defined below.
jobs
This is a list of gexps where each gexp corresponds to an mcron job specification (see 执行计划任务).
Data type representing the rotation of a group of log files.
Taking an example from the Rottlog manual (see Period Related File Examples in GNU Rot[t]log Manual), a log rotation might be defined like this:
(log-rotation
(frequency 'daily)
(files '("/var/log/apache/*"))
(options '("storedir apache-archives"
"rot