Skip to main content

gitpoulpi_hosting/
model.rs

1//! Host-agnostic shapes for the account, pull/merge request and issue
2//! queries. Normalised here, once, so the TUI/CLI/MCP never see whether a
3//! row came from GitHub or GitLab.
4
5use serde::{Deserialize, Serialize};
6
7/// Who a token belongs to.
8#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
9pub struct HostedUser {
10    /// The handle (`octocat`, GitLab's `username`).
11    pub login: String,
12    /// Display name; empty when the account has none.
13    pub name: String,
14    /// The host's own numeric id, as a string.
15    pub id: String,
16    pub web_url: Option<String>,
17}
18
19/// The outcome of checking a token against its host.
20#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
21pub struct TokenCheck {
22    pub user: HostedUser,
23    /// The scopes the host reports. `None` means *unknown* (a GitHub
24    /// fine-grained token, an old GitLab without
25    /// `/personal_access_tokens/self`), which is deliberately not the same
26    /// as "none": it never produces a missing-scope warning.
27    pub scopes: Option<Vec<String>>,
28    /// Scopes GitPoulpi wants (see `IntegrationKind::token_help`) that the
29    /// host said are absent. Always empty when `scopes` is `None`.
30    pub missing_scopes: Vec<String>,
31    /// When the token expires, as the host spelled it.
32    pub expires_at: Option<String>,
33    /// Granted scopes beyond what GitPoulpi needs, dangerous ones first
34    /// ([`is_dangerous_scope`]). Always empty when `scopes` is `None`: an
35    /// unknown set is never a warning.
36    #[serde(default)]
37    pub excess_scopes: Vec<String>,
38    /// What kind of token it is, when the host or the token's prefix says.
39    #[serde(default)]
40    pub token_flavor: Option<TokenFlavor>,
41    /// A classic token whose host offers fine-grained ones: say so.
42    #[serde(default)]
43    pub recommend_fine_grained: bool,
44}
45
46/// What kind of token a connection uses.
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
48#[serde(rename_all = "snake_case")]
49pub enum TokenFlavor {
50    /// A personal token whose scopes are a flat list.
51    Classic,
52    /// A token limited to chosen repositories and permissions.
53    FineGrained,
54    /// A token of a project or a group, not of a person.
55    ProjectOrGroup,
56    Unknown,
57}
58
59/// Scopes that can destroy data or reach beyond the repositories: shown
60/// first, and in the warning colour, when a token holds them without need.
61const DANGEROUS_SCOPES: &[&str] = &[
62    "delete_repo",
63    "admin:org",
64    "admin:repo_hook",
65    "admin:enterprise",
66    "admin:gpg_key",
67    "delete:packages",
68    "write:packages",
69    "site_admin",
70    "sudo",
71    "admin_mode",
72    "create_runner",
73    "manage_runner",
74    "k8s_proxy",
75];
76
77/// Whether `scope` is one of the sensitive ones above.
78pub fn is_dangerous_scope(scope: &str) -> bool {
79    DANGEROUS_SCOPES.contains(&scope)
80}
81
82/// The scopes in `granted` that neither `needed` nor `tolerated` (optional
83/// scopes GitPoulpi can use) names, directly or through an umbrella scope,
84/// dangerous ones first. Order inside each group is the host's.
85pub fn excess_scopes(needed: &[&str], tolerated: &[&str], granted: &[String]) -> Vec<String> {
86    let wanted = |g: &str| {
87        needed
88            .iter()
89            .chain(tolerated)
90            .any(|n| *n == g || scope_satisfies(n, g))
91    };
92    let (mut dangerous, other): (Vec<String>, Vec<String>) = granted
93        .iter()
94        .filter(|g| !wanted(g))
95        .cloned()
96        .partition(|g| is_dangerous_scope(g));
97    dangerous.extend(other);
98    dangerous
99}
100
101#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
102#[serde(rename_all = "snake_case")]
103pub enum PullRequestState {
104    #[default]
105    Open,
106    Draft,
107    Merged,
108    Closed,
109}
110
111impl PullRequestState {
112    /// Lower is better when several requests exist for one branch: a live
113    /// non-draft request beats a draft, which beats a merged one, which
114    /// beats one closed unmerged.
115    fn rank(self) -> u8 {
116        match self {
117            PullRequestState::Open => 0,
118            PullRequestState::Draft => 1,
119            PullRequestState::Merged => 2,
120            PullRequestState::Closed => 3,
121        }
122    }
123}
124
125#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
126pub struct PullRequestSummary {
127    /// GitHub number / GitLab `iid`.
128    pub number: u64,
129    /// What the host's own UI shows: `#12` (GitHub) or `!53` (GitLab).
130    pub iid_label: String,
131    pub title: String,
132    pub state: PullRequestState,
133    pub source_branch: String,
134    pub target_branch: String,
135    /// The fork the source branch lives in, when it is not the target
136    /// project itself.
137    pub source_project: Option<String>,
138    pub author: String,
139    pub web_url: String,
140    /// ISO-8601 as the host sent it.
141    pub updated_at: String,
142    /// The current user is asked to review it.
143    pub review_requested: bool,
144    /// Logins of the people it is assigned to.
145    #[serde(default)]
146    pub assignees: Vec<String>,
147    /// Logins of the people asked to review it.
148    #[serde(default)]
149    pub reviewers: Vec<String>,
150    /// The state of the head commit's checks (CI); `None` = unknown or not
151    /// asked (GitHub only answers it on request, see [`PrFilter::checks`]).
152    #[serde(default, skip_serializing_if = "Option::is_none")]
153    pub checks: Option<ChecksState>,
154    /// Whether the request conflicts with its target; `None` = unknown.
155    #[serde(default, skip_serializing_if = "Option::is_none")]
156    pub has_conflicts: Option<bool>,
157}
158
159/// The rolled-up state of a request's checks.
160#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
161#[serde(rename_all = "snake_case")]
162pub enum ChecksState {
163    /// Queued or running.
164    Pending,
165    Passing,
166    Failing,
167}
168
169/// Picks the request that best answers "which PR is this branch's?":
170/// open, then draft, then merged, then closed; newest `updated_at` breaks
171/// a tie (ISO-8601 strings sort chronologically).
172pub fn best_pull_request(mut all: Vec<PullRequestSummary>) -> Option<PullRequestSummary> {
173    all.sort_by(|a, b| {
174        a.state
175            .rank()
176            .cmp(&b.state.rank())
177            .then_with(|| b.updated_at.cmp(&a.updated_at))
178    });
179    all.into_iter().next()
180}
181
182#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
183#[serde(rename_all = "snake_case")]
184pub enum IssueState {
185    #[default]
186    Open,
187    Closed,
188}
189
190/// A milestone as an issue row carries it (`"milestone": {"title": ..}`).
191#[derive(Debug, Clone, Default, serde::Deserialize)]
192#[allow(dead_code)] // only the hosts compiled in read it
193pub(crate) struct MilestoneTitle {
194    #[serde(default)]
195    pub title: String,
196}
197
198#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
199pub struct IssueSummary {
200    /// GitHub number / GitLab `iid`; Jira's numeric key suffix; Trello's
201    /// `idShort`. For sorting and old paths: humans use `reference`.
202    pub number: u64,
203    /// The provider's own id (Trello card id, Jira id); the number as a
204    /// string on GitHub and GitLab.
205    #[serde(default)]
206    pub id: String,
207    /// What a human types to reference it: `#12` (GitHub / GitLab),
208    /// `ABC-123` (Jira), `AB#123` (Azure), a Trello `shortUrl`.
209    #[serde(default)]
210    pub reference: String,
211    /// Work item type, Jira issue type, Trello list name.
212    #[serde(default, skip_serializing_if = "Option::is_none")]
213    pub kind_label: Option<String>,
214    /// The workflow state as the provider spells it (Jira, Azure).
215    #[serde(default, skip_serializing_if = "Option::is_none")]
216    pub status_label: Option<String>,
217    /// `#12` on both hosts.
218    pub iid_label: String,
219    pub title: String,
220    pub state: IssueState,
221    pub author: String,
222    pub assignees: Vec<String>,
223    pub labels: Vec<String>,
224    pub web_url: String,
225    pub updated_at: String,
226    /// The branch name the tracker proposes for the issue (Linear's
227    /// `branchName`); `None`: the app derives one from the reference.
228    #[serde(default, skip_serializing_if = "Option::is_none")]
229    pub branch_name: Option<String>,
230    /// The milestone's title (GitHub, GitLab, Gitea, local notes); the
231    /// Kanban board filters on it.
232    #[serde(default, skip_serializing_if = "Option::is_none")]
233    pub milestone: Option<String>,
234}
235
236/// Which states a list query asks for.
237#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
238#[serde(rename_all = "snake_case")]
239pub enum StateFilter {
240    #[default]
241    Open,
242    /// For pull requests this includes merged ones.
243    Closed,
244    All,
245}
246
247#[derive(Debug, Clone, Default, PartialEq, Eq)]
248pub struct PrFilter {
249    pub state: StateFilter,
250    /// Only those the current user opened.
251    pub mine: bool,
252    /// Only those awaiting the current user's review.
253    pub review_requested: bool,
254    /// Only those that mention the current user (GitHub: the search API's
255    /// `mentions:`; GitLab: the to-do list's `mentioned` items). Providers
256    /// without the notion return nothing.
257    pub mentioned: bool,
258    /// Also fill `checks` and `has_conflicts` where the list endpoint does
259    /// not carry them (GitHub: a bounded number of extra requests per
260    /// request shown). GitLab always carries them.
261    pub checks: bool,
262}
263
264#[derive(Debug, Clone, Default, PartialEq, Eq)]
265pub struct IssueFilter {
266    pub state: StateFilter,
267    /// Only those assigned to the current user.
268    pub assigned_to_me: bool,
269    /// Only those that mention the current user (see [`PrFilter::mentioned`]).
270    pub mentioned: bool,
271    /// The provider-native extra clause (`IssuesSource::filter`): a Jira
272    /// JQL fragment ANDed with `project = KEY`, an Azure WIQL condition,
273    /// Trello list names (comma-separated). Other providers ignore it.
274    pub query: Option<String>,
275}
276
277/// One entry of a create-form choice list.
278#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
279pub struct Choice {
280    pub id: String,
281    pub label: String,
282}
283
284/// What the New-issue form can offer for a project: issue types (Jira,
285/// Azure) and lists (Trello). Empty for GitHub and GitLab.
286#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
287pub struct IssueCreateOptions {
288    pub types: Vec<Choice>,
289    pub lists: Vec<Choice>,
290    pub default_type: Option<String>,
291    pub default_list: Option<String>,
292}
293
294/// Whether a granted scope satisfies a required one, including the
295/// umbrella scopes (`api` covers everything GitLab-side, `user` covers
296/// `read:user`, ...).
297fn scope_satisfies(granted: &str, required: &str) -> bool {
298    granted == required
299        || matches!(
300            (granted, required),
301            (
302                "api",
303                "read_user" | "read_api" | "read_repository" | "write_repository"
304            ) | ("user", "read:user" | "user:email")
305                | ("admin:public_key", "write:public_key" | "read:public_key")
306                | ("write:public_key", "read:public_key")
307                | (
308                    "repo",
309                    "repo:status"
310                        | "repo_deployment"
311                        | "public_repo"
312                        | "repo:invite"
313                        | "security_events"
314                )
315        )
316}
317
318/// The required scopes nothing in `granted` satisfies.
319pub fn missing_scopes(required: &[&str], granted: &[String]) -> Vec<String> {
320    required
321        .iter()
322        .filter(|r| !granted.iter().any(|g| scope_satisfies(g, r)))
323        .map(|r| r.to_string())
324        .collect()
325}
326
327#[cfg(test)]
328mod tests {
329    use super::*;
330
331    fn pr(n: u64, state: PullRequestState, updated: &str) -> PullRequestSummary {
332        PullRequestSummary {
333            number: n,
334            iid_label: format!("#{n}"),
335            title: String::new(),
336            state,
337            source_branch: "b".into(),
338            target_branch: "main".into(),
339            source_project: None,
340            author: String::new(),
341            web_url: String::new(),
342            updated_at: updated.into(),
343            review_requested: false,
344            assignees: Vec::new(),
345            reviewers: Vec::new(),
346            checks: None,
347            has_conflicts: None,
348        }
349    }
350
351    #[test]
352    fn best_pull_request_prefers_open_then_draft_then_merged_then_newest() {
353        use PullRequestState::*;
354        let best = best_pull_request(vec![
355            pr(1, Merged, "2026-01-05"),
356            pr(2, Draft, "2026-01-04"),
357            pr(3, Open, "2026-01-01"),
358            pr(4, Open, "2026-01-02"),
359            pr(5, Closed, "2026-01-09"),
360        ])
361        .unwrap();
362        assert_eq!(best.number, 4, "newest of the open ones");
363        let best = best_pull_request(vec![pr(1, Closed, "x"), pr(2, Merged, "a")]).unwrap();
364        assert_eq!(best.number, 2);
365        assert!(best_pull_request(vec![]).is_none());
366    }
367
368    #[test]
369    fn the_issue_model_has_defaults_and_additive_fields() {
370        let issue = IssueSummary::default();
371        assert_eq!(issue.state, IssueState::Open);
372        assert_eq!(issue.reference, "");
373        assert_eq!(issue.kind_label, None);
374        // Optional labels stay out of the JSON when absent.
375        let json = serde_json::to_value(&issue).unwrap();
376        assert!(json.get("kind_label").is_none() && json.get("status_label").is_none());
377        // An older payload without the new fields still deserializes.
378        let old = r##"{"number":1,"iid_label":"#1","title":"t","state":"open","author":"a",
379            "assignees":[],"labels":[],"web_url":"u","updated_at":"x"}"##;
380        let parsed: IssueSummary = serde_json::from_str(old).unwrap();
381        assert_eq!(parsed.number, 1);
382        assert_eq!(parsed.id, "");
383        assert_eq!(IssueFilter::default().query, None);
384        let options = IssueCreateOptions::default();
385        assert!(options.types.is_empty() && options.lists.is_empty());
386    }
387
388    #[test]
389    fn umbrella_scopes_satisfy_narrower_ones() {
390        let granted = vec!["api".to_string()];
391        assert!(missing_scopes(&["api", "read_user"], &granted).is_empty());
392        let granted = vec!["repo".to_string()];
393        assert_eq!(
394            missing_scopes(&["repo", "read:user", "admin:public_key"], &granted),
395            vec!["read:user", "admin:public_key"]
396        );
397        let granted = vec!["user".to_string()];
398        assert!(missing_scopes(&["read:user"], &granted).is_empty());
399    }
400}