1pub mod actions;
9mod bound;
10pub mod copilot_agents;
11pub use bound::{
12 BoundRead, Organization, PackageRelease, PackageRepository, ReleaseAsset, RepositoryRef,
13 ResolvedRepository, newest_package_release,
14};
15mod cache;
16pub mod copilot_agent_sessions;
17pub mod issue_report;
18pub mod lifecycle;
19pub mod model;
20mod pull_request_writes;
21mod queries;
22mod raw;
23pub mod scope;
24mod transport;
25pub mod validate;
26mod work;
27pub use transport::{is_access_refusal, is_not_found};
28pub use work::PinnedWork;
29
30use std::sync::Arc;
31use std::thread;
32use std::time::Duration;
33
34use serde::Deserialize;
35use serde::de::DeserializeOwned;
36use serde_json::{Value, json};
37use subspace_core::credentials::{
38 Credential, CredentialError, Credentials, GitHubAccounts, Source,
39};
40use subspace_core::http::status as http_status;
41use subspace_core::http::{Error, send_with_retry};
42
43use crate::cache::{Lru, Ttl};
44use crate::model::{
45 AssignableResponse, DiffResponse, FileResponse, GhDiffFile, GhItemDetail, GhRepository, GhUser,
46 Image, ItemKind, ReviewEvent, SECTIONS, SectionResponse, image_type,
47};
48use crate::raw::{Nodes, RawActor, RawDetail, RawPrFile};
49use crate::transport::{JSON, RAW, not_found, unexpected};
50use crate::validate::{
51 ItemRef, check_key, check_login, check_logins, check_path, check_repo, check_review_body,
52 check_section, check_sha, invalid, is_sha,
53};
54
55pub const API_URL: &str = "https://api.github.com";
56pub const API_URL_ENV: &str = "SUBSPACE_GITHUB_API_URL";
59const USER_RESPONSE_LIMIT: usize = 64 * 1024;
60pub(crate) const MAX_BODY_BYTES: usize = subspace_core::http::MAX_BODY_BYTES as usize;
62
63pub fn credential_login(credential: &Credential) -> Result<String, Error> {
66 #[derive(Deserialize)]
67 struct User {
68 login: String,
69 }
70 let account = transport::account_label(credential, None);
71 let url = format!("{}/user", api_url());
72 let response = transport::get_rest(&url, credential, &account, JSON)?;
73 let bytes = transport::read_limited(response, USER_RESPONSE_LIMIT)?;
74 let user: User = serde_json::from_slice(&bytes).map_err(|_| unexpected("user"))?;
75 validate::check_login(&user.login).map(str::to_owned)
76}
77
78fn debug_api_url() -> Option<String> {
80 let value = std::env::var(API_URL_ENV)
81 .ok()
82 .filter(|_| cfg!(debug_assertions))?;
83 let value = value.trim().trim_end_matches('/');
84 (!value.is_empty()).then(|| value.to_owned())
85}
86
87fn api_url() -> String {
89 debug_api_url().unwrap_or_else(|| API_URL.to_owned())
90}
91
92fn copilot_api_override() -> std::sync::OnceLock<String> {
95 debug_api_url()
96 .map(std::sync::OnceLock::from)
97 .unwrap_or_default()
98}
99const ASSIGNABLE_TTL: Duration = Duration::from_secs(10 * 60);
100pub const MAX_DIFF_FILES: u32 = 3000;
102const FILES_PER_PAGE: u32 = 100;
103const PAGE_CONCURRENCY: u32 = 6;
104pub const MAX_FILE_BYTES: usize = 1024 * 1024;
105pub const MAX_IMAGE_BYTES: usize = 10 * 1024 * 1024;
106const FILE_CACHE_BYTES: usize = 50 * 1024 * 1024;
107const DIFF_CACHE_ENTRIES: usize = 20;
108const MAX_AGENT_SEARCH_BYTES: usize = 200;
109const MAX_AGENT_SEARCH_ITEMS: u32 = 100;
110const REPOSITORIES_PER_PAGE: &str = "30";
111
112struct DiffRequest<'a> {
115 login: &'a str,
116 item: &'a ItemRef,
117 base_tip: &'a str,
118 head: &'a str,
119 pages: u32,
120}
121
122fn pull_commits(pull: &RawPull) -> Result<(String, String), Error> {
124 let sha = |side: &Option<Sha>| {
125 side.as_ref()
126 .and_then(|side| side.sha.clone())
127 .unwrap_or_default()
128 };
129 let head = sha(&pull.head);
130 let base_tip = sha(&pull.base);
131 if !is_sha(&head) || !is_sha(&base_tip) {
132 return Err(Error::Status {
133 status: http_status::BAD_GATEWAY,
134 message: "GitHub returned no commits for this pull request.".into(),
135 });
136 }
137 Ok((head, base_tip))
138}
139
140pub struct Client {
142 credentials: Arc<Credentials>,
143 work_account: Option<String>,
144 api_url: String,
145 copilot_api: std::sync::OnceLock<String>,
147 verified: std::sync::Mutex<Option<work::Verified>>,
149 assignable: Ttl<Vec<GhUser>>,
150 diffs: Lru<DiffResponse>,
151 files: Lru<String>,
152}
153
154#[derive(Deserialize)]
155#[serde(rename_all = "camelCase")]
156struct Search {
157 #[serde(default)]
158 issue_count: u32,
159 #[serde(default)]
160 nodes: Vec<Value>,
161}
162
163#[derive(Deserialize)]
164struct SearchData {
165 search: Search,
166}
167
168#[derive(Deserialize)]
169#[serde(rename_all = "camelCase")]
170struct Repository<T> {
171 issue_or_pull_request: Option<T>,
172 #[serde(flatten)]
173 merge_settings: pull_request_writes::MergeSettings,
174}
175
176#[derive(Deserialize)]
177struct RepositoryData<T> {
178 repository: Option<Repository<T>>,
179}
180
181#[derive(Deserialize)]
182#[serde(rename_all = "camelCase")]
183struct Subject {
184 #[serde(rename = "__typename")]
185 typename: String,
186 id: String,
187}
188
189#[derive(Deserialize)]
190struct Sha {
191 sha: Option<String>,
192}
193
194#[derive(Deserialize)]
195struct RawPull {
196 head: Option<Sha>,
197 base: Option<Sha>,
198 changed_files: Option<u32>,
199}
200
201#[derive(Deserialize)]
202struct RawCompare {
203 merge_base_commit: Option<Sha>,
204}
205
206fn valid_agent_search(query: &str, limit: u32) -> bool {
207 let lower = query.to_ascii_lowercase();
208 query.len() <= MAX_AGENT_SEARCH_BYTES
209 && (1..=MAX_AGENT_SEARCH_ITEMS).contains(&limit)
210 && !["repo:", "org:", "user:"]
211 .iter()
212 .any(|scope| lower.contains(scope))
213 && !query.chars().any(char::is_control)
214 && !query.contains(['(', ')'])
215 && !query
216 .split_whitespace()
217 .any(|word| word.eq_ignore_ascii_case("OR"))
218}
219
220fn agent_mutation(action: &str, kind: &str) -> Result<(&'static str, &'static str), &'static str> {
221 match (action, kind) {
222 ("comment", _) => Ok((
223 "mutation($input:AddCommentInput!) { addComment(input:$input) { commentEdge { node { id url } } } }",
224 "subjectId",
225 )),
226 ("review", "PullRequest") => Ok((
227 "mutation($input:AddPullRequestReviewInput!) { addPullRequestReview(input:$input) { pullRequestReview { id url } } }",
228 "pullRequestId",
229 )),
230 ("update_pr", "PullRequest") => Ok((
231 "mutation($input:UpdatePullRequestInput!) { updatePullRequest(input:$input) { pullRequest { id url title state } } }",
232 "pullRequestId",
233 )),
234 _ => Err("Unsupported action or target is not a pull request."),
235 }
236}
237
238fn agent_mutation_body(
239 mutation: (&str, &str),
240 subject: &str,
241 mut fields: Value,
242) -> Result<String, &'static str> {
243 fields
244 .as_object_mut()
245 .ok_or("Mutation fields must be an object.")?
246 .insert(mutation.1.into(), json!(subject));
247 Ok(json!({"query":mutation.0,"variables":{"input":fields}}).to_string())
248}
249
250#[cfg(test)]
251mod agent_tools_tests {
252 use super::{agent_mutation, agent_mutation_body, valid_agent_search};
253 use serde_json::{Value, json};
254 #[test]
255 fn search_cannot_override_repo_scope_or_bounds() {
256 assert!(valid_agent_search("is:pr merged:>=2026-10-01", 100));
257 for query in [
258 "repo:outside/repo",
259 "org:outside",
260 "user:outside",
261 "is:pr OR is:issue",
262 "(is:pr)",
263 "is:pr\n",
264 ] {
265 assert!(!valid_agent_search(query, 50), "{query}");
266 }
267 assert!(!valid_agent_search("is:pr", 101));
268 assert!(!valid_agent_search("is:pr", 0));
269 }
270 #[test]
271 fn writes_use_only_named_mutations_and_verified_subject() {
272 assert!(agent_mutation("review", "Issue").is_err());
273 assert!(agent_mutation("merge", "PullRequest").is_err());
274 let mutation = agent_mutation("comment", "Issue").unwrap();
275 let body = agent_mutation_body(
276 mutation,
277 "verified-id",
278 json!({"subjectId":"untrusted-id","body":"exact comment"}),
279 )
280 .unwrap();
281 let body: Value = serde_json::from_str(&body).unwrap();
282 assert_eq!(body["variables"]["input"]["subjectId"], "verified-id");
283 assert_eq!(body["variables"]["input"]["body"], "exact comment");
284 assert!(agent_mutation_body(mutation, "id", json!("not an object")).is_err());
285 assert_eq!(
286 agent_mutation("review", "PullRequest").unwrap().1,
287 "pullRequestId"
288 );
289 assert_eq!(
290 agent_mutation("update_pr", "PullRequest").unwrap().1,
291 "pullRequestId"
292 );
293 }
294}
295
296impl Client {
297 pub fn bind_read(&self, login: &str) -> Result<BoundRead, Error> {
299 BoundRead::bind(self, login)
300 }
301
302 pub fn new(credentials: Arc<Credentials>) -> Self {
303 Self {
304 credentials,
305 work_account: None,
306 api_url: api_url(),
307 copilot_api: copilot_api_override(),
308 verified: std::sync::Mutex::new(None),
309 assignable: Ttl::new(ASSIGNABLE_TTL),
310 diffs: Lru::new(DIFF_CACHE_ENTRIES, |_| 1),
311 files: Lru::new(FILE_CACHE_BYTES, String::len),
312 }
313 }
314
315 pub fn agent_search(
319 &self,
320 login: &str,
321 repo: &str,
322 query: &str,
323 limit: u32,
324 ) -> Result<Value, Error> {
325 check_login(login)?;
326 check_repo(repo)?;
327 valid_agent_search(query, limit).then_some(()).ok_or_else(|| invalid("Use at most 200 characters of search terms without scope qualifiers, OR, parentheses or control characters; limit is 1..100."))?;
328 self.graphql_value(Some(login), "query($query:String!, $limit:Int!) { search(query:$query,type:ISSUE,first:$limit) { issueCount pageInfo { hasNextPage endCursor } nodes { ... on Issue { number title body state url updatedAt repository { nameWithOwner } author { login } } ... on PullRequest { number title body state url updatedAt mergedAt repository { nameWithOwner } author { login } } } } }", json!({"query":format!("repo:{repo} {query}"),"limit":limit}), false)
329 }
330
331 pub fn agent_write(
334 &self,
335 login: &str,
336 key: &str,
337 action: &str,
338 fields: Value,
339 ) -> Result<Value, Error> {
340 check_login(login)?;
341 let item = check_key(key)?;
342 let subject = self.subject(login, &item)?;
343 let mutation = agent_mutation(action, &subject.typename).map_err(invalid)?;
344 let body = agent_mutation_body(mutation, &subject.id, fields).map_err(invalid)?;
345 let credential = self.credentials.github(Some(login))?;
346 let account = transport::account_label(&credential, Some(login));
347 let response = transport::post_graphql(
348 &format!("{}/graphql", self.api_url),
349 &credential,
350 &account,
351 &body,
352 )?;
353 transport::graphql_data(&account, response, false)
354 }
355
356 pub fn with_api_url(mut self, api_url: impl Into<String>) -> Self {
358 self.api_url = api_url.into().trim_end_matches('/').to_owned();
359 self
360 }
361
362 pub fn with_work_account(mut self, login: Option<String>) -> Self {
365 self.work_account = login;
366 self
367 }
368
369 pub fn accounts(&self) -> Result<GitHubAccounts, Error> {
373 let (hosts, credential) = match self.credentials.github_accounts() {
374 Ok(hosts) => {
375 let login = hosts
376 .active
377 .clone()
378 .or_else(|| hosts.logins.first().cloned());
379 let credential = self.credentials.github(login.as_deref())?;
380 (Some(hosts), credential)
381 }
382 Err(_) => (None, self.credentials.github(None)?),
383 };
384 if let (Some(hosts), Source::GhCli { .. } | Source::SignedIn { .. }) =
385 (hosts, &credential.source)
386 {
387 return Ok(hosts);
388 }
389 let login = self.viewer_login(None)?;
390 Ok(GitHubAccounts {
391 logins: vec![login.clone()],
392 active: Some(login),
393 signed_in: Vec::new(),
394 })
395 }
396
397 pub fn viewer_login(&self, login: Option<&str>) -> Result<String, Error> {
399 #[derive(Deserialize)]
400 struct Viewer {
401 login: String,
402 }
403 #[derive(Deserialize)]
404 struct Data {
405 viewer: Viewer,
406 }
407 let data: Data = self.graphql(login, queries::VIEWER_QUERY, json!({}), false)?;
408 Ok(data.viewer.login)
409 }
410
411 pub fn pin_work(&self) -> Result<PinnedWork<'_>, Error> {
418 self.pin_work_for(self.work_account.as_deref())
419 }
420
421 pub fn pin_work_for(&self, account: Option<&str>) -> Result<PinnedWork<'_>, Error> {
423 PinnedWork::pin(self, account)
424 }
425
426 pub fn pin_account(&self, login: &str) -> Result<PinnedWork<'_>, Error> {
429 PinnedWork::for_login(self, login)
430 }
431
432 pub fn work_login(&self) -> Result<String, Error> {
440 self.pin_work().map(|work| work.login().to_owned())
441 }
442
443 pub fn credential(&self, login: Option<&str>) -> Result<Credential, CredentialError> {
446 self.credentials.github(login)
447 }
448
449 fn graphql_value(
450 &self,
451 login: Option<&str>,
452 query: &str,
453 variables: Value,
454 partial: bool,
455 ) -> Result<Value, Error> {
456 let url = format!("{}/graphql", self.api_url);
457 let body = json!({ "query": query, "variables": variables }).to_string();
458 send_with_retry(
459 &self.credentials,
460 |credentials| credentials.github(login),
461 |credential| {
462 let account = transport::account_label(credential, login);
463 let response = transport::post_graphql(&url, credential, &account, &body)?;
464 transport::graphql_data(&account, response, partial)
465 },
466 )
467 }
468
469 fn graphql<T: DeserializeOwned>(
470 &self,
471 login: Option<&str>,
472 query: &str,
473 variables: Value,
474 partial: bool,
475 ) -> Result<T, Error> {
476 let data = self.graphql_value(login, query, variables, partial)?;
477 serde_json::from_value(data).map_err(|_| unexpected("response"))
478 }
479
480 fn rest_url<'a>(
482 &self,
483 segments: impl IntoIterator<Item = &'a str>,
484 query: &[(&str, &str)],
485 ) -> Result<String, Error> {
486 let mut url = url::Url::parse(&self.api_url)
487 .map_err(|_| invalid("The GitHub API URL is not valid."))?;
488 url.path_segments_mut()
489 .map_err(|()| invalid("The GitHub API URL is not valid."))?
490 .pop_if_empty()
491 .extend(segments);
492 if !query.is_empty() {
493 url.query_pairs_mut().extend_pairs(query);
494 }
495 Ok(url.into())
496 }
497
498 fn rest_bytes(
499 &self,
500 login: &str,
501 url: &str,
502 accept: &str,
503 max: usize,
504 ) -> Result<Vec<u8>, Error> {
505 send_with_retry(
506 &self.credentials,
507 |credentials| credentials.github(Some(login)),
508 |credential| {
509 let account = transport::account_label(credential, Some(login));
510 let response = transport::get_rest(url, credential, &account, accept)?;
511 transport::read_limited(response, max)
512 },
513 )
514 }
515
516 fn rest_json<T: DeserializeOwned>(&self, login: &str, url: &str) -> Result<T, Error> {
517 let bytes = self.rest_bytes(login, url, JSON, MAX_BODY_BYTES)?;
519 serde_json::from_slice(&bytes).map_err(|_| unexpected("response"))
520 }
521
522 pub fn section(
528 &self,
529 login: &str,
530 section_id: &str,
531 repos: Option<&[String]>,
532 ) -> Result<SectionResponse, Error> {
533 check_login(login)?;
534 let section = check_section(section_id)?;
535 let repos = if section.repos_only {
536 Some(repos.unwrap_or_default())
537 } else {
538 repos
539 };
540 let searches = scope::searches(section.query, repos)?;
541 let results: Vec<Result<(u32, Vec<model::GhItem>), Error>> = thread::scope(|scope| {
542 let handles: Vec<_> = searches
543 .iter()
544 .map(|query| scope.spawn(|| self.section_search(login, section.kind, query)))
545 .collect();
546 handles
547 .into_iter()
548 .map(|handle| {
549 handle
550 .join()
551 .unwrap_or_else(|_| Err(Error::Network("The request failed.".into())))
552 })
553 .collect()
554 });
555 let (total, items) = scope::merge(results.into_iter().collect::<Result<_, _>>()?);
556 Ok(SectionResponse {
557 account: login.to_owned(),
558 section: section.id.to_owned(),
559 total,
560 items,
561 })
562 }
563
564 fn section_search(
568 &self,
569 login: &str,
570 kind: ItemKind,
571 query: &str,
572 ) -> Result<(u32, Vec<model::GhItem>), Error> {
573 let variables = json!({ "query": query });
574 let search =
576 |query: &str| self.graphql::<SearchData>(Some(login), query, variables.clone(), true);
577 let main_query = queries::section_query();
578 let main = search(&main_query)?.search;
579 let extra_queries =
580 if kind == ItemKind::Pr && !raw::section_items(&main.nodes, &[]).is_empty() {
581 queries::pr_extra_queries().to_vec()
582 } else {
583 Vec::new()
584 };
585 let extras: Vec<SearchData> = thread::scope(|scope| {
586 let handles: Vec<_> = extra_queries
587 .iter()
588 .map(|query| scope.spawn(|| search(query)))
589 .collect();
590 handles
591 .into_iter()
592 .filter_map(|handle| handle.join().ok()?.ok())
593 .collect()
594 });
595 let extra_nodes: Vec<Value> = extras
596 .into_iter()
597 .flat_map(|extra| extra.search.nodes)
598 .collect();
599 let items = raw::section_items(&main.nodes, &raw::extras(&extra_nodes));
600 Ok((main.issue_count, items))
601 }
602
603 pub fn repositories(&self, login: &str, text: &str) -> Result<Vec<GhRepository>, Error> {
607 #[derive(Deserialize)]
608 struct Found {
609 items: Vec<GhRepository>,
610 }
611 check_login(login)?;
612 let text = scope::check_search_text(text)?;
613 if text.is_empty() {
614 let url = self.rest_url(
615 ["user", "repos"],
616 &[
617 ("sort", "pushed"),
618 ("per_page", REPOSITORIES_PER_PAGE),
619 ("affiliation", "owner,collaborator,organization_member"),
620 ],
621 )?;
622 return self.rest_json(login, &url);
623 }
624 let url = self.rest_url(
625 ["search", "repositories"],
626 &[("q", text), ("per_page", REPOSITORIES_PER_PAGE)],
627 )?;
628 Ok(self.rest_json::<Found>(login, &url)?.items)
629 }
630
631 pub fn sections(&self, login: &str) -> Vec<(&'static str, Result<SectionResponse, Error>)> {
633 thread::scope(|scope| {
634 let handles: Vec<_> = SECTIONS
635 .iter()
636 .map(|section| {
637 (
638 section.id,
639 scope.spawn(|| self.section(login, section.id, None)),
640 )
641 })
642 .collect();
643 handles
644 .into_iter()
645 .map(|(id, handle)| {
646 let result = handle
647 .join()
648 .unwrap_or_else(|_| Err(Error::Network("The request failed.".into())));
649 (id, result)
650 })
651 .collect()
652 })
653 }
654
655 fn load_detail(&self, login: &str, item: &ItemRef) -> Result<GhItemDetail, Error> {
656 let variables = json!({ "owner": item.owner, "name": item.name, "number": item.number });
657 let data: RepositoryData<RawDetail> =
658 self.graphql(Some(login), &queries::detail_query(), variables, false)?;
659 detail_from_data(data, login)
660 }
661
662 pub fn item(&self, login: &str, key: &str) -> Result<GhItemDetail, Error> {
664 check_login(login)?;
665 self.load_detail(login, &check_key(key)?)
666 }
667
668 pub fn assignable(&self, login: &str, repo: &str) -> Result<AssignableResponse, Error> {
671 check_login(login)?;
672 let (owner, name) = check_repo(repo)?;
673 #[derive(Deserialize)]
674 #[serde(rename_all = "camelCase")]
675 struct Assignable {
676 assignable_users: Nodes<RawActor>,
677 }
678 #[derive(Deserialize)]
679 struct Data {
680 repository: Option<Assignable>,
681 }
682 let key = format!("gh-assignable:{login}:{owner}/{name}").to_lowercase();
683 let users = self.assignable.get_or_load(&key, || {
684 let variables = json!({ "owner": owner, "name": name });
685 let data: Data =
686 self.graphql(Some(login), queries::ASSIGNABLE_QUERY, variables, false)?;
687 let repository = data.repository.ok_or_else(|| Error::Status {
688 status: http_status::NOT_FOUND,
689 message: "Repository not found on GitHub.".into(),
690 })?;
691 Ok::<_, Error>(raw::assignable_users(&repository.assignable_users))
692 })?;
693 Ok(AssignableResponse { users })
694 }
695
696 fn subject(&self, login: &str, item: &ItemRef) -> Result<Subject, Error> {
697 let variables = json!({ "owner": item.owner, "name": item.name, "number": item.number });
698 let data: RepositoryData<Subject> =
699 self.graphql(Some(login), queries::SUBJECT_QUERY, variables, false)?;
700 data.repository
701 .and_then(|repository| repository.issue_or_pull_request)
702 .ok_or_else(not_found)
703 }
704
705 pub fn review(
708 &self,
709 login: &str,
710 key: &str,
711 event: ReviewEvent,
712 body: &str,
713 ) -> Result<GhItemDetail, Error> {
714 let item = check_key(key)?;
715 let body = check_review_body(event, body)?;
716 let account = self.bind_read(login)?;
717 let variables = json!({ "owner": item.owner, "name": item.name, "number": item.number });
718 let data = account.graphql(queries::SUBJECT_QUERY, variables)?;
719 let data: RepositoryData<Subject> =
720 serde_json::from_value(data).map_err(|_| unexpected("response"))?;
721 let subject = data
722 .repository
723 .and_then(|repository| repository.issue_or_pull_request)
724 .ok_or_else(not_found)?;
725 if subject.typename != "PullRequest" {
726 return Err(invalid("Reviews apply only to pull requests."));
727 }
728 let body = (!body.is_empty()).then_some(body);
729 let variables = json!({ "id": subject.id, "event": event.as_str(), "body": body });
730 account.graphql(queries::REVIEW_MUTATION, variables)?;
731 account.item(key)
732 }
733
734 pub fn default_branch(&self, login: &str, repo: &str) -> Result<String, Error> {
737 check_login(login)?;
738 check_repo(repo)?;
739 let value: Value = self.rest_json(login, &format!("{}/repos/{repo}", self.api_url))?;
740 value
741 .get("default_branch")
742 .and_then(Value::as_str)
743 .map(str::to_owned)
744 .ok_or_else(|| invalid("The repository reports no default branch."))
745 }
746
747 pub fn issue_comment(&self, login: &str, key: &str, body: &str) -> Result<(), Error> {
749 pull_request_writes::issue_comment(self, login, key, body)
750 }
751
752 pub fn close_pull_request(&self, login: &str, key: &str) -> Result<(), Error> {
755 pull_request_writes::close(self, login, key)
756 }
757
758 pub fn merge_pull_request(
761 &self,
762 login: &str,
763 key: &str,
764 target: &model::MergeTarget,
765 ) -> Result<(), Error> {
766 pull_request_writes::merge(self, login, key, target)
767 }
768
769 pub fn comment(&self, login: &str, key: &str, body: &str) -> Result<GhItemDetail, Error> {
772 check_login(login)?;
773 let item = check_key(key)?;
774 let body = validate::check_body(body, true)?;
775 let subject = self.subject(login, &item)?;
776 let variables = json!({ "id": subject.id, "body": body });
777 self.graphql_value(Some(login), queries::COMMENT_MUTATION, variables, false)?;
778 self.load_detail(login, &item)
779 }
780
781 pub fn set_assignees(
785 &self,
786 login: &str,
787 key: &str,
788 add: &[String],
789 remove: &[String],
790 ) -> Result<GhItemDetail, Error> {
791 check_login(login)?;
792 let item = check_key(key)?;
793 let add = check_logins("add", add)?;
794 let remove = check_logins("remove", remove)?;
795 if add.is_empty() && remove.is_empty() {
796 return Err(invalid("add or remove must name at least one login."));
797 }
798 let mut all: Vec<&String> = Vec::new();
799 for user in add.iter().chain(&remove) {
800 if !all.contains(&user) {
801 all.push(user);
802 }
803 }
804 let mut variables =
805 json!({ "owner": item.owner, "name": item.name, "number": item.number });
806 for (index, user) in all.iter().enumerate() {
807 variables[format!("l{index}")] = json!(user);
808 }
809 let data = self.graphql_value(
812 Some(login),
813 &queries::assignee_lookup_query(all.len()),
814 variables,
815 true,
816 )?;
817 let id = data["repository"]["issueOrPullRequest"]["id"]
818 .as_str()
819 .ok_or_else(not_found)?
820 .to_owned();
821 let user_id = |user: &String| -> Result<String, Error> {
822 let index = all
823 .iter()
824 .position(|known| *known == user)
825 .unwrap_or_default();
826 data[format!("u{index}")]["id"]
827 .as_str()
828 .map(str::to_owned)
829 .ok_or_else(|| invalid(format!("Unknown GitHub user: {user}.")))
830 };
831 let add_ids = add.iter().map(user_id).collect::<Result<Vec<_>, _>>()?;
832 let remove_ids = remove.iter().map(user_id).collect::<Result<Vec<_>, _>>()?;
833 let mut variables = json!({ "id": id });
834 if !add_ids.is_empty() {
835 variables["add"] = json!(add_ids);
836 }
837 if !remove_ids.is_empty() {
838 variables["remove"] = json!(remove_ids);
839 }
840 let mutation = queries::assignee_mutation(!add_ids.is_empty(), !remove_ids.is_empty());
841 self.graphql_value(Some(login), &mutation, variables, false)?;
842 self.load_detail(login, &item)
843 }
844
845 pub fn diff(&self, login: &str, key: &str) -> Result<DiffResponse, Error> {
848 check_login(login)?;
849 let item = check_key(key)?;
850 let number = item.number.to_string();
851 let repo = item.repo();
852 let pull_url = self.rest_url(["repos", &item.owner, &item.name, "pulls", &number], &[])?;
853 let pull: RawPull = self.rest_json(login, &pull_url)?;
854 let (head, base_tip) = pull_commits(&pull)?;
855 let cache_key = format!("{login}\n{repo}#{number}@{base_tip}..{head}");
856 if let Some(hit) = self.diffs.get(&cache_key) {
857 return Ok(hit);
858 }
859 let changed_files = pull.changed_files.unwrap_or(0);
860 let (base, mut files) = self.diff_files(&DiffRequest {
861 login,
862 item: &item,
863 base_tip: &base_tip,
864 head: &head,
865 pages: file_pages(changed_files),
866 })?;
867 files.truncate(MAX_DIFF_FILES as usize);
868 let result = DiffResponse {
869 repo,
870 number: item.number,
871 base_sha: base,
872 head_sha: head,
873 total: pull.changed_files.unwrap_or(files.len() as u32),
874 files,
875 };
876 self.diffs.set(cache_key, result.clone());
877 Ok(result)
878 }
879
880 fn diff_files(&self, request: &DiffRequest<'_>) -> Result<(String, Vec<GhDiffFile>), Error> {
883 let DiffRequest {
884 login,
885 item,
886 base_tip,
887 head,
888 pages,
889 } = *request;
890 let number = item.number.to_string();
891 let files_url = |page: u32| {
892 let page = page.to_string();
893 let per_page = FILES_PER_PAGE.to_string();
894 self.rest_url(
895 ["repos", &item.owner, &item.name, "pulls", &number, "files"],
896 &[("per_page", &per_page), ("page", &page)],
897 )
898 };
899 thread::scope(|scope| {
900 let base = scope.spawn(|| self.merge_base(login, item, base_tip, head));
901 let mut files: Vec<GhDiffFile> = Vec::new();
902 let mut first = 1;
903 while first <= pages {
904 let last = (first + PAGE_CONCURRENCY - 1).min(pages);
905 let handles: Vec<_> = (first..=last)
906 .map(|page| {
907 let url = files_url(page);
908 scope.spawn(move || self.rest_json::<Vec<RawPrFile>>(login, &url?))
909 })
910 .collect();
911 let mut short_page = false;
912 for handle in handles {
913 let list = handle
914 .join()
915 .unwrap_or_else(|_| Err(Error::Network("The request failed.".into())))?;
916 short_page |= list.len() < FILES_PER_PAGE as usize;
917 files.extend(list.into_iter().map(raw::to_diff_file));
918 }
919 if short_page {
920 break;
921 }
922 first = last + 1;
923 }
924 let base = base.join().unwrap_or_else(|_| base_tip.to_owned());
925 Ok((base, files))
926 })
927 }
928
929 fn merge_base(&self, login: &str, item: &ItemRef, base: &str, head: &str) -> String {
933 let range = format!("{base}...{head}");
934 let compare = self
935 .rest_url(
936 ["repos", &item.owner, &item.name, "compare", &range],
937 &[("per_page", "1"), ("page", "2")],
938 )
939 .and_then(|url| self.rest_json::<RawCompare>(login, &url));
940 compare
941 .ok()
942 .and_then(|compare| compare.merge_base_commit?.sha)
943 .filter(|sha| is_sha(sha))
944 .unwrap_or_else(|| base.to_owned())
945 }
946
947 fn contents_url(
948 &self,
949 owner: &str,
950 name: &str,
951 sha: &str,
952 path: &str,
953 ) -> Result<String, Error> {
954 let segments = ["repos", owner, name, "contents"]
955 .into_iter()
956 .chain(path.split('/'));
957 self.rest_url(segments, &[("ref", sha)])
958 }
959
960 pub fn file(
963 &self,
964 login: &str,
965 repo: &str,
966 sha: &str,
967 path: &str,
968 ) -> Result<FileResponse, Error> {
969 check_login(login)?;
970 let (owner, name) = check_repo(repo)?;
971 let sha = check_sha(sha)?;
972 let path = check_path(path)?;
973 let key = format!("{login}\n{owner}/{name}@{sha}:{path}");
976 if let Some(text) = self.files.get(&key) {
977 return Ok(FileResponse { text });
978 }
979 let url = self.contents_url(&owner, &name, sha, path)?;
980 let bytes = self.rest_bytes(login, &url, RAW, MAX_FILE_BYTES)?;
981 if bytes.contains(&0) {
982 return Err(Error::Status {
983 status: http_status::UNSUPPORTED_MEDIA_TYPE,
984 message: "The file is binary.".into(),
985 });
986 }
987 let text = String::from_utf8_lossy(&bytes).into_owned();
988 self.files.set(key, text.clone());
989 Ok(FileResponse { text })
990 }
991
992 pub fn image(&self, login: &str, repo: &str, sha: &str, path: &str) -> Result<Image, Error> {
995 check_login(login)?;
996 let (owner, name) = check_repo(repo)?;
997 let sha = check_sha(sha)?;
998 let path = check_path(path)?;
999 let content_type = image_type(path).ok_or_else(|| Error::Status {
1000 status: http_status::UNSUPPORTED_MEDIA_TYPE,
1001 message: "The file is not a supported image.".into(),
1002 })?;
1003 let url = self.contents_url(&owner, &name, sha, path)?;
1004 let bytes = self.rest_bytes(login, &url, RAW, MAX_IMAGE_BYTES)?;
1005 Ok(Image {
1006 content_type,
1007 bytes,
1008 })
1009 }
1010}
1011
1012fn detail_from_data(data: RepositoryData<RawDetail>, login: &str) -> Result<GhItemDetail, Error> {
1013 let repository = data.repository.ok_or_else(not_found)?;
1014 let node = repository.issue_or_pull_request.ok_or_else(not_found)?;
1015 let mut detail = raw::to_detail(&node);
1016 detail.merge_target = repository.merge_settings.target(&node, &detail.item);
1017 detail.viewer_approved = raw::viewer_approved(&node, login);
1018 Ok(detail)
1019}
1020
1021fn pick_work_login<'a>(logins: &'a [String], chosen: Option<&str>) -> Option<&'a String> {
1023 chosen
1024 .and_then(|chosen| {
1025 logins
1026 .iter()
1027 .find(|login| login.eq_ignore_ascii_case(chosen))
1028 })
1029 .or_else(|| {
1030 logins.iter().find(|login| {
1031 login.rsplit_once('_').is_some_and(|(_, code)| {
1032 !code.is_empty() && code.bytes().all(|byte| byte.is_ascii_alphanumeric())
1033 })
1034 })
1035 })
1036}
1037
1038fn verified_work_login(login: &str, actual: &str) -> Result<String, Error> {
1040 if actual != login {
1041 return Err(Error::Status {
1042 status: http_status::BAD_GATEWAY,
1043 message: "The selected work GitHub credential belongs to another account.".into(),
1044 });
1045 }
1046 Ok(login.to_owned())
1047}
1048
1049pub fn file_pages(changed_files: u32) -> u32 {
1052 changed_files
1053 .clamp(1, MAX_DIFF_FILES)
1054 .div_ceil(FILES_PER_PAGE)
1055}
1056
1057#[cfg(test)]
1058mod tests;