Skip to main content

github_rust/github/
search.rs

1use crate::github::client::GitHubClient;
2use crate::github::types::*;
3use crate::{config::*, error::*};
4use chrono::{Duration, Utc};
5use serde::Deserialize;
6use std::collections::{HashMap, HashSet};
7
8/// Validates and sanitizes a language parameter for GitHub search.
9/// Returns None if the language is invalid, Some(sanitized) otherwise.
10fn validate_language(language: &str) -> Option<String> {
11    let trimmed = language.trim();
12
13    // Empty language is invalid
14    if trimmed.is_empty() {
15        return None;
16    }
17
18    // Language should only contain alphanumeric, spaces, hyphens, plus, hash, and dots
19    // Examples: "C++", "C#", "F#", "Objective-C", "Visual Basic .NET"
20    let is_valid = trimmed
21        .chars()
22        .all(|c| c.is_alphanumeric() || c == ' ' || c == '-' || c == '+' || c == '#' || c == '.');
23
24    if !is_valid {
25        return None;
26    }
27
28    Some(trimmed.to_string())
29}
30
31pub use crate::github::models::SearchRepository;
32
33/// Repository data from GitHub search API.
34///
35/// A lighter-weight repository struct returned by search operations,
36/// containing the most commonly needed fields.
37#[derive(Deserialize)]
38struct GraphQLSearchRepository {
39    /// Opaque global node ID, shared by the REST and GraphQL APIs.
40    #[serde(rename = "id")]
41    pub node_id: String,
42    /// Numeric database ID, when supplied by GitHub.
43    #[serde(rename = "databaseId")]
44    pub database_id: Option<u64>,
45    /// Repository name (without owner)
46    pub name: String,
47    /// Full repository name in "owner/repo" format
48    #[serde(rename = "nameWithOwner")]
49    pub name_with_owner: String,
50    /// Repository description
51    pub description: Option<String>,
52    /// GitHub URL for the repository
53    pub url: String,
54    /// Number of stars
55    #[serde(rename = "stargazerCount")]
56    pub stargazer_count: u32,
57    /// Number of forks
58    #[serde(rename = "forkCount")]
59    pub fork_count: u32,
60    /// ISO 8601 timestamp when repository was created
61    #[serde(rename = "createdAt")]
62    pub created_at: String,
63    /// ISO 8601 timestamp of last update
64    #[serde(rename = "updatedAt")]
65    pub updated_at: String,
66    /// ISO 8601 timestamp of last push
67    #[serde(rename = "pushedAt")]
68    pub pushed_at: Option<String>,
69    /// Primary programming language
70    #[serde(rename = "primaryLanguage")]
71    pub primary_language: Option<Language>,
72    /// License information
73    #[serde(rename = "licenseInfo")]
74    pub license_info: Option<License>,
75    /// Repository topics/tags
76    #[serde(rename = "repositoryTopics")]
77    pub repository_topics: TopicConnection,
78}
79
80impl From<GraphQLSearchRepository> for SearchRepository {
81    fn from(repo: GraphQLSearchRepository) -> Self {
82        Self {
83            node_id: repo.node_id,
84            database_id: repo.database_id,
85            name: repo.name,
86            name_with_owner: repo.name_with_owner,
87            description: repo.description,
88            url: repo.url,
89            stargazer_count: repo.stargazer_count,
90            fork_count: repo.fork_count,
91            created_at: repo.created_at,
92            updated_at: repo.updated_at,
93            pushed_at: repo.pushed_at,
94            primary_language: repo.primary_language,
95            license_info: repo.license_info,
96            topics: repo
97                .repository_topics
98                .edges
99                .into_iter()
100                .map(|edge| edge.node.topic.name)
101                .collect(),
102        }
103    }
104}
105
106#[derive(Deserialize)]
107struct SearchResult {
108    search: SearchConnection,
109}
110
111#[derive(Deserialize)]
112struct PageInfo {
113    #[serde(rename = "hasNextPage")]
114    has_next_page: bool,
115    #[serde(rename = "endCursor")]
116    end_cursor: Option<String>,
117}
118
119#[derive(Deserialize)]
120struct SearchConnection {
121    #[serde(rename = "repositoryCount")]
122    #[allow(dead_code)]
123    repository_count: u32,
124    #[serde(rename = "pageInfo")]
125    page_info: PageInfo,
126    edges: Vec<SearchEdge>,
127}
128
129#[derive(Deserialize)]
130struct SearchEdge {
131    node: GraphQLSearchRepository,
132}
133
134/// Search for repositories created in the last N days with minimum stars.
135pub async fn search_repositories(
136    client: &GitHubClient,
137    days_back: u32,
138    limit: usize,
139    language: Option<&str>,
140    min_stars: u32,
141) -> Result<Vec<SearchRepository>> {
142    if limit == 0 {
143        return Ok(Vec::new());
144    }
145    let now = Utc::now();
146    let days_ago = now
147        .checked_sub_signed(Duration::days(i64::from(days_back)))
148        .ok_or_else(|| {
149            GitHubError::InvalidInput("days_back exceeds the supported date range".into())
150        })?;
151    let date_filter = days_ago.format("%Y-%m-%d").to_string();
152
153    let mut query_parts = vec![
154        format!("created:>{}", date_filter),
155        format!("stars:>={}", min_stars),
156        "is:public".to_string(),
157        "sort:stars-desc".to_string(),
158    ];
159
160    if let Some(lang) = language {
161        if let Some(validated_lang) = validate_language(lang) {
162            query_parts.push(format!("language:\"{}\"", validated_lang));
163        } else {
164            return Err(GitHubError::InvalidInput(format!(
165                "Invalid language parameter: '{}'. Language must contain only alphanumeric characters, spaces, hyphens, plus signs, hash, or dots.",
166                lang
167            )));
168        }
169    }
170
171    if !client.has_token() {
172        return Err(GitHubError::AuthenticationError(
173            "Repository search requires a GitHub token".into(),
174        ));
175    }
176    let query_string = query_parts.join(" ");
177    tracing::debug!("GitHub search query: {}", query_string);
178
179    let mut all_repositories = Vec::new();
180    let mut after_cursor: Option<String> = None;
181    let max_total = limit.min(1000);
182    let mut seen_cursors = HashSet::new();
183
184    loop {
185        let mut variables = HashMap::new();
186        variables.insert(
187            "queryString".to_string(),
188            serde_json::Value::String(query_string.clone()),
189        );
190        variables.insert(
191            "first".to_string(),
192            serde_json::Value::Number(serde_json::Number::from(
193                (max_total - all_repositories.len()).min(100),
194            )),
195        );
196
197        if let Some(cursor) = &after_cursor {
198            variables.insert(
199                "after".to_string(),
200                serde_json::Value::String(cursor.clone()),
201            );
202        } else {
203            variables.insert("after".to_string(), serde_json::Value::Null);
204        }
205
206        let graphql_query: GraphQLQuery<HashMap<String, serde_json::Value>> = GraphQLQuery {
207            query: GRAPHQL_SEARCH_REPOSITORIES_QUERY.to_string(),
208            variables,
209        };
210
211        let response = client
212            .post(client.graphql_url())
213            .json(&graphql_query)
214            .send()
215            .await?;
216
217        let data: SearchResult = super::response::graphql(response).await?;
218        let page_is_empty = data.search.edges.is_empty();
219        let page_repositories = data
220            .search
221            .edges
222            .into_iter()
223            .map(|edge| SearchRepository::from(edge.node));
224        all_repositories.extend(page_repositories);
225        if data.search.page_info.has_next_page && all_repositories.len() < max_total {
226            let cursor = data
227                .search
228                .page_info
229                .end_cursor
230                .filter(|cursor| !cursor.is_empty())
231                .ok_or_else(|| {
232                    GitHubError::PaginationError("hasNextPage without endCursor".into())
233                })?;
234            if page_is_empty || !seen_cursors.insert(cursor.clone()) {
235                return Err(GitHubError::PaginationError(
236                    "Search pagination made no progress".into(),
237                ));
238            }
239            after_cursor = Some(cursor);
240        } else {
241            break;
242        }
243    }
244
245    all_repositories.truncate(max_total);
246    Ok(all_repositories)
247}
248
249#[cfg(test)]
250mod tests {
251    use super::*;
252
253    #[test]
254    fn test_search_repository_default() {
255        let repo = SearchRepository::default();
256        assert_eq!(repo.stargazer_count, 0);
257        assert_eq!(repo.fork_count, 0);
258        assert!(repo.description.is_none());
259    }
260}