源替换
本文档介绍如何替换 crate 索引。你可以在本文档的覆盖依赖项部分了解有关覆盖依赖项的信息。
一个源(source)是提供者,包含可以作为包的依赖项的 crate。Cargo 支持将一个源替换为另一个源,以实现以下策略:
-
Vendoring(本地化):可以定义自定义源,表示本地文件系统上的 crate。这些源是它们所替换源的子集,如果需要,可以将其检入到包中。
-
Mirroring(镜像):源可以被替换为一个等价的版本,该版本充当 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"
仓库源(Registry Sources)
“仓库源”是与 crates.io 本身相同的源。也就是说,它有一个通过 git 仓库提供的索引,该索引的格式与crates.io 索引匹配。该仓库随后包含指示从何处下载 crate 的配置。
目前还没有现成的项目用于设置 crates.io 的镜像。敬请关注!
本地仓库源(Local Registry Sources)
“本地仓库源”旨在成为另一个仓库源的子集,但在本地文件系统上可用(即 vendoring)。本地仓库会提前下载,通常与 Cargo.lock 同步,由一组 *.crate 文件和一个像普通仓库一样的索引组成。
管理和创建本地仓库源的主要方式是通过 cargo-local-registry 子命令,该命令可在 crates.io 上找到,并可以使用 cargo install cargo-local-registry 安装。
本地仓库包含在一个目录中,并包含许多从 crates.io 下载的 *.crate 文件以及一个 index 目录,该目录的格式与 crates.io-index 项目相同(仅包含存在的 crate 的条目)。
目录源(Directory Sources)
“目录源”类似于本地仓库源,它包含本地文件系统上可用的许多 crate,适用于 vendoring 依赖项。目录源主要由 cargo vendor 子命令管理。
然而,目录源与本地仓库的不同之处在于,它们包含 *.crate 文件的解压版本,这使得在某些情况下更适合将所有内容检入到源代码控制中。目录源只是一个包含许多其他目录的目录,这些目录包含 crate 的源代码(*.crate 文件的解压版本)。目前对每个目录的名称没有限制。
目录源中的每个 crate 还都有一个相关的元数据文件,指示 crate 中每个文件的校验和,以防止意外修改。