acorn-lib 0.1.69

ACORN library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
//! GitLab API service operations.

use super::{
    eyre, first_env_var, require_non_empty_secret, ApiResult, BoxFuture, CommitStatus, CommitStatusState, Configuration, EmptyField, Endpoint,
    ErrorResponse, EventFilterKey, EventsResponse, Fallback, FutureExt, GitLabIdentity, GroupsResponse, InstanceVersion, MergeRequestDetails,
    MergeRequestDiffsResponse, Note, NoteMetadata, NotesResponse, Options, PaginationKey, Params, ProgrammingLanguageUseResponse,
    ProgrammingLanguagesResponse, ProjectMember, ProjectWebhook, ProjectWebhookRequest, ProjectWebhooksResponse, RemoteResource, RepositoryFile,
    ResponseContent, RunnerCreationResponse, RunnerMetadata, RunnersResponse, Searchable, TreeResponse, Validate, WebhookOptions,
    WebhookRegistration, WorkItem, GITLAB_TOKEN_VARIABLE_NAMES, INCLUDED_ENDPOINTS,
};
use serde::Deserialize;

pub(crate) fn handle_tree_paths_response(response: ApiResult<TreeResponse>, page: u32) -> ApiResult<TreeResponse> {
    match response {
        | Ok(value) => match value.error {
            | Some(why) if page > 1 && why.is_terminal_pagination_error() => Ok(TreeResponse::default()),
            | Some(why) => Err(eyre!(why.message())),
            | None => Ok(value),
        },
        | Err(why) => Err(why),
    }
}
/// Create a new runner using project or group identifier
///
/// See <https://docs.gitlab.com/api/users/#create-a-runner-linked-to-a-user> for more information on the GitLab API
pub async fn create_runner(options: &Options) -> ApiResult<RunnerCreationResponse> {
    #[derive(Deserialize)]
    struct StrictRunnerCreationResponse {
        #[serde(rename = "id")]
        identifier: u64,
        token: Option<String>,
        token_expires_at: Option<String>,
    }
    let template = "gitlab::api";
    let action = "runner::create";
    let path = format!("{template}::{action}");
    let runner_metadata = &options.runner_metadata;
    let runner_type = &runner_metadata.runner_type;
    let description = runner_metadata.description.as_deref().unwrap_or_default();
    let tags = runner_metadata.tags.as_deref().unwrap_or_default();
    let run_untagged = runner_metadata.run_untagged;
    let tag_list = if tags.is_empty() { None } else { Some(tags.join(",")) };
    match require_non_empty_secret(&options.token, &path, &GITLAB_TOKEN_VARIABLE_NAMES) {
        | Ok(token) => match Endpoint::from_template(template).map(|e| e.with_domain(options.domain())) {
            | Ok(endpoint) => {
                let params = Params::new()
                    .with_auth(&token, Some("PRIVATE-TOKEN"))
                    .with_body("description", description)
                    .with_body(&format!("{runner_type}_id"), options.identifier.as_deref().unwrap_or_default())
                    .with_body("runner_type", &format!("{runner_type}_type"))
                    .with_body("run_untagged", &run_untagged.to_string())
                    .with_body_maybe("tag_list", tag_list.as_deref())
                    .with_custom(options.params())
                    .build();
                let response = endpoint.invoke(action, Some(params)).await;
                match response {
                    | Ok(ResponseContent::Json(content)) => match serde_json::from_str::<StrictRunnerCreationResponse>(&content) {
                        | Ok(parsed) => Ok(RunnerCreationResponse {
                            identifier: parsed.identifier,
                            token: parsed.token,
                            token_expires_at: parsed.token_expires_at,
                        }),
                        | Err(_) => {
                            let rendered = serde_json::from_str::<serde_json::Value>(&content)
                                .ok()
                                .and_then(|value| serde_json::to_string_pretty(&value).ok())
                                .unwrap_or(content);
                            Err(eyre!("{rendered}"))
                        }
                    },
                    | Ok(other) => endpoint.handle::<RunnerCreationResponse>(Ok(other)),
                    | Err(why) => Err(why),
                }
            }
            | Err(why) => Err(why),
        },
        | Err(why) => Err(why),
    }
}
/// Get events for a project
/// ### Example
///
/// ```ignore
/// use acorn::io::api::{gitlab, Configuration};
/// use acorn::param;
///
/// let project_id = "16689";
/// let options = gitlab::Options::from_env()
///     .with_identifier(project_id)
///     .with_params(vec![
///         param!(KeyValuePair, "target_type", "note"),
///         param!(KeyValuePair, "after", "2026-06-27"),
///         // 'before' value is invalid and will not be including in final URL
///         param!(KeyValuePair, "before", "2026-##-04"),
///     ]);
/// let events = gitlab::events(&options).await;
/// ```
///
/// See <https://docs.gitlab.com/api/events/#list-all-visible-events-for-a-project> for more information
pub async fn events(options: &Options) -> ApiResult<EventsResponse> {
    let template = "gitlab::api";
    let action = "events";
    let path = format!("{template}::{action}");
    match require_non_empty_secret(&options.token, &path, &GITLAB_TOKEN_VARIABLE_NAMES) {
        | Ok(token) => match Endpoint::from_template(template).map(|e| e.with_domain(options.domain())) {
            | Ok(endpoint) => {
                let params = Params::new()
                    .with_auth(&token, Some("PRIVATE-TOKEN"))
                    .with_template("identifier", options.identifier())
                    .with_custom(options.params())
                    .build();
                let response = endpoint.invoke_with::<EventFilterKey, EmptyField>(action, Some(params)).await;
                endpoint.handle::<EventsResponse>(response)
            }
            | Err(why) => Err(why),
        },
        | Err(why) => Err(why),
    }
}
/// Get the GitLab instance version
pub async fn version(options: &Options) -> ApiResult<InstanceVersion> {
    let template = "gitlab::api";
    let action = "version";
    let path = format!("{template}::{action}");
    match require_non_empty_secret(&options.token, &path, &GITLAB_TOKEN_VARIABLE_NAMES) {
        | Ok(token) => match Endpoint::from_template(template).map(|endpoint| endpoint.with_domain(options.domain())) {
            | Ok(endpoint) => {
                let params = Params::new().with_auth(&token, Some("PRIVATE-TOKEN")).build();
                let response = endpoint.invoke(action, Some(params)).await;
                endpoint.handle::<InstanceVersion>(response)
            }
            | Err(why) => Err(why),
        },
        | Err(why) => Err(why),
    }
}
/// List all project webhooks for the configured project
pub async fn project_webhooks(options: &Options) -> ApiResult<ProjectWebhooksResponse> {
    project_webhooks_page(options).await
}
fn project_webhooks_page(options: &Options) -> BoxFuture<'_, ApiResult<ProjectWebhooksResponse>> {
    async move {
        let template = "gitlab::api";
        let action = "hooks";
        let path = format!("{template}::{action}");
        let page = options.page;
        match require_non_empty_secret(&options.token, &path, &GITLAB_TOKEN_VARIABLE_NAMES) {
            | Ok(token) => match Endpoint::from_template(template).map(|endpoint| endpoint.with_domain(options.domain())) {
                | Ok(endpoint) => {
                    let params = Params::new()
                        .with_auth(&token, Some("PRIVATE-TOKEN"))
                        .with_template("identifier", options.identifier())
                        .with_keyvalue("page", Some(&page.to_string()))
                        .with_keyvalue("per_page", Some("100"))
                        .build();
                    let response = endpoint.invoke_with::<PaginationKey, EmptyField>(action, Some(params)).await;
                    match endpoint.handle::<ProjectWebhooksResponse>(response) {
                        | Ok(hooks) if hooks.len() == 100 => match project_webhooks_page(&options.clone().with_page(page.saturating_add(1))).await {
                            | Ok(remaining) => Ok(hooks.into_iter().chain(remaining).collect()),
                            | Err(why) => Err(why),
                        },
                        | result => result,
                    }
                }
                | Err(why) => Err(why),
            },
            | Err(why) => Err(why),
        }
    }
    .boxed()
}
/// Create or refresh the ACORN merge request and note webhook
pub async fn upsert_project_webhook(options: &Options, webhook: &WebhookOptions) -> ApiResult<WebhookRegistration> {
    match webhook.validate() {
        | Ok(()) => match version(options).await {
            | Ok(version) => {
                let registration = webhook.for_registration(version.supports_signing_tokens());
                match registration.public_url.as_deref() {
                    | Some(endpoint_url) => match project_webhooks(options).await {
                        | Ok(hooks) => match hooks.into_iter().find(|hook| hook.url.trim_end_matches('/') == endpoint_url) {
                            | Some(hook) => write_project_webhook(options, "hook::update", Some(hook.id), &registration)
                                .await
                                .map(|hook| WebhookRegistration { hook, created: false }),
                            | None => write_project_webhook(options, "hook::create", None, &registration)
                                .await
                                .map(|hook| WebhookRegistration { hook, created: true }),
                        },
                        | Err(why) => Err(why),
                    },
                    | None => Err(eyre!("Webhook mode requires --public-url")),
                }
            }
            | Err(why) => Err(why),
        },
        | Err(why) => Err(eyre!(why)),
    }
}
async fn write_project_webhook(options: &Options, action: &str, hook_id: Option<u64>, webhook: &WebhookOptions) -> ApiResult<ProjectWebhook> {
    let template = "gitlab::api";
    let path = format!("{template}::{action}");
    match require_non_empty_secret(&options.token, &path, &GITLAB_TOKEN_VARIABLE_NAMES) {
        | Ok(token) => match Endpoint::from_template(template).map(|endpoint| endpoint.with_domain(options.domain())) {
            | Ok(endpoint) => {
                let request = ProjectWebhookRequest {
                    url: webhook.public_url.as_deref().unwrap_or_default(),
                    name: "ACORN bot",
                    description: "ACORN merge request analysis and citation intake",
                    merge_requests_events: true,
                    note_events: true,
                    enable_ssl_verification: true,
                    token: webhook.webhook_token.as_deref(),
                    signing_token: webhook.signing_token.as_deref(),
                };
                match serde_json::to_string(&request) {
                    | Ok(body) => {
                        let hook_id = hook_id.map(|value| value.to_string());
                        let params = Params::new()
                            .with_auth(&token, Some("PRIVATE-TOKEN"))
                            .with_template("identifier", options.identifier())
                            .with_template("hook_id", hook_id.as_deref())
                            .with(crate::param!(Body, &body))
                            .build();
                        let response = endpoint.invoke(action, Some(params)).await;
                        endpoint.handle::<ProjectWebhook>(response)
                    }
                    | Err(why) => Err(eyre!("Failed to encode GitLab webhook registration — {why}")),
                }
            }
            | Err(why) => Err(why),
        },
        | Err(why) => Err(why),
    }
}
/// Get descendant groups of a group by identifier
///
/// See <https://docs.gitlab.com/api/groups/#list-descendant-groups> for more information
pub async fn groups(options: &Options) -> ApiResult<GroupsResponse> {
    let template = "gitlab::api";
    let action = "groups";
    let path = format!("{template}::{action}");
    match require_non_empty_secret(&options.token, &path, &GITLAB_TOKEN_VARIABLE_NAMES) {
        | Ok(token) => match Endpoint::from_template(template).map(|e| e.with_domain(options.domain())) {
            | Ok(endpoint) => {
                let params = Params::new()
                    .with_auth(&token, Some("PRIVATE-TOKEN"))
                    .with_template("identifier", options.identifier())
                    .with_keyvalue("page", Some("1"))
                    .with_keyvalue("per_page", Some("100"))
                    .with_custom(options.params())
                    .build();
                let response = endpoint.invoke_with::<PaginationKey, EmptyField>(action, Some(params)).await;
                endpoint.handle_or::<GroupsResponse, Fallback<ErrorResponse>>(response)
            }
            | Err(why) => Err(why),
        },
        | Err(why) => Err(why),
    }
}
/// Get programming languages used by a GitLab project
///
/// See <https://docs.gitlab.com/api/projects/?utm_source=perplexity#retrieve-programming-language-usage-information> for more information on GitLab API.
pub async fn language_use(options: &Options) -> ApiResult<ProgrammingLanguageUseResponse> {
    let template = "gitlab::api";
    let action = "languages";
    let path = format!("{template}::{action}");
    match require_non_empty_secret(&options.token, &path, &GITLAB_TOKEN_VARIABLE_NAMES) {
        | Ok(token) => match Endpoint::from_template(template).map(|e| e.with_domain(options.domain())) {
            | Ok(endpoint) => {
                let params = Params::new()
                    .with_auth(&token, Some("PRIVATE-TOKEN"))
                    .with_template("identifier", options.identifier())
                    .with_custom(options.params())
                    .build();
                let response = endpoint.invoke_with::<PaginationKey, EmptyField>(action, Some(params)).await;
                endpoint.handle::<ProgrammingLanguageUseResponse>(response)
            }
            | Err(why) => Err(why),
        },
        | Err(why) => Err(why),
    }
}
/// Download programming language metadata from GitLab linguist source file
pub async fn languages() -> ApiResult<ProgrammingLanguagesResponse> {
    let names = ["gitlab::org", "github::org"];
    let action = "languages";
    async fn fetch(name: &str, action: &str) -> ApiResult<ProgrammingLanguagesResponse> {
        match INCLUDED_ENDPOINTS.find_by_name(name) {
            | Some(endpoint) => {
                let response = endpoint.invoke(action, None).await.map(|content| match content {
                    | ResponseContent::Raw(content) => ResponseContent::Yaml(content),
                    | other => other,
                });
                endpoint.handle::<ProgrammingLanguagesResponse>(response)
            }
            | None => Err(eyre!("{name} API endpoint not found")),
        }
    }
    let mut response: Option<ProgrammingLanguagesResponse> = None;
    let mut errors = Vec::new();
    for name in names {
        let path = format!("{name}::{action}");
        match fetch(name, action).await {
            | Ok(value) => {
                response = Some(value);
                break;
            }
            | Err(why) => errors.push(format!("{path}={why}")),
        }
    }
    match response {
        | Some(value) => Ok(value),
        | None => Err(eyre!("Failed to download and parse language metadata — {}", errors.join("; "))),
    }
}
fn authenticated_endpoint(action: &str, options: &Options) -> ApiResult<(Endpoint, String)> {
    let path = format!("gitlab::api::{action}");
    match require_non_empty_secret(&options.token, &path, &GITLAB_TOKEN_VARIABLE_NAMES) {
        | Ok(token) => Endpoint::from_template("gitlab::api").map(|endpoint| (endpoint.with_domain(options.domain()), token)),
        | Err(why) => Err(why),
    }
}
/// Get merge request metadata by IID
pub async fn merge_request(options: &Options) -> ApiResult<MergeRequestDetails> {
    let action = "merge-requests";
    match authenticated_endpoint(action, options) {
        | Ok((endpoint, token)) => {
            let params = Params::new()
                .with_auth(&token, Some("PRIVATE-TOKEN"))
                .with_template("identifier", options.identifier())
                .with_template("internal_identifier", options.internal_identifier.as_deref())
                .build();
            let response = endpoint.invoke(action, Some(params)).await;
            endpoint.handle_or::<MergeRequestDetails, Fallback<ErrorResponse>>(response)
        }
        | Err(why) => Err(why),
    }
}
/// List every changed file in a merge request
pub fn merge_request_diffs(options: &Options) -> BoxFuture<'_, ApiResult<MergeRequestDiffsResponse>> {
    async move {
        let action = "merge-request-diffs";
        match authenticated_endpoint(action, options) {
            | Ok((endpoint, token)) => {
                let page_value = options.page.to_string();
                let params = Params::new()
                    .with_auth(&token, Some("PRIVATE-TOKEN"))
                    .with_template("identifier", options.identifier())
                    .with_template("internal_identifier", options.internal_identifier.as_deref())
                    .with_keyvalue("page", Some(&page_value))
                    .with_keyvalue("per_page", Some("100"))
                    .build();
                let response = endpoint.invoke_with::<PaginationKey, EmptyField>(action, Some(params)).await;
                match endpoint.handle_or::<MergeRequestDiffsResponse, Fallback<ErrorResponse>>(response) {
                    | Ok(diffs) if diffs.len() == 100 => {
                        match merge_request_diffs(&options.clone().with_page(options.page.saturating_add(1))).await {
                            | Ok(remaining) => Ok(diffs.into_iter().chain(remaining).collect()),
                            | Err(why) => Err(why),
                        }
                    }
                    | result => result,
                }
            }
            | Err(why) => Err(why),
        }
    }
    .boxed()
}
/// Fetch the configured repository file at an exact commit SHA
pub async fn repository_file(options: &Options) -> ApiResult<RepositoryFile> {
    let action = "repository-file";
    match (
        authenticated_endpoint(action, options),
        options.identifier(),
        options.path(),
        options.sha(),
    ) {
        | (Ok((endpoint, token)), Some(project_identifier), Ok(file_path), Ok(sha)) => {
            let encoded_identifier = urlencoding::encode(project_identifier);
            let encoded_path = urlencoding::encode(file_path);
            let params = Params::new()
                .with_auth(&token, Some("PRIVATE-TOKEN"))
                .with_template("identifier", Some(encoded_identifier.as_ref()))
                .with_template("file_path", Some(encoded_path.as_ref()))
                .with_keyvalue("ref", Some(sha))
                .build();
            let response = endpoint.invoke(action, Some(params)).await;
            endpoint.handle_or::<RepositoryFile, Fallback<ErrorResponse>>(response)
        }
        | (Err(why), _, _, _) | (_, _, Err(why), _) | (_, _, _, Err(why)) => Err(why),
        | (_, None, _, _) => Err(eyre!("GitLab project identifier is required")),
    }
}
/// Publish the `acorn/check` external commit status
pub async fn publish_commit_status(
    options: &Options,
    project_id: Option<u64>,
    sha: &str,
    state: CommitStatusState,
    description: &str,
    target_url: Option<&str>,
) -> ApiResult<CommitStatus> {
    let action = "commit-status";
    match authenticated_endpoint(action, options) {
        | Ok((endpoint, token)) => {
            let state = state.to_string();
            let project_id = project_id.map(|value| value.to_string());
            let params = Params::new()
                .with_auth(&token, Some("PRIVATE-TOKEN"))
                .with_template("identifier", project_id.as_deref().or(options.identifier()))
                .with_template("sha", Some(sha))
                .with_body("state", &state)
                .with_body("name", "acorn/check")
                .with_body("description", description)
                .with_body_maybe("target_url", target_url)
                .build();
            let response = endpoint.invoke(action, Some(params)).await;
            endpoint.handle_or::<CommitStatus, Fallback<ErrorResponse>>(response)
        }
        | Err(why) => Err(why),
    }
}
/// List every note on a merge request
pub async fn merge_request_notes(options: &Options) -> ApiResult<NotesResponse> {
    merge_request_notes_page(options).await
}
fn merge_request_notes_page(options: &Options) -> BoxFuture<'_, ApiResult<NotesResponse>> {
    async move {
        let action = "merge-request-notes";
        match authenticated_endpoint(action, options) {
            | Ok((endpoint, token)) => {
                let page_value = options.page.to_string();
                let params = Params::new()
                    .with_auth(&token, Some("PRIVATE-TOKEN"))
                    .with_template("identifier", options.identifier())
                    .with_template("internal_identifier", options.internal_identifier.as_deref())
                    .with_keyvalue("page", Some(&page_value))
                    .with_keyvalue("per_page", Some("100"))
                    .build();
                let response = endpoint.invoke_with::<PaginationKey, EmptyField>(action, Some(params)).await;
                match endpoint.handle_or::<NotesResponse, Fallback<ErrorResponse>>(response) {
                    | Ok(notes) if notes.len() == 100 => {
                        match merge_request_notes_page(&options.clone().with_page(options.page.saturating_add(1))).await {
                            | Ok(remaining) => Ok(notes.into_iter().chain(remaining).collect()),
                            | Err(why) => Err(why),
                        }
                    }
                    | result => result,
                }
            }
            | Err(why) => Err(why),
        }
    }
    .boxed()
}
/// Get the GitLab user authenticated by the outbound API token
pub async fn current_user(options: &Options) -> ApiResult<GitLabIdentity> {
    let action = "current-user";
    match authenticated_endpoint(action, options) {
        | Ok((endpoint, token)) => {
            let params = Params::new().with_auth(&token, Some("PRIVATE-TOKEN")).build();
            let response = endpoint.invoke(action, Some(params)).await;
            endpoint.handle_or::<GitLabIdentity, Fallback<ErrorResponse>>(response)
        }
        | Err(why) => Err(why),
    }
}
/// Get one GitLab Issue or Task by IID
pub async fn work_item(options: &Options) -> ApiResult<WorkItem> {
    let action = "issue";
    match authenticated_endpoint(action, options) {
        | Ok((endpoint, token)) => {
            let params = Params::new()
                .with_auth(&token, Some("PRIVATE-TOKEN"))
                .with_template("identifier", options.identifier())
                .with_template("internal_identifier", options.internal_identifier.as_deref())
                .build();
            let response = endpoint.invoke(action, Some(params)).await;
            endpoint.handle_or::<WorkItem, Fallback<ErrorResponse>>(response)
        }
        | Err(why) => Err(why),
    }
}
/// Get a user's effective project membership, including inherited membership
pub async fn project_member(options: &Options, user_id: u64) -> ApiResult<ProjectMember> {
    let action = "member";
    match authenticated_endpoint(action, options) {
        | Ok((endpoint, token)) => {
            let user_id = user_id.to_string();
            let params = Params::new()
                .with_auth(&token, Some("PRIVATE-TOKEN"))
                .with_template("identifier", options.identifier())
                .with_template("user_id", Some(&user_id))
                .build();
            let response = endpoint.invoke(action, Some(params)).await;
            endpoint.handle_or::<ProjectMember, Fallback<ErrorResponse>>(response)
        }
        | Err(why) => Err(why),
    }
}
/// List every note on one GitLab Issue or Task
pub fn work_item_notes(options: &Options) -> BoxFuture<'_, ApiResult<NotesResponse>> {
    async move {
        let action = "issue-notes";
        match authenticated_endpoint(action, options) {
            | Ok((endpoint, token)) => {
                let page = options.page.to_string();
                let params = Params::new()
                    .with_auth(&token, Some("PRIVATE-TOKEN"))
                    .with_template("identifier", options.identifier())
                    .with_template("internal_identifier", options.internal_identifier.as_deref())
                    .with_keyvalue("page", Some(&page))
                    .with_keyvalue("per_page", Some("100"))
                    .with_keyvalue("sort", Some("asc"))
                    .build();
                let response = endpoint.invoke_with::<PaginationKey, EmptyField>(action, Some(params)).await;
                match endpoint.handle_or::<NotesResponse, Fallback<ErrorResponse>>(response) {
                    | Ok(notes) if notes.len() == 100 => match work_item_notes(&options.clone().with_page(options.page.saturating_add(1))).await {
                        | Ok(remaining) => Ok(notes.into_iter().chain(remaining).collect()),
                        | Err(why) => Err(why),
                    },
                    | result => result,
                }
            }
            | Err(why) => Err(why),
        }
    }
    .boxed()
}
/// Create or update the bot-authored citation-intake report note
pub async fn upsert_work_item_note(options: &Options, marker: &str, body: &str) -> ApiResult<Note> {
    match current_user(options).await {
        | Ok(identity) => match work_item_notes(options).await {
            | Ok(notes) => {
                let existing = notes
                    .into_iter()
                    .find(|note| note.body().contains(marker) && note.author_id() == Some(identity.identifier));
                write_work_item_note(options, existing.map(|note| note.identifier()), body).await
            }
            | Err(why) => Err(why),
        },
        | Err(why) => Err(why),
    }
}
async fn write_work_item_note(options: &Options, note_id: Option<u64>, body: &str) -> ApiResult<Note> {
    let action = if note_id.is_some() { "issue-note::update" } else { "issue-note" };
    match authenticated_endpoint(action, options) {
        | Ok((endpoint, token)) => {
            let note_id = note_id.map(|value| value.to_string());
            let params = Params::new()
                .with_auth(&token, Some("PRIVATE-TOKEN"))
                .with_template("identifier", options.identifier())
                .with_template("internal_identifier", options.internal_identifier.as_deref())
                .with_template("note_id", note_id.as_deref())
                .with_body("body", body)
                .build();
            let response = endpoint.invoke(action, Some(params)).await;
            endpoint.handle_or::<Note, Fallback<ErrorResponse>>(response)
        }
        | Err(why) => Err(why),
    }
}
/// Create or update the bot-authored merge request report note
pub async fn upsert_merge_request_note(options: &Options, marker: &str, body: &str) -> ApiResult<Note> {
    match current_user(options).await {
        | Ok(identity) => match merge_request_notes(options).await {
            | Ok(notes) => {
                let existing = notes
                    .into_iter()
                    .find(|note| note.body().contains(marker) && note.author_id() == Some(identity.identifier));
                write_merge_request_note(options, existing.map(|note| note.identifier()), body).await
            }
            | Err(why) => Err(why),
        },
        | Err(why) => Err(why),
    }
}
async fn write_merge_request_note(options: &Options, note_id: Option<u64>, body: &str) -> ApiResult<Note> {
    let action = if note_id.is_some() {
        "merge-request-note::update"
    } else {
        "merge-request-note"
    };
    match authenticated_endpoint(action, options) {
        | Ok((endpoint, token)) => {
            let note_id = note_id.map(|value| value.to_string());
            let params = Params::new()
                .with_auth(&token, Some("PRIVATE-TOKEN"))
                .with_template("identifier", options.identifier())
                .with_template("internal_identifier", options.internal_identifier.as_deref())
                .with_template("note_id", note_id.as_deref())
                .with_body("body", body)
                .build();
            let response = endpoint.invoke(action, Some(params)).await;
            endpoint.handle_or::<Note, Fallback<ErrorResponse>>(response)
        }
        | Err(why) => Err(why),
    }
}
/// Add a note (comment) to a merge request using project identifier and merge request IID
///
/// When used in CI environment, the project identifier can be obtained from the `CI_PROJECT_ID` environment variable and the merge request IID can be obtained from the `CI_MERGE_REQUEST_IID` environment variable.
/// The GitLab token must be provided in the `CI_JOB_TOKEN` environment variable.
///
/// See <https://docs.gitlab.com/api/notes/#create-a-merge-request-note> for more information on this API endpoint and required parameters
pub async fn merge_request_note(options: &Options) -> ApiResult<NoteMetadata> {
    let template = "gitlab::api";
    let action = "merge-request-note";
    let path = format!("{template}::{action}");
    match require_non_empty_secret(&options.token, &path, &GITLAB_TOKEN_VARIABLE_NAMES) {
        | Ok(token) => match Endpoint::from_template(template).map(|e| e.with_domain(options.domain())) {
            | Ok(endpoint) => {
                let body = options.body.as_deref().unwrap_or_default();
                let params = Params::new()
                    .with_auth(&token, Some("PRIVATE-TOKEN"))
                    .with_body("body", body)
                    .with_template("identifier", options.identifier())
                    .with_template("internal_identifier", options.internal_identifier.as_deref())
                    .with_custom(options.params())
                    .build();
                let response = endpoint.invoke_with::<PaginationKey, EmptyField>(action, Some(params)).await;
                endpoint.handle::<NoteMetadata>(response)
            }
            | Err(why) => Err(why),
        },
        | Err(why) => Err(why),
    }
}
/// Get runner details by identifier
pub async fn runner(options: &Options) -> ApiResult<RunnerMetadata> {
    let template = "gitlab::api";
    let action = "runner";
    let path = format!("{template}::{action}");
    match require_non_empty_secret(&options.token, &path, &GITLAB_TOKEN_VARIABLE_NAMES) {
        | Ok(token) => match Endpoint::from_template(template).map(|e| e.with_domain(options.domain())) {
            | Ok(endpoint) => {
                let params = Params::new()
                    .with_auth(&token, Some("PRIVATE-TOKEN"))
                    .with_template("identifier", options.identifier())
                    .with_custom(options.params())
                    .build();
                let response = endpoint.invoke(action, Some(params)).await;
                endpoint.handle::<RunnerMetadata>(response)
            }
            | Err(why) => Err(why),
        },
        | Err(why) => Err(why),
    }
}
/// Get runners visible to user associated with given token
pub async fn runners(options: &Options) -> ApiResult<RunnersResponse> {
    let template = "gitlab::api";
    let action = "runners";
    let path = format!("{template}::{action}");
    match require_non_empty_secret(&options.token, &path, &GITLAB_TOKEN_VARIABLE_NAMES) {
        | Ok(token) => match Endpoint::from_template(template).map(|e| e.with_domain(options.domain())) {
            | Ok(endpoint) => {
                let params = Params::new()
                    .with_auth(&token, Some("PRIVATE-TOKEN"))
                    .with_custom(options.params())
                    .build();
                let response = endpoint.invoke_with::<PaginationKey, EmptyField>(action, Some(params)).await;
                endpoint.handle_or::<RunnersResponse, Fallback<ErrorResponse>>(response)
            }
            | Err(why) => Err(why),
        },
        | Err(why) => Err(why),
    }
}
/// Fetch one page of repository tree blob paths for a GitLab project
pub(crate) async fn tree_paths(options: &Options) -> ApiResult<TreeResponse> {
    let template = "gitlab::api";
    let action = "tree";
    match Endpoint::from_template(template).map(|e| e.with_domain(options.domain())) {
        | Ok(endpoint) => {
            let params = Params::new()
                .with_template("identifier", options.identifier())
                .with_keyvalue("per_page", Some("100"))
                .with_keyvalue("page", Some(&options.page.to_string()))
                .with_keyvalue("recursive", Some("true"))
                .with_keyvalue("path", options.path.as_deref())
                .with_custom(options.params());
            let token = if options.token.trim().is_empty() {
                first_env_var(&GITLAB_TOKEN_VARIABLE_NAMES)
            } else {
                Some(options.token.clone())
            };
            let params = match token.as_ref().filter(|v| !v.trim().is_empty()) {
                | Some(token) => params.with_auth(token, Some("PRIVATE-TOKEN")),
                | None => params,
            };
            let response = endpoint.invoke(action, Some(params.build())).await;
            handle_tree_paths_response(endpoint.handle_or::<TreeResponse, Fallback<ErrorResponse>>(response), options.page)
        }
        | Err(why) => Err(why),
    }
}