Rust GitHub API集成库octorust的使用,octorust提供高效的GitHub数据交互与仓库管理功能
Rust GitHub API集成库octorust的使用
octorust
是一个为GitHub生成的、有主见的API客户端库,提供了高效的GitHub数据交互与仓库管理功能。
API详情
该库基于GitHub的v3 REST API开发。
安装
在项目中添加依赖:
[dependencies]
octorust = "0.10.0"
tokio = { version = "1.0", features = ["full"] }
完整示例
下面是一个扩展的完整示例,展示如何使用octorust库进行更丰富的GitHub操作:
use octorust::{auth::Credentials, Client};
use octorust::repos::ReposHandler;
use octorust::issues::IssuesHandler;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// 1. 创建GitHub客户端
let github = Client::new(
String::from("my-github-app"),
Credentials::Token(String::from("your-personal-access-token")),
);
// 2. 获取仓库信息
let repo = github.repos().get("rust-lang", "rust").await?;
println!("Repository: {}", repo.name);
println!("Description: {}", repo.description.unwrap_or_default());
println!("Stars: {}", repo.stargazers_count.unwrap_or(0));
// 3. 获取仓库的issues
let issues = github.issues()
.list_for_repo("rust-lang", "rust")
.state("open")
.per_page(5)
.send()
.await?;
println!("\n最近5个open状态的issue:");
for issue in issues {
println!("- #{}: {}", issue.number, issue.title);
}
// 4. 创建新issue
/*
let new_issue = github.issues()
.create("your-username", "your-repo", &CreateIssue {
title: String::from("Test issue from octorust"),
body: Some(String::from("This is a test issue created using octorust")),
assignee: None,
assignees: None,
milestone: None,
labels: None,
})
.await?;
println!("Created new issue: {}", new_issue.html_url);
*/
Ok(())
}
这个扩展示例展示了:
- 创建GitHub API客户端
- 获取指定仓库的基本信息
- 查询仓库的最近5个open状态的issue
- 注释掉的创建新issue的代码(取消注释并替换your-username/your-repo后可用)
要运行这个示例,你需要:
- 有效的GitHub个人访问令牌
- 将"your-personal-access-token"替换为你的令牌
- 对于创建issue操作,需要取消注释并替换为你的用户名和仓库名
更多功能
octorust还支持以下操作:
- 管理pull requests
- 处理仓库分支
- 操作GitHub Actions工作流
- 管理组织和团队
- 处理GitHub Packages
注意事项
- GitHub API有速率限制,请合理控制请求频率
- 敏感信息如访问令牌应通过环境变量管理
- 生产环境建议启用httpcache功能减少API调用
1 回复
octorust: Rust的GitHub API集成库
概述
octorust是一个Rust库,提供了与GitHub API交互的高效接口,简化了GitHub数据获取和仓库管理操作。它封装了GitHub REST API v3,提供类型安全的Rust接口,支持异步操作。
主要特性
- 完整的GitHub API覆盖(仓库、问题、PRs、用户等)
- 类型安全的请求和响应
- 异步/await支持
- 分页支持
- 自定义请求构建
安装
在Cargo.toml中添加依赖:
[dependencies]
octorust = "0.2"
tokio = { version = "1.0", features = ["full"] }
基本使用方法
1. 创建客户端
use octorust::Client;
#[tokio::main]
async fn main() {
let user_agent = "my-github-app/1.0";
let token = std::env::var("GITHUB_TOKEN").expect("GITHUB_TOKEN not set");
let client = Client::new(user_agent, token).unwrap();
}
2. 获取仓库信息
async fn get_repo_info(client: &Client) {
let owner = "rust-lang";
let repo = "rust";
match client.repos().get(owner, repo).await {
Ok(repository) => {
println!("Repository: {}", repository.name);
println!("Description: {:?}", repository.description);
println!("Stars: {}", repository.stargazers_count.unwrap_or(0));
}
Err(e) => eprintln!("Error: {}", e),
}
}
3. 创建Issue
async fn create_issue(client: &Client) {
let owner = "your-username";
let repo = "your-repo";
let issue = octorust::types::IssuesCreateRequest {
title: "Test issue".to_string(),
body: Some("This is a test issue created with octorust".to_string()),
assignee: None,
assignees: None,
milestone: None,
labels: None,
};
match client.issues().create(owner, repo, &issue).await {
Ok(created_issue) => {
println!("Created issue #{}: {}", created_issue.number, created_issue.title);
}
Err(e) => eprintln!("Error creating issue: {}", e),
}
}
4. 获取用户信息
async fn get_user_info(client: &Client, username: &str) {
match client.users().get_by_username(username).await {
Ok(user) => {
println!("User: {}", user.login);
println!("Name: {:?}", user.name);
println!("Public repos: {}", user.public_repos.unwrap_or(0));
}
Err(e) => eprintln!("Error: {}", e),
}
}
5. 分页获取仓库提交
async fn list_commits(client: &Client) {
let owner = "rust-lang";
let repo = "rust";
let per_page = 30;
let params = octorust::params::repos::ListCommits {
sha: None,
path: None,
author: None,
since: None,
until: None,
page: Some(1),
per_page: Some(per_page),
};
match client.repos().list_commits(owner, repo, ¶ms).await {
Ok(commits) => {
for commit in commits {
println!("Commit: {}", commit.sha);
println!("Message: {}", commit.commit.message);
println!("Author: {}", commit.commit.author.name);
}
}
Err(e) => eprintln!("Error: {}", e),
}
}
高级用法
自定义请求
use octorust::http::request::Request;
use octorust::types::Repository;
async fn custom_request(client: &Client) {
let request = Request::get("/repos/rust-lang/rust")
.accept("application/vnd.github.v3+json");
match client.execute::<Repository>(request).await {
Ok(repo) => println!("Repo: {}", repo.name),
Err(e) => eprintln!("Error: {}", e),
}
}
处理速率限制
async fn check_rate_limit(client: &Client) {
match client.rate_limit().get().await {
Ok(rate_limit) => {
println!("Remaining requests: {}", rate_limit.resources.core.remaining);
println!("Reset time: {}", rate_limit.resources.core.reset);
}
Err(e) => eprintln!("Error: {}", e),
}
}
完整示例demo
use octorust::Client;
use octorust::types::IssuesCreateRequest;
#[tokio::main]
async fn main() {
// 1. 创建客户端
let user_agent = "my-github-app/1.0";
let token = std::env::var("GITHUB_TOKEN").expect("GITHUB_TOKEN not set");
let client = Client::new(user_agent, token).unwrap();
// 2. 获取仓库信息
async fn get_repo_info(client: &Client) {
let owner = "rust-lang";
let repo = "rust";
match client.repos().get(owner, repo).await {
Ok(repository) => {
println!("Repository: {}", repository.name);
println!("Description: {:?}", repository.description);
println!("Stars: {}", repository.stargazers_count.unwrap_or(0));
}
Err(e) => eprintln!("Error: {}", e),
}
}
// 3. 创建Issue
async fn create_issue(client: &Client) {
let owner = "your-username";
let repo = "your-repo";
let issue = IssuesCreateRequest {
title: "Test issue".to_string(),
body: Some("This is a test issue created with octorust".to_string()),
assignee: None,
assignees: None,
milestone: None,
labels: None,
};
match client.issues().create(owner, repo, &issue).await {
Ok(created_issue) => {
println!("Created issue #{}: {}", created_issue.number, created_issue.title);
}
Err(e) => eprintln!("Error creating issue: {}", e),
}
}
// 4. 获取用户信息
async fn get_user_info(client: &Client, username: &str) {
match client.users().get_by_username(username).await {
Ok(user) => {
println!("User: {}", user.login);
println!("Name: {:?}", user.name);
println!("Public repos: {}", user.public_repos.unwrap_or(0));
}
Err(e) => eprintln!("Error: {}", e),
}
}
// 5. 检查速率限制
async fn check_rate_limit(client: &Client) {
match client.rate_limit().get().await {
Ok(rate_limit) => {
println!("Remaining requests: {}", rate_limit.resources.core.remaining);
println!("Reset time: {}", rate_limit.resources.core.reset);
}
Err(e) => eprintln!("Error: {}", e),
}
}
// 执行示例函数
get_repo_info(&client).await;
get_user_info(&client, "octocat").await;
check_rate_limit(&client).await;
// create_issue(&client).await; // 取消注释来创建issue
}
注意事项
- 确保正确处理GitHub API的速率限制
- 对于生产环境,考虑实现请求重试逻辑
- 敏感信息如token应该妥善管理,不要硬编码在代码中
- 检查GitHub API文档了解各端点的权限要求
octorust提供了强大的GitHub API集成能力,通过类型安全的接口简化了开发流程,是Rust项目中与GitHub交互的理想选择。