Skip to main content

github_rust/github/
graphql.rs

1use crate::github::client::GitHubClient;
2use crate::github::types::*;
3use crate::{config::*, error::*};
4use serde::Deserialize;
5use std::collections::HashMap;
6
7pub use crate::github::models::Repository;
8
9/// Full repository information from GitHub API.
10///
11/// Contains comprehensive details about a repository including metadata,
12/// statistics, and related information.
13#[derive(Deserialize)]
14struct GraphQLRepository {
15    /// Opaque global node ID, shared by the REST and GraphQL APIs.
16    #[serde(rename = "id")]
17    pub node_id: String,
18    /// Numeric database ID, when supplied by GitHub.
19    #[serde(rename = "databaseId")]
20    pub database_id: Option<u64>,
21    /// Repository name (without owner)
22    pub name: String,
23    /// Full repository name in "owner/repo" format
24    #[serde(rename = "nameWithOwner")]
25    pub name_with_owner: String,
26    /// Repository description
27    pub description: Option<String>,
28    /// GitHub URL for the repository
29    pub url: String,
30    /// Custom homepage URL if set
31    #[serde(rename = "homepageUrl")]
32    pub homepage_url: Option<String>,
33    /// ISO 8601 timestamp when repository was created
34    #[serde(rename = "createdAt")]
35    pub created_at: String,
36    /// ISO 8601 timestamp of last update
37    #[serde(rename = "updatedAt")]
38    pub updated_at: String,
39    /// ISO 8601 timestamp of last push
40    #[serde(rename = "pushedAt")]
41    pub pushed_at: Option<String>,
42    /// Whether the repository is private
43    #[serde(rename = "isPrivate")]
44    pub is_private: bool,
45    /// Whether the repository is a fork
46    #[serde(rename = "isFork")]
47    pub is_fork: bool,
48    /// Whether the repository is archived
49    #[serde(rename = "isArchived")]
50    pub is_archived: bool,
51    /// Number of stars
52    #[serde(rename = "stargazerCount")]
53    pub stargazer_count: u32,
54    /// Number of forks
55    #[serde(rename = "forkCount")]
56    pub fork_count: u32,
57    /// Number of watchers
58    pub watchers: TotalCount,
59    /// Number of open issues
60    pub issues: TotalCount,
61    /// Number of pull requests
62    #[serde(rename = "pullRequests")]
63    pub pull_requests: TotalCount,
64    /// Number of releases
65    pub releases: TotalCount,
66    /// Primary programming language
67    #[serde(rename = "primaryLanguage")]
68    pub primary_language: Option<Language>,
69    /// All languages used in the repository
70    pub languages: GraphQLLanguages,
71    /// License information
72    #[serde(rename = "licenseInfo")]
73    pub license_info: Option<License>,
74    /// Default branch reference
75    #[serde(rename = "defaultBranchRef")]
76    pub default_branch_ref: Option<Branch>,
77    /// Repository topics/tags
78    #[serde(rename = "repositoryTopics")]
79    pub repository_topics: TopicConnection,
80}
81
82#[derive(Deserialize)]
83struct GraphQLLanguages {
84    edges: Vec<LanguageEdge>,
85    #[serde(rename = "pageInfo")]
86    page_info: LanguagePageInfo,
87}
88
89#[derive(Deserialize)]
90struct LanguagePageInfo {
91    #[serde(rename = "hasNextPage")]
92    has_next_page: bool,
93}
94
95impl From<GraphQLRepository> for Repository {
96    fn from(repo: GraphQLRepository) -> Self {
97        Self {
98            node_id: repo.node_id,
99            database_id: repo.database_id,
100            name: repo.name,
101            name_with_owner: repo.name_with_owner,
102            description: repo.description,
103            url: repo.url,
104            homepage_url: repo.homepage_url,
105            created_at: repo.created_at,
106            updated_at: repo.updated_at,
107            pushed_at: repo.pushed_at,
108            is_private: repo.is_private,
109            is_fork: repo.is_fork,
110            is_archived: repo.is_archived,
111            stargazer_count: repo.stargazer_count,
112            fork_count: repo.fork_count,
113            watcher_count: Some(repo.watchers.total_count),
114            open_issue_count: Some(repo.issues.total_count),
115            pull_request_count: Some(repo.pull_requests.total_count),
116            release_count: Some(repo.releases.total_count),
117            primary_language: repo.primary_language,
118            languages: Some(
119                repo.languages
120                    .edges
121                    .into_iter()
122                    .map(|edge| crate::github::models::LanguageUsage {
123                        language: edge.node,
124                        bytes: edge.size,
125                    })
126                    .collect(),
127            ),
128            languages_complete: !repo.languages.page_info.has_next_page,
129            license_info: repo.license_info,
130            default_branch: repo.default_branch_ref.map(|branch| branch.name),
131            topics: repo
132                .repository_topics
133                .edges
134                .into_iter()
135                .map(|edge| edge.node.topic.name)
136                .collect(),
137        }
138    }
139}
140
141#[derive(Deserialize)]
142struct RepositoryResponse {
143    repository: Option<GraphQLRepository>,
144}
145
146pub async fn get_repository_info(
147    client: &GitHubClient,
148    owner: &str,
149    name: &str,
150) -> Result<Repository> {
151    let mut variables = HashMap::new();
152    variables.insert("owner".to_string(), owner.to_string());
153    variables.insert("name".to_string(), name.to_string());
154
155    let query: GraphQLQuery<HashMap<String, String>> = GraphQLQuery {
156        query: GRAPHQL_REPOSITORY_QUERY.to_string(),
157        variables,
158    };
159
160    let response = client
161        .post(client.graphql_url())
162        .json(&query)
163        .send()
164        .await?;
165
166    let data: RepositoryResponse = super::response::graphql(response)
167        .await
168        .map_err(|error| error.with_repository_context(owner, name))?;
169    data.repository
170        .map(Into::into)
171        .ok_or_else(|| GitHubError::NotFoundError(format!("{owner}/{name}")))
172}