入门 The Cargo Team 2026-09-13 15:48:21 · 0 阅读
第23章 Package ID 规范
Package ID 规范
Cargo 的子命令经常需要在依赖图中引用某个特定的包,用于更新、清理、构建等各种操作。为此,Cargo 支持 Package ID 规范(Package ID Specifications)。规范是一个字符串,用来在包的依赖图中唯一地指代某一个包。
规范可以是完全限定的形式,比如 registry+https://github.com/rust-lang/crates.io-index#regex@1.4.3,也可以是简写形式,比如 regex。只要简写能在依赖图中唯一确定一个包,就可以使用。如果有歧义,可以补充更多限定条件来区分。例如图中存在两个版本的 regex 包,就可以加上版本号来唯一指定,如 regex@1.4.3。
Cargo 输出的 Package ID 规范,比如 cargo metadata 的输出,都是完全限定的形式。
规范语法
Package ID 规范的正式语法如下:
spec := pkgname |
[ kind "+" ] proto "://" hostname-and-path [ "?" query] [ "#" ( pkgname | semver ) ]
query = ( "branch" | "tag" | "rev" ) "=" ref
pkgname := name [ ("@" | ":" ) semver ]
semver := digits [ "." digits [ "." digits [ "-" prerelease ] [ "+" build ]]]
kind = "registry" | "git" | "path"
proto := "http" | "git" | "file" | ...
其中方括号表示内容可选。
URL 形式可用于 git 依赖,也可用于区分来自不同源的包,比如不同的 registry。
规范示例
以下是对 crates.io 上 regex 包的各种引用方式:
| 规范 | 名称 | 版本 |
|---|---|---|
regex | regex | * |
regex@1.4 | regex |
1.4.* |
regex@1.4.3 | regex | 1.4.3 |
https://github.com/rust-lang/crates.io-index#regex | regex | * |
https://github.com/rust-lang/crates.io-index#regex@1.4.3 | regex | 1.4.3 |
registry+https://github.com/rust-lang/crates.io-index#regex@1.4.3 | regex | 1.4.3 |
以下是几种不同 git 依赖的规格示例:
| Spec | 名称 | 版本 |
|---|---|---|
https://github.com/rust-lang/cargo#0.52.0 | cargo | 0.52.0 |
https://github.com/rust-lang/cargo#cargo-platform@0.1.2 | cargo-platform | 0.1.2 |
ssh://git@github.com/rust-lang/regex.git#regex@1.4.3 | regex | 1.4.3 |
git+ssh://git@github.com/rust-lang/regex.git#regex@1.4.3 | regex | 1.4.3 |
git+ssh://git@github.com/rust-lang/regex.git?branch=dev#regex@1.4.3 | regex | 1.4.3 |
可以使用 file:// URL 引用文件系统中的本地包:
| 规范 | 名称 | 版本 |
|---|---|---|
file:///path/to/my/project/foo | foo | * |
file:///path/to/my/project/foo#1.1.8 | foo | 1.1.8 |
path+file:///path/to/my/project/foo#1.1.8 | foo | 1.1.8 |
规范的简洁性
其目的是在依赖图中引用软件包时,既支持简洁的语法,也支持详尽的语法。含糊不清的引用可能指代一个或多个软件包。如果同一个规范能指向多个软件包,大多数命令都会报错。