源替换

本文档是关于替换 crate 索引的。您可以在本文档的覆盖依赖项章节中了解有关覆盖依赖项的信息。

一个是一个提供者,其中包含可以作为包的依赖项的 crate。Cargo 支持将一个源替换为另一个源,以表达以下策略,例如

  • 供应商化 — 可以定义自定义源,这些源表示本地文件系统上的 crate。这些源是它们所替换的源的子集,并且可以在必要时检入包中。

  • 镜像 — 源可以用等效版本替换,该版本充当 crates.io 本身的缓存。

Cargo 对源替换有一个核心假设,即来自两个源的源代码是完全相同的。请注意,这也意味着不允许替换源包含原始源中不存在的 crate。

因此,源替换不适用于诸如修补依赖项或私有注册表的情况。Cargo 支持通过使用 [patch]来修补依赖项,并且在 注册表章节中描述了私有注册表支持。

使用源替换时,运行诸如 cargo publish 之类的需要联系注册表的命令时,需要传递 --registry 选项。这有助于避免关于联系哪个注册表的任何歧义,并将使用指定注册表的身份验证令牌。

配置

替换源的配置通过 .cargo/config.toml 完成,完整的可用键集是

# The `source` table is where all keys related to source-replacement
# are stored.
[source]

# Under the `source` table are a number of other tables whose keys are a
# name for the relevant source. For example this section defines a new
# source, called `my-vendor-source`, which comes from a directory
# located at `vendor` relative to the directory containing this `.cargo/config.toml`
# file
[source.my-vendor-source]
directory = "vendor"

# The crates.io default source for crates is available under the name
# "crates-io", and here we use the `replace-with` key to indicate that it's
# replaced with our source above.
#
# The `replace-with` key can also reference an alternative registry name
# defined in the `[registries]` table.
[source.crates-io]
replace-with = "my-vendor-source"

# Each source has its own table where the key is the name of the source
[source.the-source-name]

# Indicate that `the-source-name` will be replaced with `another-source`,
# defined elsewhere
replace-with = "another-source"

# Several kinds of sources can be specified (described in more detail below):
registry = "https://example.com/path/to/index"
local-registry = "path/to/registry"
directory = "path/to/vendor"

# Git sources can optionally specify a branch/tag/rev as well
git = "https://example.com/path/to/repo"
# branch = "master"
# tag = "v1.0.1"
# rev = "313f44e8"

注册表源

“注册表源”与 crates.io 本身相同。也就是说,它有一个在 git 仓库中提供的索引,其格式与 crates.io 索引的格式相匹配。然后,该仓库具有配置,指示从哪里下载 crate。

目前还没有用于设置 crates.io 镜像的现有项目。敬请关注!

本地注册表源

“本地注册表源”旨在成为另一个注册表源的子集,但在本地文件系统上可用(又名供应商化)。本地注册表会提前下载,通常与 Cargo.lock 同步,并由一组 *.crate 文件和像正常注册表一样的索引组成。

管理和创建本地注册表源的主要方法是通过 cargo-local-registry 子命令,可在 crates.io 上获取,并且可以使用 cargo install cargo-local-registry 安装。

本地注册表包含在一个目录中,其中包含从 crates.io 下载的许多 *.crate 文件,以及一个与 crates.io-index 项目格式相同的 index 目录(仅填充存在 crate 的条目)。

目录源

“目录源”类似于本地注册表源,它包含本地文件系统上可用的大量 crate,适用于供应商化依赖项。目录源主要由 cargo vendor 子命令管理。

目录源与本地注册表不同,因为它们包含 *.crate 文件的解压缩版本,这使得在某些情况下更适合将所有内容检入源代码控制。目录源只是一个目录,其中包含许多其他目录,这些目录包含 crate 的源代码(*.crate 文件的解压缩版本)。目前,对每个目录的名称没有限制。

目录源中的每个 crate 还具有一个关联的元数据文件,指示 crate 中每个文件的校验和,以防止意外修改。