github_rust/github/
search.rs1use crate::github::client::GitHubClient;
2use crate::github::types::*;
3use crate::{config::*, error::*};
4use chrono::{Duration, Utc};
5use serde::Deserialize;
6use serde_json::json;
7use std::collections::HashSet;
8
9fn validate_language(language: &str) -> Option<String> {
12 let trimmed = language.trim();
13
14 if trimmed.is_empty() {
16 return None;
17 }
18
19 let is_valid = trimmed
22 .chars()
23 .all(|c| c.is_alphanumeric() || c == ' ' || c == '-' || c == '+' || c == '#' || c == '.');
24
25 if !is_valid {
26 return None;
27 }
28
29 Some(trimmed.to_string())
30}
31
32pub use crate::github::models::SearchRepository;
33
34#[derive(Deserialize)]
35#[serde(rename_all = "camelCase")]
36struct GraphQLSearchRepository {
37 #[serde(rename = "id")]
38 node_id: String,
39 database_id: Option<u64>,
40 name: String,
41 name_with_owner: String,
42 description: Option<String>,
43 url: String,
44 stargazer_count: u32,
45 fork_count: u32,
46 created_at: String,
47 updated_at: String,
48 pushed_at: Option<String>,
49 primary_language: Option<Language>,
50 license_info: Option<License>,
51 repository_topics: TopicConnection,
52}
53
54impl From<GraphQLSearchRepository> for SearchRepository {
55 fn from(repo: GraphQLSearchRepository) -> Self {
56 Self {
57 node_id: repo.node_id,
58 database_id: repo.database_id,
59 name: repo.name,
60 name_with_owner: repo.name_with_owner,
61 description: repo.description,
62 url: repo.url,
63 stargazer_count: repo.stargazer_count,
64 fork_count: repo.fork_count,
65 created_at: repo.created_at,
66 updated_at: repo.updated_at,
67 pushed_at: repo.pushed_at,
68 primary_language: repo.primary_language,
69 license_info: repo.license_info,
70 topics: repo
71 .repository_topics
72 .edges
73 .into_iter()
74 .map(|edge| edge.node.topic.name)
75 .collect(),
76 }
77 }
78}
79
80#[derive(Deserialize)]
81struct SearchResult {
82 search: SearchConnection,
83}
84
85#[derive(Deserialize)]
86struct PageInfo {
87 #[serde(rename = "hasNextPage")]
88 has_next_page: bool,
89 #[serde(rename = "endCursor")]
90 end_cursor: Option<String>,
91}
92
93#[derive(Deserialize)]
94struct SearchConnection {
95 #[serde(rename = "pageInfo")]
96 page_info: PageInfo,
97 edges: Vec<SearchEdge>,
98}
99
100#[derive(Deserialize)]
101struct SearchEdge {
102 node: GraphQLSearchRepository,
103}
104
105pub async fn search_repositories(
107 client: &GitHubClient,
108 days_back: u32,
109 limit: usize,
110 language: Option<&str>,
111 min_stars: u32,
112) -> Result<Vec<SearchRepository>> {
113 if limit == 0 {
114 return Ok(Vec::new());
115 }
116 let now = Utc::now();
117 let days_ago = now
118 .checked_sub_signed(Duration::days(i64::from(days_back)))
119 .ok_or_else(|| {
120 GitHubError::InvalidInput("days_back exceeds the supported date range".into())
121 })?;
122 let date_filter = days_ago.format("%Y-%m-%d").to_string();
123
124 let mut query_parts = vec![
125 format!("created:>{}", date_filter),
126 format!("stars:>={}", min_stars),
127 "is:public".to_string(),
128 "sort:stars-desc".to_string(),
129 ];
130
131 if let Some(lang) = language {
132 if let Some(validated_lang) = validate_language(lang) {
133 query_parts.push(format!("language:\"{}\"", validated_lang));
134 } else {
135 return Err(GitHubError::InvalidInput(format!(
136 "Invalid language parameter: '{}'. Language must contain only alphanumeric characters, spaces, hyphens, plus signs, hash, or dots.",
137 lang
138 )));
139 }
140 }
141
142 if !client.has_token() {
143 return Err(GitHubError::AuthenticationError(
144 "Repository search requires a GitHub token".into(),
145 ));
146 }
147 let query_string = query_parts.join(" ");
148 tracing::debug!("GitHub search query: {}", query_string);
149
150 let mut all_repositories = Vec::new();
151 let mut after_cursor: Option<String> = None;
152 let max_total = limit.min(1000);
153 let mut seen_cursors = HashSet::new();
154
155 loop {
156 let data: SearchResult = super::response::query(
157 client,
158 GRAPHQL_SEARCH_REPOSITORIES_QUERY,
159 json!({
160 "queryString": query_string,
161 "first": (max_total - all_repositories.len()).min(100),
162 "after": after_cursor,
163 }),
164 )
165 .await?;
166 let page_is_empty = data.search.edges.is_empty();
167 let page_repositories = data
168 .search
169 .edges
170 .into_iter()
171 .map(|edge| SearchRepository::from(edge.node));
172 all_repositories.extend(page_repositories);
173 if data.search.page_info.has_next_page && all_repositories.len() < max_total {
174 let cursor = data
175 .search
176 .page_info
177 .end_cursor
178 .filter(|cursor| !cursor.is_empty())
179 .ok_or_else(|| {
180 GitHubError::PaginationError("hasNextPage without endCursor".into())
181 })?;
182 if page_is_empty || !seen_cursors.insert(cursor.clone()) {
183 return Err(GitHubError::PaginationError(
184 "Search pagination made no progress".into(),
185 ));
186 }
187 after_cursor = Some(cursor);
188 } else {
189 break;
190 }
191 }
192
193 all_repositories.truncate(max_total);
194 Ok(all_repositories)
195}