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//! - Repository metadata through GraphQL or REST, with configurable REST fallback.
6//! - Authenticated account discovery, repository inventories and open issues/PRs.
7//! - Owned page streams, borrowed page callbacks and complete collections.
8//! - Repository search, stargazers and resource-specific quota information.
9//!
10//! Start with [`GitHubService`], configure authentication with [`GitHubClient::builder`],
11//! or process pages with [`GitHubService::get_open_issue_pages`].
12//!
13//! ## Quick Start
14//!
15//! ```rust,no_run
16//! use github_rust::GitHubService;
17//!
18//! # async fn example() -> github_rust::Result<()> {
19//! let service = GitHubService::new()?;
20//!
21//! // Get repository info
22//! let repo = service.get_repository_info("microsoft", "vscode").await?;
23//! println!("{}: {} stars", repo.name_with_owner, repo.stargazer_count);
24//! # Ok(())
25//! # }
26//! ```
27//!
28//! ## Authentication
29//!
30//! `GitHubService::new()` reads `GITHUB_TOKEN`; the explicit client builder does not.
31//! Collections and search require a token. Repository metadata also supports anonymous
32//! REST access. 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 Some((owner, name)) = repo.split_once('/').filter(|(_, name)| !name.contains('/')) else {
115        return Err(format!(
116            "Invalid repository format '{}'. Use 'owner/repo'",
117            repo
118        ));
119    };
120
121    let owner = owner.trim();
122    let name = name.trim();
123
124    if owner.is_empty() || name.is_empty() {
125        return Err(format!(
126            "Invalid repository format '{}'. Owner and repository name cannot be empty",
127            repo
128        ));
129    }
130
131    Ok((owner.to_string(), name.to_string()))
132}
133
134#[cfg(test)]
135#[allow(deprecated)]
136mod tests {
137    use super::*;
138
139    #[test]
140    fn test_parse_repository_valid() {
141        let (owner, repo) = parse_repository("owner/repo").unwrap();
142        assert_eq!(owner, "owner");
143        assert_eq!(repo, "repo");
144    }
145
146    #[test]
147    fn test_parse_repository_with_whitespace() {
148        let (owner, repo) = parse_repository(" owner / repo ").unwrap();
149        assert_eq!(owner, "owner");
150        assert_eq!(repo, "repo");
151    }
152
153    #[test]
154    fn test_parse_repository_invalid() {
155        assert!(parse_repository("invalid").is_err());
156        assert!(parse_repository("/repo").is_err());
157        assert!(parse_repository("owner/").is_err());
158        assert!(parse_repository("owner/repo/extra").is_err());
159    }
160
161    #[test]
162    fn test_parse_github_node_id_new_format() {
163        // R_kgDOQBnJRQ = karpathy/nanochat (ID: 1075431749)
164        assert_eq!(parse_github_node_id("R_kgDOQBnJRQ"), 1075431749);
165        // R_kgDOQpc_vg = productdevbook/port-killer (ID: 1117208510)
166        assert_eq!(parse_github_node_id("R_kgDOQpc_vg"), 1117208510);
167        // R_kgDOPQG3Mw = anomalyco/opentui (ID: 1023522611)
168        assert_eq!(parse_github_node_id("R_kgDOPQG3Mw"), 1023522611);
169    }
170
171    #[test]
172    fn test_parse_github_node_id_legacy_format() {
173        assert_eq!(
174            parse_github_node_id("MDEwOlJlcG9zaXRvcnkxMjk2MjY5"),
175            1296269
176        );
177    }
178
179    #[test]
180    fn test_parse_github_node_id_invalid() {
181        assert_eq!(parse_github_node_id("invalid"), 0);
182        assert_eq!(parse_github_node_id(""), 0);
183        assert_eq!(parse_github_node_id("R_invalid"), 0);
184    }
185}