Skip to content

Commit cec71a7

Browse files
unhappychoiceclaude
andcommitted
feat(fetcher): add gitlab_my_mrs
Open merge requests authored by the authenticated GitLab user across every project. Uses `/api/v4/merge_requests?scope=created_by_me&state=opened`. 9 shapes via the shared forge_items dispatcher: LinkedTextBlock (default) / TextBlock / MarkdownTextBlock / ImageLinkedList / Entries / Text / Bars / Badge ("N open MRs") / Timeline. `host` option (default `gitlab.com`) covers self-hosted instances; `limit` clamps 1..=30 (default 10). Mirrors `github_my_prs`; differences are GitLab-specific (`reviewer_username` filter, `references.full` slug, MR `!42` instead of PR `#42`). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
1 parent 174360f commit cec71a7

2 files changed

Lines changed: 224 additions & 1 deletion

File tree

‎src/fetcher/gitlab/mod.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,10 @@ use std::sync::Arc;
1212
pub(crate) mod client;
1313
pub(crate) mod common;
1414
pub(crate) mod items;
15+
mod my_mrs;
1516

1617
use super::Fetcher;
1718

1819
pub fn fetchers() -> Vec<Arc<dyn Fetcher>> {
19-
vec![]
20+
vec![Arc::new(my_mrs::GitlabMyMrs)]
2021
}

‎src/fetcher/gitlab/my_mrs.rs‎

Lines changed: 222 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,222 @@
1+
//! `gitlab_my_mrs` — open merge requests authored by the authenticated GitLab user across
2+
//! every project. Uses `/api/v4/merge_requests?scope=created_by_me&state=opened`.
3+
4+
use async_trait::async_trait;
5+
use serde::Deserialize;
6+
7+
use crate::fetcher::forge_items::{self, LIST_SHAPES};
8+
use crate::options::OptionSchema;
9+
use crate::payload::{Body, Payload};
10+
use crate::render::Shape;
11+
12+
use super::super::{FetchContext, FetchError, Fetcher, Safety};
13+
use super::client::{default_host, rest_get};
14+
use super::common::{cache_key, parse_options, payload, validate_host};
15+
use super::items::{GitlabIssueLike, sample_rows, to_forge_rows};
16+
17+
const DEFAULT_LIMIT: u32 = 10;
18+
19+
const OPTION_SCHEMAS: &[OptionSchema] = &[
20+
OptionSchema {
21+
name: "host",
22+
type_hint: "hostname",
23+
required: false,
24+
default: Some("gitlab.com"),
25+
description: "GitLab instance host. Use this for self-hosted GitLab.",
26+
},
27+
OptionSchema {
28+
name: "limit",
29+
type_hint: "integer (1..=30)",
30+
required: false,
31+
default: Some("10"),
32+
description: "Maximum number of MRs to show.",
33+
},
34+
];
35+
36+
pub struct GitlabMyMrs;
37+
38+
#[derive(Debug, Default, Deserialize)]
39+
#[serde(deny_unknown_fields)]
40+
pub struct Options {
41+
#[serde(default)]
42+
pub host: Option<String>,
43+
#[serde(default)]
44+
pub limit: Option<u32>,
45+
}
46+
47+
#[async_trait]
48+
impl Fetcher for GitlabMyMrs {
49+
fn name(&self) -> &str {
50+
"gitlab_my_mrs"
51+
}
52+
fn safety(&self) -> Safety {
53+
Safety::Safe
54+
}
55+
fn description(&self) -> &'static str {
56+
"Open merge requests authored by the authenticated GitLab user across every project. Use `gitlab_repo_mrs` instead to list MRs against one specific project regardless of who opened them."
57+
}
58+
fn refresh_interval(&self) -> u64 {
59+
60 * 5
60+
}
61+
fn shapes(&self) -> &[Shape] {
62+
LIST_SHAPES
63+
}
64+
fn option_schemas(&self) -> &[OptionSchema] {
65+
OPTION_SCHEMAS
66+
}
67+
fn cache_key(&self, ctx: &FetchContext) -> String {
68+
let host = host_for_key(ctx);
69+
cache_key(self.name(), ctx, &host)
70+
}
71+
fn sample_body(&self, shape: Shape) -> Option<Body> {
72+
let rows = sample_rows(&[
73+
(
74+
"g/splashboard!54",
75+
"feat(docs): generate widget catalogue",
76+
Some("https://gitlab.com/g/splashboard/-/merge_requests/54"),
77+
7,
78+
1_774_000_000,
79+
),
80+
(
81+
"g/splashboard!51",
82+
"feat(fetcher): split clock options",
83+
Some("https://gitlab.com/g/splashboard/-/merge_requests/51"),
84+
2,
85+
1_773_800_000,
86+
),
87+
]);
88+
forge_items::dispatch_sample(&rows, shape, "open MR", "open MRs")
89+
}
90+
async fn fetch(&self, ctx: &FetchContext) -> Result<Payload, FetchError> {
91+
let opts: Options = parse_options(ctx.options.as_ref()).map_err(FetchError::Failed)?;
92+
let host = resolve_host(opts.host.as_deref())?;
93+
let limit = opts.limit.unwrap_or(DEFAULT_LIMIT).clamp(1, 30);
94+
let path = format!(
95+
"/merge_requests?scope=created_by_me&state=opened&per_page={limit}&order_by=updated_at"
96+
);
97+
let items: Vec<GitlabIssueLike> = rest_get(&host, &path).await?;
98+
let rows = to_forge_rows(&items, true);
99+
let shape = ctx.shape.unwrap_or(Shape::LinkedTextBlock);
100+
let body = forge_items::dispatch_rows_async(rows, shape, "open MR", "open MRs").await;
101+
Ok(payload(body))
102+
}
103+
}
104+
105+
pub(super) fn resolve_host(explicit: Option<&str>) -> Result<String, FetchError> {
106+
let host = explicit.unwrap_or(default_host());
107+
validate_host(host)
108+
.map(String::from)
109+
.map_err(FetchError::Failed)
110+
}
111+
112+
fn host_for_key(ctx: &FetchContext) -> String {
113+
ctx.options
114+
.as_ref()
115+
.and_then(|v| v.get("host"))
116+
.and_then(|v| v.as_str())
117+
.unwrap_or(default_host())
118+
.to_string()
119+
}
120+
121+
#[cfg(test)]
122+
mod tests {
123+
use std::time::Duration;
124+
125+
use super::*;
126+
use crate::payload::{BadgeData, Status};
127+
128+
#[test]
129+
fn options_deserialize_both_fields() {
130+
let raw: toml::Value = toml::from_str("host = \"git.example.org\"\nlimit = 5").unwrap();
131+
let opts: Options = raw.try_into().unwrap();
132+
assert_eq!(opts.host.as_deref(), Some("git.example.org"));
133+
assert_eq!(opts.limit, Some(5));
134+
}
135+
136+
#[test]
137+
fn options_reject_unknown_keys() {
138+
let raw: toml::Value = toml::from_str("limit = 5\nbogus = true").unwrap();
139+
assert!(raw.try_into::<Options>().is_err());
140+
}
141+
142+
#[test]
143+
fn shapes_table_matches_shared_list() {
144+
let fetcher = GitlabMyMrs;
145+
assert_eq!(fetcher.shapes(), LIST_SHAPES);
146+
assert_eq!(fetcher.default_shape(), Shape::LinkedTextBlock);
147+
assert_eq!(fetcher.safety(), Safety::Safe);
148+
}
149+
150+
#[test]
151+
fn sample_body_covers_every_list_shape_plus_badge() {
152+
let fetcher = GitlabMyMrs;
153+
for shape in LIST_SHAPES {
154+
assert!(
155+
fetcher.sample_body(*shape).is_some(),
156+
"missing sample for {shape:?}"
157+
);
158+
}
159+
// Shapes outside the catalogued list (e.g. Ratio) return None instead of an empty body
160+
// so docs generation never accidentally promotes them.
161+
assert!(fetcher.sample_body(Shape::Ratio).is_none());
162+
}
163+
164+
#[test]
165+
fn sample_badge_starts_calm_when_count_is_low_but_warm_when_open() {
166+
let fetcher = GitlabMyMrs;
167+
let Some(Body::Badge(BadgeData { status, label })) = fetcher.sample_body(Shape::Badge)
168+
else {
169+
panic!("expected badge");
170+
};
171+
assert_eq!(status, Status::Warn);
172+
assert_eq!(label, "2 open MRs");
173+
}
174+
175+
#[test]
176+
fn host_for_key_falls_back_to_default() {
177+
assert_eq!(host_for_key(&FetchContext::default()), "gitlab.com");
178+
}
179+
180+
#[test]
181+
fn host_for_key_reads_explicit_host_option() {
182+
let ctx = FetchContext {
183+
options: Some(toml::from_str("host = \"git.example.org\"").unwrap()),
184+
..Default::default()
185+
};
186+
assert_eq!(host_for_key(&ctx), "git.example.org");
187+
}
188+
189+
#[test]
190+
fn cache_key_changes_with_host_option() {
191+
let fetcher = GitlabMyMrs;
192+
let a = fetcher.cache_key(&FetchContext::default());
193+
let b = fetcher.cache_key(&FetchContext {
194+
options: Some(toml::from_str("host = \"git.example.org\"").unwrap()),
195+
..Default::default()
196+
});
197+
assert_ne!(a, b);
198+
assert!(a.starts_with("gitlab_my_mrs-"));
199+
}
200+
201+
#[test]
202+
fn resolve_host_validates_input() {
203+
assert_eq!(resolve_host(None).unwrap(), "gitlab.com");
204+
assert!(resolve_host(Some("https://gitlab.com")).is_err());
205+
}
206+
207+
#[tokio::test]
208+
async fn fetch_rejects_invalid_host_before_network_request() {
209+
let err = GitlabMyMrs
210+
.fetch(&FetchContext {
211+
options: Some(toml::from_str("host = \"https://gitlab.com\"").unwrap()),
212+
timeout: Duration::from_secs(1),
213+
..Default::default()
214+
})
215+
.await
216+
.unwrap_err();
217+
assert!(matches!(
218+
err,
219+
FetchError::Failed(m) if m.contains("invalid gitlab host")
220+
));
221+
}
222+
}

0 commit comments

Comments
 (0)