在Debian系统上,首先需要安装Rust工具链和CI所需的辅助工具。打开终端,执行以下命令:
# 更新系统包列表
sudo apt update
# 安装curl(用于下载rustup)、build-essential(编译依赖)、git(版本控制)
sudo apt install -y curl build-essential git
# 使用rustup安装Rust(默认安装stable版本)
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- --no-modify-path -y
# 配置环境变量(使rustc/cargo全局可用)
echo 'export PATH="$HOME/.cargo/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc
# 验证安装
rustc --version # 应输出Rust编译器版本
cargo --version # 应输出Cargo包管理器版本
以上步骤确保系统具备Rust开发能力,是后续CI配置的基础。
主流CI工具(如GitHub Actions、GitLab CI)均支持Debian环境。以下以GitHub Actions(最常用)为例,说明配置流程:
.github/workflows目录(若不存在则新建)。rust-ci.yml文件,内容如下:name: Rust CI
on:
push: # 当代码推送到main分支时触发
branches: [ main ]
pull_request: # 当提交pull request到main分支时触发
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest # 使用GitHub提供的最新Ubuntu虚拟机
steps:
# 1. 检出代码
- uses: actions/checkout@v2
# 2. 安装Rust(指定stable版本)
- name: Install Rust
run: rustup default stable
# 3. 编译项目(debug模式)
- name: Build
run: cargo build --verbose
# 4. 运行单元测试
- name: Run tests
run: cargo test --verbose
# 5. 检查代码格式(需项目已配置rustfmt)
- name: Check formatting
run: cargo fmt -- --check
# 6. 检查代码风格(需项目已配置clippy)
- name: Check clippy
run: cargo clippy -- -D warnings
该配置实现了自动触发、依赖安装、编译、测试、代码质量检查的完整CI流程。Rust的依赖下载和编译耗时较长,可通过缓存~/.cargo目录加速后续构建。修改rust-ci.yml,在steps中添加缓存步骤:
- name: Cache cargo registry
uses: actions/cache@v3
with:
path: ~/.cargo/registry
key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}
restore-keys: |
${{ runner.os }}-cargo-registry-
- name: Cache cargo index
uses: actions/cache@v3
with:
path: ~/.cargo/git
key: ${{ runner.os }}-cargo-index-${{ hashFiles('**/Cargo.lock') }}
restore-keys: |
${{ runner.os }}-cargo-index-
缓存机制可将依赖下载时间从几分钟缩短至几秒,显著提升CI效率。
若需将Rust项目打包为Debian格式(.deb),可使用cargo-deb工具。步骤如下:
cargo-deb:cargo install cargo-deb
cargo deb --no-build # 输出到target/debian/目录,默认包名格式为<项目名>_<版本>-1_<架构>.deb
dpkg安装:scp target/debian/*.deb user@your_server:/tmp/
ssh user@your_server
sudo dpkg -i /tmp/your_project_*.deb # 安装包
sudo apt-get install -f # 修复依赖(若有缺失)
生成的.deb包可通过CI流程自动上传至服务器,实现自动化部署。将rust-ci.yml文件提交至GitHub仓库并推送:
git add .github/workflows/rust-ci.yml
git commit -m "Add Rust CI workflow"
git push origin main
推送后,前往GitHub仓库的Actions标签页,即可查看CI运行状态。若所有步骤通过,说明CI环境搭建成功。
libssl-dev),需在CI配置中通过sudo apt-get install -y libssl-dev预装。runs-on为对应镜像(如ubuntu-22.04-arm64)或使用Docker镜像。Deploy to Production步骤,例如使用scp复制二进制文件或调用Ansible自动化部署。