Cargo 发布包 #

发布概述 #

crates.io 是 Rust 的官方包仓库,类似于 npm 的 npmjs.com 或 Python 的 PyPI。本节将详细介绍如何将你的 Rust 包发布到 crates.io

发布流程 #

text
发布流程
├── 1. 准备工作
│   ├── 注册账号
│   ├── 配置 Cargo.toml
│   └── 编写文档
├── 2. 发布前检查
│   ├── 运行测试
│   ├── 检查文档
│   └── 验证包内容
├── 3. 发布
│   ├── 登录
│   ├── 打包
│   └── 发布
└── 4. 发布后
    ├── 版本管理
    ├── 废弃处理
    └── 维护更新

注册账号 #

创建 crates.io 账号 #

  1. 访问 https://crates.io/
  2. 使用 GitHub 账号登录
  3. 授权 crates.io 访问

获取 API Token #

  1. 登录 crates.io
  2. 进入 Account Settings → API Tokens
  3. 创建新的 API Token

登录 Cargo #

bash
# 使用 token 登录
cargo login

# 或直接指定 token
cargo login <your-api-token>

登录信息保存在 ~/.cargo/credentials 文件中。

准备发布 #

Cargo.toml 配置 #

发布前需要完善 Cargo.toml 配置:

toml
[package]
name = "my_awesome_lib"
version = "0.1.0"
edition = "2021"
description = "A short description of my package"
documentation = "https://docs.rs/my_awesome_lib"
homepage = "https://myproject.com"
repository = "https://github.com/user/my_awesome_lib"
license = "MIT OR Apache-2.0"
keywords = ["rust", "library", "awesome"]
categories = ["development-tools", "rust-patterns"]
readme = "README.md"
authors = ["Your Name <you@example.com>"]

[dependencies]
# ...

必需字段 #

字段 描述 示例
name 包名 my_lib
version 版本号 0.1.0
edition Rust 版本 2021
description 描述 "A library"
license 许可证 "MIT"

推荐字段 #

字段 描述 示例
documentation 文档 URL "https://docs.rs/my_lib"
repository 仓库 URL "https://github.com/user/my_lib"
readme README 文件 "README.md"
keywords 关键词 ["rust", "lib"]
categories 分类 ["development-tools"]

许可证选择 #

toml
# 常用许可证
license = "MIT"
license = "Apache-2.0"
license = "MIT OR Apache-2.0"    # 双许可
license = "GPL-3.0"
license = "BSD-3-Clause"
license = "MPL-2.0"
license = "ISC"
license = "Unlicense"

编写 README #

markdown
# my_awesome_lib

A short description of what this library does.

## Installation

Add this to your `Cargo.toml`:

```toml
[dependencies]
my_awesome_lib = "0.1"

Usage #

rust
use my_awesome_lib::some_function;

fn main() {
    some_function();
}

Features #

  • Feature 1
  • Feature 2

License #

Licensed under either of Apache License, Version 2.0 or MIT license at your option.

text

### 编写文档

```rust
//! # My Awesome Library
//!
//! `my_awesome_lib` is a collection of utilities to make performing certain
//! calculations more convenient.
//!
//! ## Examples
//!
//! ```
//! use my_awesome_lib::add;
//!
//! let result = add(2, 3);
//! assert_eq!(result, 5);
//! ```

/// Adds two numbers together.
///
/// # Examples
///
/// ```
/// use my_awesome_lib::add;
///
/// let result = add(1, 2);
/// assert_eq!(result, 3);
/// ```
///
/// # Panics
///
/// Panics if the result overflows.
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

发布前检查 #

运行测试 #

bash
# 运行所有测试
cargo test

# 运行文档测试
cargo test --doc

# 运行 clippy
cargo clippy

# 检查格式
cargo fmt --check

检查文档 #

bash
# 生成文档
cargo doc

# 打开文档
cargo doc --open

# 检查文档链接
cargo doc --document-private-items

验证包内容 #

bash
# 查看将要发布的文件
cargo package --list

# 打包(不发布)
cargo package

# 查看打包内容
tar -tzf target/package/my_lib-0.1.0.crate

控制发布内容 #

toml
# Cargo.toml

# 包含的文件
include = [
    "src/**/*",
    "Cargo.toml",
    "README.md",
    "LICENSE",
]

# 排除的文件
exclude = [
    "tests/*",
    "examples/*",
    "docs/*",
    "*.bak",
]

发布包 #

发布命令 #

bash
# 发布到 crates.io
cargo publish

# 发布前验证(不实际发布)
cargo publish --dry-run

# 发布特定包(工作区)
cargo publish -p my_lib

# 发布到特定注册表
cargo publish --registry my-registry

发布流程 #

text
1. 验证 Cargo.toml
   ↓
2. 检查包名是否可用
   ↓
3. 打包源代码
   ↓
4. 上传到 crates.io
   ↓
5. 索引更新
   ↓
6. 文档生成(docs.rs)

发布后验证 #

bash
# 搜索包
cargo search my_lib

# 查看包信息
cargo show my_lib

# 安装测试
cargo install my_lib

版本管理 #

语义化版本 #

text
MAJOR.MINOR.PATCH

MAJOR: 不兼容的 API 变更
MINOR: 向后兼容的功能新增
PATCH: 向后兼容的 bug 修复

版本更新 #

bash
# 更新补丁版本(0.1.0 → 0.1.1)
cargo install cargo-release
cargo release patch

# 或手动更新 Cargo.toml 中的 version

# 发布新版本
cargo publish

预发布版本 #

toml
[package]
version = "1.0.0-alpha.1"
version = "1.0.0-beta.2"
version = "1.0.0-rc.1"
bash
# 发布预发布版本
cargo publish

版本废弃 #

bash
# 废弃特定版本
cargo yank --vers 1.0.0

# 取消废弃
cargo yank --vers 1.0.0 --undo

⚠️ 注意:yank 不会删除代码,只是阻止新项目使用该版本。

包管理 #

添加所有者 #

bash
# 添加所有者
cargo owner --add username

# 移除所有者
cargo owner --remove username

# 列出所有者
cargo owner --list

团队管理 #

bash
# 添加 GitHub 团队
cargo owner --add github:org:team

私有注册表 #

配置私有注册表 #

toml
# .cargo/config.toml
[registries]
my-registry = { index = "https://my-registry.com/index" }

发布到私有注册表 #

bash
# 登录私有注册表
cargo login --registry my-registry

# 发布到私有注册表
cargo publish --registry my-registry

文档托管 #

docs.rs #

发布到 crates.io 的包会自动在 docs.rs 生成文档:

  • URL: https://docs.rs/<package_name>
  • URL: https://docs.rs/<package_name>/<version>

自定义文档配置 #

toml
[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]

文档特性 #

rust
/// # Example
///
/// ```
/// use my_lib::some_function;
///
/// some_function();
/// ```
///
/// # Feature Flags
///
/// - `feature1`: Description
/// - `feature2`: Description
#[cfg(feature = "feature1")]
pub fn some_function() {}

发布最佳实践 #

1. 完善的文档 #

rust
//! # Library Name
//!
//! ## Overview
//!
//! Detailed description of the library.
//!
//! ## Features
//!
//! - Feature 1
//! - Feature 2
//!
//! ## Getting Started
//!
//! ```rust
//! use my_lib::function;
//!
//! function();
//! ```

/// Function description.
///
/// # Arguments
///
/// * `arg1` - Description of arg1
///
/// # Returns
///
/// Description of return value.
///
/// # Examples
///
/// ```
/// use my_lib::function;
///
/// let result = function(42);
/// ```
///
/// # Errors
///
/// Description of possible errors.
///
/// # Panics
///
/// Description of panic conditions.
pub fn function(arg1: i32) -> Result<i32, Error> {
    // ...
}

2. 变更日志 #

markdown
# Changelog

All notable changes to this project will be documented in this file.

## [0.2.0] - 2024-01-15

### Added
- New feature X

### Changed
- Improved Y

### Fixed
- Bug Z

## [0.1.0] - 2024-01-01

### Added
- Initial release

3. CI/CD 配置 #

yaml
# .github/workflows/publish.yml
name: Publish

on:
  push:
    tags:
      - 'v*'

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
      - name: Publish
        run: cargo publish --token ${{ secrets.CARGO_TOKEN }}

4. 版本策略 #

toml
# 0.x.x 版本:快速迭代
version = "0.1.0"  # 初始版本
version = "0.2.0"  # 新功能
version = "0.2.1"  # Bug 修复

# 1.x.x 版本:稳定 API
version = "1.0.0"  # 正式版
version = "1.1.0"  # 新功能
version = "1.1.1"  # Bug 修复
version = "2.0.0"  # 破坏性变更

常见问题 #

1. 包名已存在 #

bash
# 错误:crate name already exists
# 解决:更换包名或联系所有者

2. 文档生成失败 #

bash
# 检查文档
cargo doc

# 修复文档错误后重新发布

3. 发布失败 #

bash
# 检查网络
# 检查 token 是否有效
cargo login

# 使用 dry-run 检查
cargo publish --dry-run

4. 版本冲突 #

bash
# 错误:version already exists
# 解决:更新版本号

发布检查清单 #

markdown
## 发布前检查

- [ ] 更新版本号
- [ ] 更新 CHANGELOG.md
- [ ] 运行所有测试
- [ ] 运行 clippy
- [ ] 检查格式
- [ ] 检查文档
- [ ] 验证包内容
- [ ] 检查 README
- [ ] 检查许可证
- [ ] 检查依赖版本
- [ ] 运行 cargo publish --dry-run

下一步 #

掌握发布流程后,继续学习 高级特性 了解 Cargo 的高级功能!

最后更新:2026-03-28