Skip to main content

ai6_source_github/
lib.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! `ai6-source-github`: the `github` provider. As a Source it lists the open issues (and
6//! pull requests) of one repository that carry the configured labels; as a Tracker it reads,
7//! comments on, labels, closes and creates issues of that repository. Requests are blocking;
8//! the host calls them off its async runtime.
9
10#![doc = include_str!("../README.md")]
11#![forbid(unsafe_code)]
12#![warn(missing_docs)]
13
14ai6::guatiao::providers!(Github);
15
16use std::collections::BTreeMap;
17use std::path::PathBuf;
18use std::sync::Mutex;
19use std::time::{Duration, Instant};
20
21use ai6::guatiao::library::ProviderError;
22use ai6::guatiao::{FromValue, Provider, Schema, Status, ToValue};
23use ai6::{
24    IssueSpec, PostedComment, Reply, ReplyBatch, ReplyPoll, Source, SourceBatch, SourceFacts,
25    SourceItem, SourcePoll, Tracker, TrackerCapabilities, TrackerIssue, TrackerLink, TrackerPost,
26    TrackerUpdate, settled_cursor,
27};
28use serde::{Deserialize, Serialize};
29use url::Url;
30
31/// The provider ID an Operation names under `sources`.
32pub const PROVIDER_ID: &str = "github";
33
34/// The REST API version asked for. Creating an issue under `2022-11-28` answers `Deprecation`
35/// with a sunset of 2028-03-10; this one answers the same fields less the singular `assignee`.
36const API_VERSION: &str = "2026-03-10";
37
38/// The `Accept` of the API's JSON, and of a file's own text.
39const JSON_ACCEPT: &str = "application/vnd.github+json";
40const RAW_ACCEPT: &str = "application/vnd.github.raw+json";
41
42// What starts the ID of a review comment, whose numbers are not the conversation comments'.
43use ai6::REVIEW_REPLY_PREFIX as REVIEW_ID_PREFIX;
44
45/// What marks a comment the provider posted, whoever the token turns out to be.
46const MARKER_PREFIX: &str = "<!-- ai6:";
47
48/// One instance's settings, from `[operation.<id>.sources.<name>]`.
49///
50/// The Station reads its own keys (`provider`, `intake`, `interval_secs`, the status maps and
51/// what Agents may touch) and passes the rest here.
52#[derive(Debug, Clone, ToValue, FromValue, Schema)]
53#[map(crate = ::ai6::guatiao, deny_unknown_fields)]
54pub struct Settings {
55    /// `owner/name`; a bare string under `sources` is this value.
56    #[schema(title = "Repository")]
57    #[map(default)]
58    repo: String,
59    /// Another spelling of `repo`, which a bare string under `sources` is; set at most one.
60    #[schema(title = "Target")]
61    target: Option<String>,
62    /// An issue needs every one of these labels to become a Mission.
63    #[schema(title = "Intake labels")]
64    #[map(default = vec!["ai6:ready".to_owned()])]
65    labels: Vec<String>,
66    /// Only issues assigned to this login, when set.
67    #[schema(title = "Assignee")]
68    assignee: Option<String>,
69    /// The environment variable holding the token; the token itself is never configured.
70    #[schema(
71        title = "Token variable",
72        format = "credential-variable:GITHUB_TOKEN,GH_TOKEN,GITHUB_ENTERPRISE_TOKEN,GH_ENTERPRISE_TOKEN"
73    )]
74    #[map(default = "GITHUB_TOKEN".to_owned())]
75    token_env: String,
76    /// The REST API root; `https`, or `http` on a loopback address.
77    #[schema(title = "API address")]
78    #[map(default = "https://api.github.com".to_owned())]
79    api_url: String,
80    /// A PEM file of certificate authorities to trust besides the public roots, by absolute path.
81    /// A set one is reported as a weakening: more authorities can vouch for this service.
82    #[schema(title = "Certificate authorities")]
83    ca_file: Option<PathBuf>,
84    /// Seconds one request may take. 0 is refused.
85    #[schema(title = "A request may take", format = "seconds")]
86    #[map(default = 30)]
87    request_timeout_secs: u64,
88    /// Issues asked for per page. 0 is refused.
89    #[schema(title = "Issues per page")]
90    #[map(default = 100)]
91    page_size: u32,
92    /// Pages one poll reads at most. 0 is refused.
93    #[schema(title = "Pages per poll")]
94    #[map(default = 5)]
95    max_pages: u64,
96    /// Seconds a poll searches behind the cursor, for an issue the listing showed after a newer
97    /// one. 0 searches from the cursor.
98    #[schema(title = "Search behind the cursor by", format = "seconds")]
99    #[map(default = 60)]
100    settling_secs: u64,
101    /// GitHub logins besides the issue's author and the associations below whose comments
102    /// may answer a question.
103    #[schema(title = "People who may answer")]
104    #[map(default)]
105    reply_authors: Vec<String>,
106    /// `author_association` values whose comments may answer a question.
107    #[schema(title = "Associations that may answer")]
108    #[map(default = ["OWNER", "MEMBER", "COLLABORATOR"].map(str::to_owned).to_vec())]
109    reply_associations: Vec<String>,
110    /// Read the line comments of pull requests' reviews as replies, and find a pull request by
111    /// its head branch. Off, only the conversation's comments are read.
112    #[schema(title = "Read review comments")]
113    #[map(default = true)]
114    review_comments: bool,
115    /// Skip review comments written by the token's own login, taking them for the Agent's own.
116    /// Off, the token's review comments count when its login may answer.
117    #[schema(title = "Skip the token's own review comments")]
118    #[map(default = true)]
119    ignore_own_review_comments: bool,
120    /// How long, in seconds, the repository's labels and settings are remembered.
121    #[schema(title = "Remember the repository for", format = "seconds")]
122    #[map(default = 600)]
123    capability_ttl_secs: u64,
124    /// The page people read the issues on as a board, such as a Projects board; the repository's
125    /// own issues page when unset. `https`.
126    #[schema(title = "Board address")]
127    board_url: Option<String>,
128}
129
130/// GitHub issues as an AI6 Source and Tracker.
131#[derive(Debug, Provider)]
132#[provider(
133    Source,
134    Tracker,
135    id = "github",
136    name = "GitHub issues",
137    config = Settings,
138    crate = ::ai6::guatiao
139)]
140pub struct Github {
141    settings: Settings,
142    api: Url,
143    agent: ureq::Agent,
144    /// The repository-level capabilities and when they were read.
145    capabilities: Mutex<Option<(Instant, TrackerCapabilities)>>,
146    /// The token's own login, once asked for: `Some(None)` when GitHub gave none.
147    login: Mutex<Option<Option<String>>>,
148}
149
150impl Github {
151    /// Builds the provider from the instance's settings.
152    ///
153    /// # Errors
154    ///
155    /// Returns a message for an unknown key, a malformed repository name or an insecure
156    /// API address.
157    pub fn new(mut settings: Settings) -> Result<Self, String> {
158        if let Some(target) = settings.target.take() {
159            if !settings.repo.is_empty() {
160                return Err("set `repo` or `target`, not both".to_owned());
161            }
162            settings.repo = target;
163        }
164        let valid_part = |part: &str| {
165            !part.is_empty()
166                && part
167                    .chars()
168                    .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
169        };
170        match settings.repo.split_once('/') {
171            Some((owner, name)) if valid_part(owner) && valid_part(name) => {}
172            _ => return Err("repo must be `owner/name`".to_owned()),
173        }
174        if settings.token_env.trim().is_empty() {
175            return Err("token_env must name an environment variable".to_owned());
176        }
177        let api = Url::parse(settings.api_url.trim_end_matches('/'))
178            .map_err(|e| format!("api_url: {e}"))?;
179        let loopback = matches!(api.host_str(), Some("localhost" | "127.0.0.1" | "[::1]"));
180        if api.scheme() != "https" && !(api.scheme() == "http" && loopback) {
181            return Err("api_url must be https (http only on a loopback address)".to_owned());
182        }
183        if let Some(board) = &settings.board_url {
184            https_page(board).map_err(|e| format!("board_url: {e}"))?;
185        }
186        for (name, zero) in [
187            ("request_timeout_secs", settings.request_timeout_secs == 0),
188            ("page_size", settings.page_size == 0),
189            ("max_pages", settings.max_pages == 0),
190        ] {
191            if zero {
192                return Err(format!("{name} must be at least 1"));
193            }
194        }
195        let mut agent = ureq::Agent::config_builder()
196            .timeout_global(Some(Duration::from_secs(settings.request_timeout_secs)))
197            .max_redirects(0)
198            .http_status_as_error(false);
199        if let Some(ca_file) = &settings.ca_file {
200            agent = agent.tls_config(ai6::tls::trusting_file(ca_file)?);
201        }
202        let agent = agent.build().into();
203        Ok(Self {
204            settings,
205            api,
206            agent,
207            capabilities: Mutex::new(None),
208            login: Mutex::new(None),
209        })
210    }
211
212    /// The site the API address belongs to: github.com for the public API, the host of a GitHub
213    /// Enterprise `.../api/v3` root; none for any other root, or one not served over `https`.
214    fn web_origin(&self) -> Option<String> {
215        let origin = match self.api.path().trim_end_matches('/') {
216            "" if self.api.host_str() == Some("api.github.com") => "https://github.com".to_owned(),
217            "/api/v3" => {
218                format!("{}://{}", self.api.scheme(), self.api.host_str()?)
219                    + &self
220                        .api
221                        .port()
222                        .map(|port| format!(":{port}"))
223                        .unwrap_or_default()
224            }
225            _ => return None,
226        };
227        (self.api.scheme() == "https").then_some(origin)
228    }
229
230    /// The repository's issues page on the web.
231    fn issues_page(&self) -> Option<String> {
232        self.web_origin()
233            .map(|origin| format!("{origin}/{}/issues", self.settings.repo))
234    }
235
236    fn endpoint(&self, path: &str) -> String {
237        format!("{}{path}", self.api.as_str().trim_end_matches('/'))
238    }
239
240    fn token(&self) -> Option<String> {
241        std::env::var(&self.settings.token_env)
242            .ok()
243            .filter(|token| !token.trim().is_empty())
244    }
245
246    /// One request, answered with whatever status GitHub gave. Reads go without a token when
247    /// none is set (public repositories); any other method needs one.
248    fn send<B: Serialize + ?Sized>(
249        &self,
250        method: &str,
251        url: &str,
252        query: &[(&str, String)],
253        body: Option<&B>,
254    ) -> Result<ureq::http::Response<ureq::Body>, ProviderError> {
255        self.send_as(JSON_ACCEPT, method, url, query, body)
256    }
257
258    /// [`Github::send`] asking for the representation `accept` names.
259    fn send_as<B: Serialize + ?Sized>(
260        &self,
261        accept: &str,
262        method: &str,
263        url: &str,
264        query: &[(&str, String)],
265        body: Option<&B>,
266    ) -> Result<ureq::http::Response<ureq::Body>, ProviderError> {
267        let mut url = Url::parse(url).map_err(|e| failure(&format!("bad address: {e}")))?;
268        for (key, value) in query {
269            url.query_pairs_mut().append_pair(key, value);
270        }
271        let mut request = ureq::http::Request::builder()
272            .method(method)
273            .uri(url.as_str())
274            .header("Accept", accept)
275            .header("X-GitHub-Api-Version", API_VERSION)
276            .header("User-Agent", "ai6-source-github");
277        match self.token() {
278            Some(token) => request = request.header("Authorization", format!("Bearer {token}")),
279            None if method != "GET" => {
280                return Err(failure(&format!(
281                    "no token: set the environment variable {}",
282                    self.settings.token_env
283                )));
284            }
285            None => {}
286        }
287        let bytes = match body {
288            Some(body) => {
289                request = request.header("Content-Type", "application/json");
290                serde_json::to_vec(body).map_err(|e| failure(&e.to_string()))?
291            }
292            None => Vec::new(),
293        };
294        let request = request
295            .body(bytes)
296            .map_err(|e| failure(&format!("bad request: {e}")))?;
297        self.agent
298            .run(request)
299            .map_err(|e| failure(&format!("request failed: {e}")))
300    }
301
302    /// One request whose status must be a success.
303    fn call<B: Serialize + ?Sized>(
304        &self,
305        method: &str,
306        url: &str,
307        query: &[(&str, String)],
308        body: Option<&B>,
309    ) -> Result<ureq::http::Response<ureq::Body>, ProviderError> {
310        let response = self.send(method, url, query, body)?;
311        self.check(&response)?;
312        Ok(response)
313    }
314
315    fn get(
316        &self,
317        url: &str,
318        query: &[(&str, String)],
319    ) -> Result<ureq::http::Response<ureq::Body>, ProviderError> {
320        self.call("GET", url, query, None::<&()>)
321    }
322
323    fn get_json<T: serde::de::DeserializeOwned>(
324        &self,
325        url: &str,
326        query: &[(&str, String)],
327    ) -> Result<T, ProviderError> {
328        read_json(self.get(url, query)?)
329    }
330
331    fn check(&self, response: &ureq::http::Response<ureq::Body>) -> Result<(), ProviderError> {
332        let status = response.status().as_u16();
333        let header = |name: &str| {
334            response
335                .headers()
336                .get(name)
337                .and_then(|value| value.to_str().ok())
338        };
339        match status {
340            200..=299 => Ok(()),
341            429 => Err(failure(&format!(
342                "GitHub rate limit reached; retry after {}s",
343                header("retry-after").unwrap_or("60")
344            ))),
345            403 if header("x-ratelimit-remaining") == Some("0") => Err(failure(&format!(
346                "GitHub rate limit exhausted; the quota resets at epoch second {}",
347                header("x-ratelimit-reset").unwrap_or("unknown")
348            ))),
349            401 | 403 => Err(failure(&format!(
350                "GitHub refused the token in {}",
351                self.settings.token_env
352            ))),
353            // A private repository answers 404, not 401, to a request with no token.
354            404 if self.token().is_none() => Err(failure(&format!(
355                "GitHub does not show this repository or issue without a token: \
356                 set the environment variable {}",
357                self.settings.token_env
358            ))),
359            404 => Err(failure(
360                "GitHub does not show this repository or issue to the token",
361            )),
362            410 => Err(failure("GitHub has issues disabled for this repository")),
363            422 => Err(failure("GitHub rejected the request as invalid")),
364            other => Err(failure(&format!("GitHub answered status {other}"))),
365        }
366    }
367
368    fn issues_url(&self) -> String {
369        self.endpoint(&format!("/repos/{}/issues", self.settings.repo))
370    }
371
372    /// The issue number of `item`, which must name this instance's repository.
373    fn number(&self, item: &str) -> Result<u64, ProviderError> {
374        let (repo, number) = item
375            .rsplit_once('#')
376            .ok_or_else(|| bad_value(&format!("{item:?} is not an issue ID like owner/name#1")))?;
377        let number = number
378            .parse::<u64>()
379            .map_err(|_| bad_value(&format!("{item:?} has no issue number")))?;
380        if !repo.eq_ignore_ascii_case(&self.settings.repo) {
381            return Err(bad_value(&format!(
382                "foreign item {item:?}: this instance serves {}",
383                self.settings.repo
384            )));
385        }
386        Ok(number)
387    }
388
389    fn issue_url(&self, number: u64) -> String {
390        format!("{}/{number}", self.issues_url())
391    }
392
393    fn repo_capabilities(&self) -> Result<TrackerCapabilities, ProviderError> {
394        let ttl = Duration::from_secs(self.settings.capability_ttl_secs);
395        if let Ok(cache) = self.capabilities.lock()
396            && let Some((at, capabilities)) = cache.as_ref()
397            && at.elapsed() < ttl
398        {
399            return Ok(capabilities.clone());
400        }
401        let response = self.get(
402            &self.endpoint(&format!("/repos/{}", self.settings.repo)),
403            &[],
404        )?;
405        let scopes = response
406            .headers()
407            .get("x-oauth-scopes")
408            .and_then(|value| value.to_str().ok())
409            .map(str::to_owned);
410        let repo: RepoDto = read_json(response)?;
411        let archived = repo.archived.unwrap_or(false);
412        let visibility = match repo.private {
413            Some(true) => "private",
414            Some(false) => "public",
415            None => "unknown",
416        };
417        let mut labels = Vec::new();
418        let mut url = self.endpoint(&format!("/repos/{}/labels", self.settings.repo));
419        let mut first = true;
420        for _ in 0..self.settings.max_pages {
421            let response = self.get(
422                &url,
423                &if first {
424                    vec![("per_page", self.settings.page_size.to_string())]
425                } else {
426                    Vec::new()
427                },
428            )?;
429            first = false;
430            let next = next_link(response.headers().get("link").and_then(|v| v.to_str().ok()))
431                .filter(|next| same_origin(next, &self.api));
432            let page: Vec<LabelDto> = read_json(response)?;
433            labels.extend(page.into_iter().map(|label| label.name));
434            match next {
435                Some(next) => url = next,
436                None => break,
437            }
438        }
439        let writes = !archived && token_writes(scopes.as_deref(), visibility);
440        let capabilities = TrackerCapabilities {
441            comment: writes,
442            edit_comment: writes,
443            labels,
444            free_labels: false,
445            transitions: Vec::new(),
446            assign: writes,
447            close: writes,
448            create: writes && repo.has_issues.unwrap_or(true),
449            issue_types: Vec::new(),
450            priorities: Vec::new(),
451            children: "sub_issues".to_owned(),
452            links: Vec::new(),
453            replies: true,
454            visibility: visibility.to_owned(),
455            markers: true,
456        };
457        if let Ok(mut cache) = self.capabilities.lock() {
458            *cache = Some((Instant::now(), capabilities.clone()));
459        }
460        Ok(capabilities)
461    }
462
463    /// The login the token belongs to, read once; `None` when GitHub does not say.
464    fn token_login(&self) -> Option<String> {
465        let mut known = self.login.lock().ok()?;
466        known
467            .get_or_insert_with(|| {
468                self.get_json::<UserDto>(&self.endpoint("/user"), &[])
469                    .ok()
470                    .map(|user| user.login)
471            })
472            .clone()
473    }
474
475    /// The issue behind `number`, for the author rule of repliers.
476    fn author_of(&self, number: u64) -> Option<String> {
477        self.get_json::<IssueAuthorDto>(&self.issue_url(number), &[])
478            .ok()?
479            .user
480            .map(|user| user.login)
481    }
482
483    fn unsupported(what: &str, can: &str) -> ProviderError {
484        ProviderError::new(
485            Status::GUATIAO_ERR_UNSUPPORTED,
486            &format!("GitHub cannot {what}; it can {can}"),
487        )
488    }
489}
490
491impl TryFrom<Settings> for Github {
492    type Error = ProviderError;
493
494    fn try_from(settings: Settings) -> Result<Self, Self::Error> {
495        Self::new(settings).map_err(|e| ProviderError::new(Status::GUATIAO_ERR_BAD_VALUE, &e))
496    }
497}
498
499impl Github {
500    /// The issues changed since `since`, oldest change first, and whether more remain past the
501    /// pages one poll reads.
502    fn changed_issues(
503        &self,
504        since: Option<&str>,
505    ) -> Result<(Vec<SourceItem>, bool), ProviderError> {
506        let mut query = vec![
507            ("state", "open".to_owned()),
508            ("sort", "updated".to_owned()),
509            ("direction", "asc".to_owned()),
510            ("per_page", self.settings.page_size.to_string()),
511        ];
512        if !self.settings.labels.is_empty() {
513            query.push(("labels", self.settings.labels.join(",")));
514        }
515        if let Some(assignee) = &self.settings.assignee {
516            query.push(("assignee", assignee.clone()));
517        }
518        if let Some(since) = since {
519            query.push(("since", since.to_owned()));
520        }
521
522        let mut items = Vec::new();
523        let mut url = self.issues_url();
524        let mut first = true;
525        let mut more = false;
526        for _ in 0..self.settings.max_pages {
527            let response = self.get(&url, if first { &query } else { &[] })?;
528            first = false;
529            let next = next_link(response.headers().get("link").and_then(|v| v.to_str().ok()))
530                .filter(|next| same_origin(next, &self.api));
531            let exhausted = response
532                .headers()
533                .get("x-ratelimit-remaining")
534                .and_then(|value| value.to_str().ok())
535                == Some("0");
536            let page: Vec<IssueDto> = read_json(response)?;
537            items.extend(
538                page.into_iter()
539                    .map(|issue| item_of(&self.settings.repo, issue)),
540            );
541            more = next.is_some();
542            match next {
543                Some(next) if !exhausted => url = next,
544                _ => break,
545            }
546        }
547        Ok((items, more))
548    }
549}
550
551impl Github {
552    /// A file or directory of the repository by its path, `None` when the repository has none
553    /// there. `raw` asks for a file's text, not the listing's JSON.
554    fn contents(&self, path: &str, raw: bool) -> Result<Option<String>, ProviderError> {
555        let url = self.endpoint(&format!("/repos/{}/contents/{path}", self.settings.repo));
556        let accept = if raw { RAW_ACCEPT } else { JSON_ACCEPT };
557        let response = self.send_as(accept, "GET", &url, &[], None::<&()>)?;
558        if response.status().as_u16() == 404 {
559            return Ok(None);
560        }
561        self.check(&response)?;
562        response
563            .into_body()
564            .read_to_string()
565            .map(Some)
566            .map_err(|e| failure(&format!("could not read {path}: {e}")))
567    }
568}
569
570impl Source for Github {
571    fn issue_templates(&self) -> Result<Vec<String>, ProviderError> {
572        let mut templates = Vec::new();
573        let url = self.endpoint(&format!(
574            "/repos/{}/contents/.github/ISSUE_TEMPLATE",
575            self.settings.repo
576        ));
577        let response = self.send_as(JSON_ACCEPT, "GET", &url, &[], None::<&()>)?;
578        if response.status().as_u16() != 404 {
579            self.check(&response)?;
580            let listing: Vec<ContentEntryDto> = read_json(response)?;
581            let files = listing.into_iter().filter_map(|entry| {
582                (entry.kind == "file" && entry.path.to_ascii_lowercase().ends_with(".md"))
583                    .then_some(entry.path)
584            });
585            for path in files {
586                templates.extend(self.contents(&path, true)?);
587            }
588        }
589        templates.extend(self.contents(".github/ISSUE_TEMPLATE.md", true)?);
590        Ok(templates)
591    }
592
593    fn poll(&self, request: SourcePoll) -> Result<SourceBatch, ProviderError> {
594        let since = request.cursor.as_deref().map(|cursor| {
595            settled_cursor(cursor, self.settings.settling_secs).unwrap_or_else(|| cursor.to_owned())
596        });
597        let (mut items, more) = self.changed_issues(since.as_deref())?;
598        // Pages filled by what the margin repeats would keep every poll from what follows them.
599        if more
600            && since != request.cursor
601            && !items
602                .iter()
603                .any(|item| Some(item.updated.as_str()) > request.cursor.as_deref())
604        {
605            items = self.changed_issues(request.cursor.as_deref())?.0;
606        }
607        // What the margin repeats is older than the cursor, which never moves back for it.
608        let cursor = items
609            .iter()
610            .map(|item| item.updated.clone())
611            .chain(request.cursor)
612            .max();
613        Ok(SourceBatch { items, cursor })
614    }
615
616    fn board_url(&self) -> Result<Option<String>, ProviderError> {
617        Ok(self
618            .settings
619            .board_url
620            .clone()
621            .or_else(|| self.issues_page()))
622    }
623
624    fn facts(&self) -> Result<SourceFacts, ProviderError> {
625        let mut hosts: Vec<String> = self
626            .api
627            .host_str()
628            .map(str::to_lowercase)
629            .into_iter()
630            .collect();
631        hosts.push("github.com".to_owned());
632        let mut credential_variables = vec![self.settings.token_env.clone()];
633        credential_variables.extend(CLI_TOKEN_VARIABLES.map(str::to_owned));
634        credential_variables.sort();
635        credential_variables.dedup();
636        Ok(SourceFacts {
637            web: self
638                .web_origin()
639                .map(|origin| format!("{origin}/{}", self.settings.repo)),
640            project: None,
641            intake_labels: self.settings.labels.clone(),
642            hosts,
643            credential_variables,
644        })
645    }
646}
647
648/// The variables the `gh` command line tool reads its token from, beside the one configured.
649const CLI_TOKEN_VARIABLES: [&str; 4] = [
650    "GITHUB_TOKEN",
651    "GH_TOKEN",
652    "GITHUB_ENTERPRISE_TOKEN",
653    "GH_ENTERPRISE_TOKEN",
654];
655
656impl Tracker for Github {
657    fn capabilities(&self, item: Option<String>) -> Result<TrackerCapabilities, ProviderError> {
658        let mut capabilities = self.repo_capabilities()?;
659        if let Some(item) = item {
660            let number = self.number(&item)?;
661            let probe = self.call(
662                "GET",
663                &format!("{}/sub_issues", self.issue_url(number)),
664                &[("per_page", "1".to_owned())],
665                None::<&()>,
666            );
667            if probe.is_err() {
668                capabilities.children = "none".to_owned();
669            }
670        }
671        Ok(capabilities)
672    }
673
674    fn issue(&self, item: String) -> Result<TrackerIssue, ProviderError> {
675        let number = self.number(&item)?;
676        let issue: IssueDto = self.get_json(&self.issue_url(number), &[])?;
677        Ok(issue_of(&self.settings.repo, issue))
678    }
679
680    fn replies(&self, request: ReplyPoll) -> Result<ReplyBatch, ProviderError> {
681        let wanted: Vec<u64> = request
682            .items
683            .iter()
684            .map(|item| self.number(item))
685            .collect::<Result<_, _>>()?;
686        if wanted.is_empty() {
687            return Ok(ReplyBatch {
688                replies: Vec::new(),
689                cursor: request.since,
690            });
691        }
692        let mut replies = Vec::new();
693        let mut cursor = request.since.clone();
694        let mut issue_authors: BTreeMap<u64, Option<String>> = BTreeMap::new();
695        // Comments on the conversation, then the line comments of pull requests' reviews.
696        let feeds = [(false, "issues/comments"), (true, "pulls/comments")];
697        for (review, path) in feeds {
698            if review && !self.settings.review_comments {
699                continue;
700            }
701            let mut query = vec![
702                ("sort", "updated".to_owned()),
703                ("direction", "asc".to_owned()),
704                ("per_page", self.settings.page_size.to_string()),
705            ];
706            if let Some(since) = &request.since {
707                query.push(("since", since.clone()));
708            }
709            let mut url = self.endpoint(&format!("/repos/{}/{path}", self.settings.repo));
710            let mut first = true;
711            for _ in 0..self.settings.max_pages {
712                let response = self.get(&url, if first { &query } else { &[] })?;
713                first = false;
714                let next = next_link(response.headers().get("link").and_then(|v| v.to_str().ok()))
715                    .filter(|next| same_origin(next, &self.api));
716                let page: Vec<CommentDto> = read_json(response)?;
717                for comment in page {
718                    if let Some(updated) = comment.updated_at.as_deref()
719                        && cursor.as_deref().is_none_or(|current| updated > current)
720                    {
721                        cursor = Some(updated.to_owned());
722                    }
723                    let parent = if review {
724                        comment.pull_request_url.as_deref()
725                    } else {
726                        comment.issue_url.as_deref()
727                    };
728                    let Some(number) = parent.and_then(trailing_number) else {
729                        continue;
730                    };
731                    if !wanted.contains(&number) {
732                        continue;
733                    }
734                    let login = comment.user.map(|user| user.login).unwrap_or_default();
735                    let association = comment.author_association.as_deref().unwrap_or_default();
736                    let permitted = self
737                        .settings
738                        .reply_associations
739                        .iter()
740                        .any(|allowed| allowed.eq_ignore_ascii_case(association))
741                        || self
742                            .settings
743                            .reply_authors
744                            .iter()
745                            .any(|allowed| allowed.eq_ignore_ascii_case(&login))
746                        || issue_authors
747                            .entry(number)
748                            .or_insert_with(|| self.author_of(number))
749                            .as_deref()
750                            .is_some_and(|author| author.eq_ignore_ascii_case(&login));
751                    let id = comment.id.to_string();
752                    let mut body = comment.body.unwrap_or_default();
753                    // By the marker alone: the token may be a person's, whose replies count. A
754                    // review comment has no marker, so the token's own are skipped by default.
755                    let marked = body.contains(MARKER_PREFIX);
756                    let own = marked
757                        || (review
758                            && self.settings.ignore_own_review_comments
759                            && self
760                                .token_login()
761                                .is_some_and(|me| me.eq_ignore_ascii_case(&login)));
762                    if review && let Some(file) = comment.path {
763                        let line = comment.line.or(comment.original_line);
764                        let place = match line {
765                            Some(line) => format!("{file}:{line}"),
766                            None => file,
767                        };
768                        body = format!("On {place}:\n{body}");
769                    }
770                    replies.push(Reply {
771                        id: if review {
772                            format!("{REVIEW_ID_PREFIX}{id}")
773                        } else {
774                            id
775                        },
776                        item: format!("{}#{number}", self.settings.repo),
777                        author_id: login.clone(),
778                        author: login,
779                        permitted,
780                        own,
781                        body,
782                        created: comment.created_at.unwrap_or_default(),
783                    });
784                }
785                match next {
786                    Some(next) => url = next,
787                    None => break,
788                }
789            }
790        }
791        replies.sort_by(|a, b| a.created.cmp(&b.created));
792        Ok(ReplyBatch { replies, cursor })
793    }
794
795    fn pull_for_branch(&self, branch: String) -> Result<Option<String>, ProviderError> {
796        if !self.settings.review_comments || branch.trim().is_empty() {
797            return Ok(None);
798        }
799        let owner = self.settings.repo.split('/').next().unwrap_or_default();
800        let found: Vec<PullSummaryDto> = self.get_json(
801            &self.endpoint(&format!("/repos/{}/pulls", self.settings.repo)),
802            &[
803                ("head", format!("{owner}:{branch}")),
804                ("state", "open".to_owned()),
805                ("per_page", "1".to_owned()),
806            ],
807        )?;
808        Ok(found
809            .first()
810            .map(|pull| format!("{}#{}", self.settings.repo, pull.number)))
811    }
812
813    fn post(&self, post: TrackerPost) -> Result<PostedComment, ProviderError> {
814        let number = self.number(&post.item)?;
815        if post.body.trim().is_empty() {
816            return Err(bad_value(
817                "the comment is empty, and GitHub refuses such a comment",
818            ));
819        }
820        let mut body = post.body;
821        let marker: String = post
822            .marker
823            .as_deref()
824            .unwrap_or("comment")
825            .chars()
826            .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | ':' | '.'))
827            .collect();
828        body.push_str(&format!("\n\n{MARKER_PREFIX}{marker} -->"));
829        let payload = CommentBodyRequest { body };
830        let comment: PostedCommentDto = match &post.edit {
831            Some(id) => {
832                if id.is_empty() || !id.bytes().all(|b| b.is_ascii_digit()) {
833                    return Err(bad_value("a comment ID is a number"));
834                }
835                read_json(self.call(
836                    "PATCH",
837                    &self.endpoint(&format!(
838                        "/repos/{}/issues/comments/{id}",
839                        self.settings.repo
840                    )),
841                    &[],
842                    Some(&payload),
843                )?)?
844            }
845            None => read_json(self.call(
846                "POST",
847                &format!("{}/comments", self.issue_url(number)),
848                &[],
849                Some(&payload),
850            )?)?,
851        };
852        Ok(PostedComment {
853            id: comment.id.to_string(),
854            url: comment.html_url,
855        })
856    }
857
858    fn update(&self, update: TrackerUpdate) -> Result<(), ProviderError> {
859        let number = self.number(&update.item)?;
860        if update.transition.is_some() {
861            return Err(Self::unsupported(
862                "make a workflow transition",
863                "set the state to open or closed",
864            ));
865        }
866        let base = self.issue_url(number);
867        if !update.add_labels.is_empty() {
868            self.call(
869                "POST",
870                &format!("{base}/labels"),
871                &[],
872                Some(&LabelsRequest {
873                    labels: &update.add_labels,
874                }),
875            )?;
876        }
877        for label in &update.remove_labels {
878            let mut response = self.send(
879                "DELETE",
880                &format!("{base}/labels/{}", encode_segment(label)),
881                &[],
882                None::<&()>,
883            )?;
884            if response.status().as_u16() == 404 {
885                // A label the issue lacks is the state asked for, but a missing issue is not:
886                // GitHub tells them apart only in the message.
887                let answer: Option<ErrorMessageDto> = response.body_mut().read_json().ok();
888                if answer.and_then(|a| a.message).as_deref() == Some("Label does not exist") {
889                    continue;
890                }
891                return Err(failure(
892                    "GitHub does not show this repository or issue to the token",
893                ));
894            }
895            self.check(&response)?;
896        }
897        if !update.add_assignees.is_empty() {
898            self.call(
899                "POST",
900                &format!("{base}/assignees"),
901                &[],
902                Some(&AssigneesRequest {
903                    assignees: &update.add_assignees,
904                }),
905            )?;
906        }
907        if !update.remove_assignees.is_empty() {
908            self.call(
909                "DELETE",
910                &format!("{base}/assignees"),
911                &[],
912                Some(&AssigneesRequest {
913                    assignees: &update.remove_assignees,
914                }),
915            )?;
916        }
917        match update.state.as_deref() {
918            None => {}
919            Some("closed") => {
920                self.call(
921                    "PATCH",
922                    &base,
923                    &[],
924                    Some(&StateUpdateRequest {
925                        state: "closed",
926                        state_reason: Some("completed"),
927                    }),
928                )?;
929            }
930            Some("open") => {
931                self.call(
932                    "PATCH",
933                    &base,
934                    &[],
935                    Some(&StateUpdateRequest {
936                        state: "open",
937                        state_reason: None,
938                    }),
939                )?;
940            }
941            Some(other) => {
942                return Err(bad_value(&format!(
943                    "state {other:?} is not `open` or `closed`"
944                )));
945            }
946        }
947        Ok(())
948    }
949
950    fn create(&self, spec: IssueSpec) -> Result<TrackerIssue, ProviderError> {
951        let capabilities = self.repo_capabilities()?;
952        if !capabilities.create {
953            return Err(Self::unsupported(
954                "create issues here",
955                "read and comment on them",
956            ));
957        }
958        let parent = spec
959            .parent
960            .as_deref()
961            .map(|parent| self.number(parent))
962            .transpose()?;
963        // A label the repository lacks would be created by GitHub: keep the ones it has.
964        let labels: Vec<&str> = spec
965            .labels
966            .iter()
967            .filter(|label| capabilities.labels.contains(label))
968            .map(String::as_str)
969            .collect();
970        let created: IssueDto = read_json(self.call(
971            "POST",
972            &self.issues_url(),
973            &[],
974            Some(&CreateIssueRequest {
975                title: &spec.title,
976                body: &spec.body,
977                labels,
978            }),
979        )?)?;
980        let created_id = created.id;
981        let mut issue = issue_of(&self.settings.repo, created);
982        if let (Some(parent), Some(id)) = (parent, created_id) {
983            let attached = self.call(
984                "POST",
985                &format!("{}/sub_issues", self.issue_url(parent)),
986                &[],
987                Some(&SubIssueRequest { sub_issue_id: id }),
988            );
989            // Sub-issues are not on every plan; the issue exists either way and the caller
990            // links it by reference when it has no parent.
991            if attached.is_ok() {
992                issue.parent = Some(format!("{}#{parent}", self.settings.repo));
993            }
994        }
995        Ok(issue)
996    }
997
998    fn link(&self, link: TrackerLink) -> Result<(), ProviderError> {
999        self.number(&link.from)?;
1000        Err(Self::unsupported(
1001            "link issues",
1002            "name an issue in a comment, which GitHub turns into a link",
1003        ))
1004    }
1005}
1006
1007#[derive(Deserialize)]
1008struct RepoDto {
1009    archived: Option<bool>,
1010    private: Option<bool>,
1011    has_issues: Option<bool>,
1012}
1013
1014#[derive(Deserialize)]
1015struct LabelDto {
1016    name: String,
1017}
1018
1019#[derive(Deserialize)]
1020struct UserDto {
1021    login: String,
1022}
1023
1024#[derive(Deserialize)]
1025struct ContentEntryDto {
1026    path: String,
1027    #[serde(rename = "type")]
1028    kind: String,
1029}
1030
1031#[derive(Deserialize)]
1032struct IssueAuthorDto {
1033    user: Option<UserDto>,
1034}
1035
1036#[derive(Deserialize)]
1037struct IssueDto {
1038    id: Option<u64>,
1039    number: u64,
1040    title: String,
1041    body: Option<String>,
1042    state: Option<String>,
1043    html_url: Option<String>,
1044    user: Option<UserDto>,
1045    labels: Option<Vec<LabelDto>>,
1046    assignees: Option<Vec<UserDto>>,
1047    parent_issue_url: Option<String>,
1048    updated_at: String,
1049}
1050
1051#[derive(Deserialize)]
1052struct CommentDto {
1053    id: u64,
1054    issue_url: Option<String>,
1055    pull_request_url: Option<String>,
1056    user: Option<UserDto>,
1057    author_association: Option<String>,
1058    body: Option<String>,
1059    path: Option<String>,
1060    line: Option<u64>,
1061    original_line: Option<u64>,
1062    created_at: Option<String>,
1063    updated_at: Option<String>,
1064}
1065
1066#[derive(Deserialize)]
1067struct PostedCommentDto {
1068    id: u64,
1069    html_url: Option<String>,
1070}
1071
1072#[derive(Deserialize)]
1073struct PullSummaryDto {
1074    number: u64,
1075}
1076
1077#[derive(Deserialize)]
1078struct ErrorMessageDto {
1079    message: Option<String>,
1080}
1081
1082#[derive(Serialize)]
1083struct CommentBodyRequest {
1084    body: String,
1085}
1086
1087#[derive(Serialize)]
1088struct LabelsRequest<'a> {
1089    labels: &'a [String],
1090}
1091
1092#[derive(Serialize)]
1093struct AssigneesRequest<'a> {
1094    assignees: &'a [String],
1095}
1096
1097#[derive(Serialize)]
1098struct StateUpdateRequest {
1099    state: &'static str,
1100    #[serde(skip_serializing_if = "Option::is_none")]
1101    state_reason: Option<&'static str>,
1102}
1103
1104#[derive(Serialize)]
1105struct CreateIssueRequest<'a> {
1106    title: &'a str,
1107    body: &'a str,
1108    labels: Vec<&'a str>,
1109}
1110
1111#[derive(Serialize)]
1112struct SubIssueRequest {
1113    sub_issue_id: u64,
1114}
1115
1116fn read_json<T: serde::de::DeserializeOwned>(
1117    mut response: ureq::http::Response<ureq::Body>,
1118) -> Result<T, ProviderError> {
1119    response
1120        .body_mut()
1121        .read_json()
1122        .map_err(|e| failure(&format!("unreadable response: {e}")))
1123}
1124
1125/// Whether a classic token's scopes (the `X-OAuth-Scopes` header) let it write to a repository
1126/// of this visibility: `repo`, or `public_repo` for a public one. A response with no such header
1127/// (a fine-grained token or an app) does not say, so it is taken to write.
1128fn token_writes(scopes: Option<&str>, visibility: &str) -> bool {
1129    let Some(scopes) = scopes else {
1130        return true;
1131    };
1132    scopes
1133        .split(',')
1134        .map(str::trim)
1135        .any(|scope| scope == "repo" || (scope == "public_repo" && visibility == "public"))
1136}
1137
1138/// The number at the end of an API URL such as `.../issues/12`.
1139fn trailing_number(url: &str) -> Option<u64> {
1140    url.trim_end_matches('/').rsplit('/').next()?.parse().ok()
1141}
1142
1143/// Percent-encodes one path segment.
1144fn encode_segment(text: &str) -> String {
1145    let mut out = String::new();
1146    for byte in text.bytes() {
1147        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
1148            out.push(byte as char);
1149        } else {
1150            out.push_str(&format!("%{byte:02X}"));
1151        }
1152    }
1153    out
1154}
1155
1156fn issue_of(repo: &str, issue: IssueDto) -> TrackerIssue {
1157    let native_id = issue.id.map(|id| id.to_string()).unwrap_or_default();
1158    let state = issue.state.clone().unwrap_or_else(|| "open".to_owned());
1159    let assignees = issue
1160        .assignees
1161        .as_ref()
1162        .map(|people| people.iter().map(|person| person.login.clone()).collect())
1163        .unwrap_or_default();
1164    let parent = issue
1165        .parent_issue_url
1166        .as_deref()
1167        .and_then(trailing_number)
1168        .map(|number| format!("{repo}#{number}"));
1169    let item = item_of(repo, issue);
1170    TrackerIssue {
1171        id: item.id,
1172        native_id,
1173        title: item.title,
1174        body: item.body,
1175        state,
1176        labels: item.labels,
1177        assignees,
1178        url: item.url,
1179        updated: item.updated,
1180        parent,
1181        author_id: item.author,
1182        priority: None,
1183        code: item.code,
1184        code_tag: item.code_tag,
1185    }
1186}
1187
1188fn bad_value(message: &str) -> ProviderError {
1189    ProviderError::new(Status::GUATIAO_ERR_BAD_VALUE, message)
1190}
1191
1192fn item_of(repo: &str, issue: IssueDto) -> SourceItem {
1193    let number = issue.number;
1194    SourceItem {
1195        id: format!("{repo}#{number}"),
1196        title: issue.title,
1197        body: issue.body.unwrap_or_default(),
1198        url: issue.html_url,
1199        labels: issue
1200            .labels
1201            .map(|labels| labels.into_iter().map(|label| label.name).collect())
1202            .unwrap_or_default(),
1203        author: issue.user.map(|user| user.login),
1204        updated: issue.updated_at,
1205        code: Some(number.to_string()),
1206        code_tag: Some("gh".to_owned()),
1207        event: None,
1208    }
1209}
1210
1211/// The `rel="next"` target of an RFC 8288 `Link` header.
1212fn next_link(header: Option<&str>) -> Option<String> {
1213    header?.split(',').find_map(|part| {
1214        let (target, params) = part.split_once(';')?;
1215        params
1216            .split(';')
1217            .any(|param| param.trim().replace(' ', "") == "rel=\"next\"")
1218            .then(|| {
1219                target
1220                    .trim()
1221                    .trim_start_matches('<')
1222                    .trim_end_matches('>')
1223                    .to_owned()
1224            })
1225    })
1226}
1227
1228/// Pagination links must stay on the API origin, so the token is never sent elsewhere.
1229fn same_origin(candidate: &str, api: &Url) -> bool {
1230    Url::parse(candidate).is_ok_and(|url| url.origin() == api.origin())
1231}
1232
1233/// Checks that a configured page is a plain `https` address with a host and no credentials.
1234fn https_page(text: &str) -> Result<(), String> {
1235    let url = Url::parse(text).map_err(|error| error.to_string())?;
1236    if url.scheme() != "https"
1237        || url.host_str().is_none()
1238        || !url.username().is_empty()
1239        || url.password().is_some()
1240    {
1241        return Err("must be an https address without credentials".to_owned());
1242    }
1243    Ok(())
1244}
1245
1246fn failure(message: &str) -> ProviderError {
1247    ProviderError::new(Status::GUATIAO_ERR_INTERNAL, message)
1248}
1249
1250#[cfg(test)]
1251mod tests {
1252    use super::*;
1253
1254    trait FromText: Sized {
1255        fn from_settings(text: &str) -> Result<Self, String>;
1256    }
1257
1258    impl FromText for Github {
1259        fn from_settings(text: &str) -> Result<Self, String> {
1260            Github::new(ai6::provider_settings::settings_from_text(
1261                ai6::bootstrap::format::Format::Toml,
1262                text,
1263            )?)
1264        }
1265    }
1266
1267    #[test]
1268    fn the_facts_name_the_page_the_labels_the_hosts_and_the_credential_variables() {
1269        let facts = |text: &str| Github::from_settings(text).unwrap().facts().unwrap();
1270        let public = facts("repo = \"o/n\"");
1271        assert_eq!(public.web.as_deref(), Some("https://github.com/o/n"));
1272        assert_eq!(public.intake_labels, ["ai6:ready"]);
1273        assert!(public.hosts.contains(&"api.github.com".to_owned()));
1274        assert!(public.hosts.contains(&"github.com".to_owned()));
1275        for name in ["GITHUB_TOKEN", "GH_TOKEN", "GH_ENTERPRISE_TOKEN"] {
1276            assert!(
1277                public.credential_variables.iter().any(|v| v == name),
1278                "{name}"
1279            );
1280        }
1281        let own = facts(
1282            "repo = \"o/own\"
1283labels = [\"go\"]
1284token_env = \"OWN_TOKEN\"
1285             api_url = \"https://ghe.example/api/v3/\"",
1286        );
1287        assert_eq!(own.web.as_deref(), Some("https://ghe.example/o/own"));
1288        assert_eq!(own.intake_labels, ["go"]);
1289        assert!(own.credential_variables.contains(&"OWN_TOKEN".to_owned()));
1290        assert!(own.hosts.contains(&"ghe.example".to_owned()));
1291        for odd in ["https://proxy.example/github", "http://127.0.0.1:1/api/v3"] {
1292            let odd = facts(&format!(
1293                "repo = \"o/odd\"
1294api_url = \"{odd}\""
1295            ));
1296            assert_eq!(
1297                odd.web, None,
1298                "no page for an unknown root or without https"
1299            );
1300        }
1301    }
1302
1303    #[test]
1304    fn link_headers_yield_the_next_page() {
1305        let header = r#"<https://api.github.com/x?page=2>; rel="next", <https://api.github.com/x?page=9>; rel="last""#;
1306        assert_eq!(
1307            next_link(Some(header)).as_deref(),
1308            Some("https://api.github.com/x?page=2")
1309        );
1310        assert_eq!(next_link(Some(r#"<https://a/x>; rel="last""#)), None);
1311        assert_eq!(next_link(None), None);
1312        assert_eq!(
1313            next_link(Some(
1314                include_str!("../tests/fixtures/issues_page2.link").trim()
1315            ))
1316            .as_deref(),
1317            Some(
1318                "https://api.github.com/repositories/1/issues?state=open&sort=updated&direction=asc&per_page=1&labels=ai6%3Aready&after=Y3Vyc29yOnYyOpLPAAABoZfTLlDPAAAAAW6BOcY%3D&page=3"
1319            ),
1320            "next, not prev, though the host sends both"
1321        );
1322    }
1323
1324    #[test]
1325    fn settings_reject_unknown_keys_bad_repos_and_insecure_apis() {
1326        assert!(Github::from_settings("repo = \"o/r\"").is_ok());
1327        assert!(Github::from_settings("target = \"o/r\"").is_ok());
1328        assert!(Github::from_settings("repo = \"o/r\"\nlabel = \"x\"").is_err());
1329        assert!(Github::from_settings("repo = \"nope\"").is_err());
1330        assert!(Github::from_settings("repo = \"o/../r\"").is_err());
1331        assert!(Github::from_settings("repo = \"o/r\"\napi_url = \"http://example.com\"").is_err());
1332        assert!(Github::from_settings("repo = \"o/r\"\napi_url = \"http://127.0.0.1:9\"").is_ok());
1333    }
1334
1335    #[test]
1336    fn the_board_is_the_issues_page_unless_the_settings_name_another() {
1337        let board = |text: &str| Github::from_settings(text).unwrap().board_url().unwrap();
1338        assert_eq!(
1339            board("repo = \"o/r\"").as_deref(),
1340            Some("https://github.com/o/r/issues")
1341        );
1342        assert_eq!(
1343            board(
1344                "repo = \"o/r\"
1345api_url = \"https://ghe.example:8443/api/v3/\""
1346            )
1347            .as_deref(),
1348            Some("https://ghe.example:8443/o/r/issues")
1349        );
1350        assert_eq!(
1351            board(
1352                "repo = \"o/r\"
1353board_url = \"https://github.com/orgs/o/projects/3\""
1354            )
1355            .as_deref(),
1356            Some("https://github.com/orgs/o/projects/3")
1357        );
1358        assert_eq!(
1359            board(
1360                "repo = \"o/r\"
1361api_url = \"https://proxy.example/github\""
1362            ),
1363            None,
1364            "a root that is not GitHub's names no web page"
1365        );
1366        assert_eq!(
1367            board(
1368                "repo = \"o/r\"
1369api_url = \"http://127.0.0.1:9\""
1370            ),
1371            None
1372        );
1373        for bad in ["http://github.com/o", "nope", "https://u:p@github.com/o"] {
1374            assert!(
1375                Github::from_settings(&format!(
1376                    "repo = \"o/r\"
1377board_url = \"{bad}\""
1378                ))
1379                .is_err(),
1380                "{bad}"
1381            );
1382        }
1383    }
1384
1385    #[test]
1386    fn pagination_never_leaves_the_api_origin() {
1387        let api = Url::parse("https://api.github.com").unwrap();
1388        assert!(same_origin("https://api.github.com/repos?page=2", &api));
1389        assert!(!same_origin("https://evil.example/repos?page=2", &api));
1390    }
1391}