Skip to main content

github_rust/
lib.rs

1//! # GitHub Rust - Core Library
2//!
3//! A Rust library for GitHub API integration with dual GraphQL/REST support.
4//!
5//! ## Features
6//!
7//! - **Dual API**: GraphQL primary with REST fallback
8//! - **Search**: Repository search with filters
9//! - **Performance**: Connection pooling and async I/O
10//! - **Type Safety**: Comprehensive error handling
11//!
12//! ## Quick Start
13//!
14//! ```rust,no_run
15//! use github_rust::GitHubService;
16//!
17//! # async fn example() -> github_rust::Result<()> {
18//! let service = GitHubService::new()?;
19//!
20//! // Get repository info
21//! let repo = service.get_repository_info("microsoft", "vscode").await?;
22//! println!("{}: {} stars", repo.name_with_owner, repo.stargazer_count);
23//!
24//! // Search recent repositories (30 days back, limit 10, Rust language, min 100 stars)
25//! let repos = service.search_repositories(30, 10, Some("rust"), 100).await?;
26//! # Ok(())
27//! # }
28//! ```
29//!
30//! ## Authentication
31//!
32//! Set `GITHUB_TOKEN` for authenticated requests. Quotas vary by API resource and token.
33
34pub mod config;
35pub mod error;
36pub mod github;
37
38pub use config::{GITHUB_API_URL, GITHUB_GRAPHQL_URL};
39pub use error::{DecodeError, ErrorKind, GitHubError, RateLimitDetails, Result};
40pub use github::{
41    Account, Actor, FallbackPolicy, FetchOptions, GitHubClient, GitHubClientBuilder, GitHubService,
42    Issue, Label, LanguageUsage, OwnedRepositories, PullRequest, RateLimit, RateLimits, Repository,
43    RepositoryCoordinates, RepositoryPage, RepositoryReference, RepositorySummary, ReviewDecision,
44    SearchRepository, StargazerWithDate, User, UserProfile, Viewer, WorkItemPage,
45};
46
47use base64::Engine;
48
49/// Best-effort decoder for historical node ID formats. Returns 0 on failure.
50///
51/// Node IDs are opaque: new formats are not guaranteed to be supported.
52/// Use the `node_id` and `database_id` fields returned by repository operations.
53#[deprecated(
54    since = "0.2.0",
55    note = "GitHub node IDs are opaque; use Repository::database_id or SearchRepository::database_id"
56)]
57pub fn parse_github_node_id(node_id: &str) -> i64 {
58    // New format: R_kgDO... (URL-safe base64-encoded msgpack)
59    if let Some(b64_part) = node_id.strip_prefix("R_") {
60        // Decode URL-safe base64 (add padding if needed)
61        let padded = match b64_part.len() % 4 {
62            2 => format!("{}==", b64_part),
63            3 => format!("{}=", b64_part),
64            _ => b64_part.to_string(),
65        };
66
67        if let Ok(bytes) = base64::engine::general_purpose::URL_SAFE.decode(&padded) {
68            // msgpack format: 0x92 (array of 2), 0x00 (type), 0xce (uint32), 4 bytes ID
69            if bytes.len() >= 7 && bytes[0] == 0x92 && bytes[2] == 0xce {
70                let id_bytes = &bytes[3..7];
71                return i64::from(u32::from_be_bytes([
72                    id_bytes[0],
73                    id_bytes[1],
74                    id_bytes[2],
75                    id_bytes[3],
76                ]));
77            }
78        }
79    }
80
81    // Legacy format: MDEwOlJlcG9zaXRvcnk... (standard base64 "010:Repository{id}")
82    if node_id.starts_with("MDEw")
83        && let Some(id) = base64::engine::general_purpose::STANDARD
84            .decode(node_id)
85            .ok()
86            .and_then(|bytes| String::from_utf8(bytes).ok())
87            .and_then(|s| {
88                s.strip_prefix("010:Repository")
89                    .and_then(|n| n.parse::<i64>().ok())
90            })
91    {
92        return id;
93    }
94
95    // Fallback: return 0 for invalid IDs
96    tracing::warn!("Failed to parse GitHub node ID: {}", node_id);
97    0
98}
99
100/// Parse a repository string "owner/repo" into components.
101///
102/// # Examples
103///
104/// ```
105/// use github_rust::parse_repository;
106///
107/// let (owner, repo) = parse_repository("microsoft/vscode").unwrap();
108/// assert_eq!(owner, "microsoft");
109/// assert_eq!(repo, "vscode");
110///
111/// assert!(parse_repository("invalid").is_err());
112/// ```
113pub fn parse_repository(repo: &str) -> std::result::Result<(String, String), String> {
114    let parts: Vec<&str> = repo.split('/').collect();
115    if parts.len() != 2 {
116        return Err(format!(
117            "Invalid repository format '{}'. Use 'owner/repo'",
118            repo
119        ));
120    }
121
122    let owner = parts[0].trim();
123    let name = parts[1].trim();
124
125    if owner.is_empty() || name.is_empty() {
126        return Err(format!(
127            "Invalid repository format '{}'. Owner and repository name cannot be empty",
128            repo
129        ));
130    }
131
132    Ok((owner.to_string(), name.to_string()))
133}
134
135#[cfg(test)]
136#[allow(deprecated)]
137mod tests {
138    use super::*;
139
140    #[test]
141    fn test_parse_repository_valid() {
142        let (owner, repo) = parse_repository("owner/repo").unwrap();
143        assert_eq!(owner, "owner");
144        assert_eq!(repo, "repo");
145    }
146
147    #[test]
148    fn test_parse_repository_with_whitespace() {
149        let (owner, repo) = parse_repository(" owner / repo ").unwrap();
150        assert_eq!(owner, "owner");
151        assert_eq!(repo, "repo");
152    }
153
154    #[test]
155    fn test_parse_repository_invalid() {
156        assert!(parse_repository("invalid").is_err());
157        assert!(parse_repository("/repo").is_err());
158        assert!(parse_repository("owner/").is_err());
159        assert!(parse_repository("owner/repo/extra").is_err());
160    }
161
162    #[test]
163    fn test_parse_github_node_id_new_format() {
164        // R_kgDOQBnJRQ = karpathy/nanochat (ID: 1075431749)
165        assert_eq!(parse_github_node_id("R_kgDOQBnJRQ"), 1075431749);
166        // R_kgDOQpc_vg = productdevbook/port-killer (ID: 1117208510)
167        assert_eq!(parse_github_node_id("R_kgDOQpc_vg"), 1117208510);
168        // R_kgDOPQG3Mw = anomalyco/opentui (ID: 1023522611)
169        assert_eq!(parse_github_node_id("R_kgDOPQG3Mw"), 1023522611);
170    }
171
172    #[test]
173    fn test_parse_github_node_id_legacy_format() {
174        assert_eq!(
175            parse_github_node_id("MDEwOlJlcG9zaXRvcnkxMjk2MjY5"),
176            1296269
177        );
178    }
179
180    #[test]
181    fn test_parse_github_node_id_invalid() {
182        assert_eq!(parse_github_node_id("invalid"), 0);
183        assert_eq!(parse_github_node_id(""), 0);
184        assert_eq!(parse_github_node_id("R_invalid"), 0);
185    }
186}