jj-vine 0.3.2

Stacked pull requests for jj (jujutsu). Supports GitLab and bookmark-based flow.
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
pub mod azure;
pub mod forgejo;
pub mod github;
pub mod gitlab;
pub mod test;

use std::borrow::Cow;

use bon::Builder;
use enum_dispatch::enum_dispatch;
use serde::{Deserialize, Serialize};

use crate::{
    config::{Config, ForgeType},
    description::FormatMergeRequest,
    error::Result,
};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ForgeUser {
    /// The ID of the user (usually a numeric ID)
    pub id: Option<String>,

    /// The username of the user
    pub username: Option<String>,
}

#[derive(Debug, Clone)]
pub enum ForgeMergeRequest {
    GitLab(gitlab::MergeRequest),
    GitHub(github::PullRequest),
    Forgejo(forgejo::PullRequest),
    Test(test::MergeRequest),
    AzureDevOps(Box<azure::GitPullRequest>),
}

impl ForgeMergeRequest {
    pub fn iid(&self) -> Cow<'_, str> {
        match self {
            ForgeMergeRequest::GitLab(mr) => Cow::Owned(mr.iid.to_string()),
            ForgeMergeRequest::GitHub(pr) => Cow::Owned(pr.number.to_string()),
            ForgeMergeRequest::Forgejo(pr) => Cow::Owned(pr.number.to_string()),
            ForgeMergeRequest::Test(mr) => Cow::Owned(mr.id.clone()),
            ForgeMergeRequest::AzureDevOps(mr) => Cow::Owned(mr.pull_request_id.to_string()),
        }
    }

    pub fn title(&self) -> &str {
        match self {
            ForgeMergeRequest::GitLab(mr) => &mr.title,
            ForgeMergeRequest::GitHub(pr) => &pr.title,
            ForgeMergeRequest::Forgejo(pr) => &pr.title,
            ForgeMergeRequest::Test(mr) => &mr.title,
            ForgeMergeRequest::AzureDevOps(mr) => &mr.title,
        }
    }

    pub fn description(&self) -> &str {
        match self {
            ForgeMergeRequest::GitLab(mr) => mr.description.as_deref().unwrap_or(""),
            ForgeMergeRequest::GitHub(pr) => pr.body.as_deref().unwrap_or(""),
            ForgeMergeRequest::Forgejo(pr) => pr.body.as_deref().unwrap_or(""),
            ForgeMergeRequest::Test(mr) => mr.description.as_deref().unwrap_or(""),
            ForgeMergeRequest::AzureDevOps(mr) => &mr.description,
        }
    }

    pub fn source_branch(&self) -> &str {
        match self {
            ForgeMergeRequest::GitLab(mr) => &mr.source_branch,
            ForgeMergeRequest::GitHub(pr) => &pr.head.ref_name,
            ForgeMergeRequest::Forgejo(pr) => &pr.head.ref_name,
            ForgeMergeRequest::Test(mr) => &mr.source_branch,
            ForgeMergeRequest::AzureDevOps(mr) => {
                mr.source_ref_name.trim_start_matches("refs/heads/")
            }
        }
    }

    pub fn target_branch(&self) -> &str {
        match self {
            ForgeMergeRequest::GitLab(mr) => &mr.target_branch,
            ForgeMergeRequest::GitHub(pr) => &pr.base.ref_name,
            ForgeMergeRequest::Forgejo(pr) => &pr.base.ref_name,
            ForgeMergeRequest::Test(mr) => &mr.target_branch,
            ForgeMergeRequest::AzureDevOps(mr) => {
                mr.target_ref_name.trim_start_matches("refs/heads/")
            }
        }
    }

    pub fn state(&self) -> ForgeMergeRequestState {
        match self {
            ForgeMergeRequest::GitLab(mr) => {
                if mr.state == "opened" {
                    ForgeMergeRequestState::Open
                } else if mr.state == "closed" {
                    ForgeMergeRequestState::Closed
                } else if mr.state == "merged" {
                    ForgeMergeRequestState::Merged
                } else {
                    ForgeMergeRequestState::Open
                }
            }
            ForgeMergeRequest::GitHub(pr) => {
                if pr.merged {
                    ForgeMergeRequestState::Merged
                } else if pr.state == "open" {
                    ForgeMergeRequestState::Open
                } else {
                    ForgeMergeRequestState::Closed
                }
            }
            ForgeMergeRequest::Forgejo(pr) => {
                if pr.merged {
                    ForgeMergeRequestState::Merged
                } else if pr.state == "open" {
                    ForgeMergeRequestState::Open
                } else {
                    ForgeMergeRequestState::Closed
                }
            }
            ForgeMergeRequest::Test(mr) => mr.state,
            ForgeMergeRequest::AzureDevOps(mr) => match mr.status {
                azure::PullRequestStatus::Abandoned => ForgeMergeRequestState::Closed,
                azure::PullRequestStatus::Completed => ForgeMergeRequestState::Merged,
                azure::PullRequestStatus::Active => ForgeMergeRequestState::Open,
                azure::PullRequestStatus::All => ForgeMergeRequestState::Open,
                azure::PullRequestStatus::NotSet => ForgeMergeRequestState::Open,
            },
        }
    }

    pub fn url(&self, forge: &ForgeImpl) -> Cow<'_, str> {
        match self {
            ForgeMergeRequest::GitLab(mr) => Cow::Borrowed(&mr.web_url),
            ForgeMergeRequest::GitHub(pr) => Cow::Borrowed(&pr.html_url),
            ForgeMergeRequest::Forgejo(pr) => Cow::Borrowed(&pr.html_url),
            ForgeMergeRequest::Test(mr) => Cow::Borrowed(&mr.url),
            ForgeMergeRequest::AzureDevOps(mr) => match forge {
                ForgeImpl::AzureDevOps(forge) => Cow::Owned(mr.web_url(forge)),
                _ => panic!(
                    "Azure DevOps merge request URL can only be retrieved from an Azure DevOps forge"
                ),
            },
        }
    }

    pub fn edit_url(&self, forge: &ForgeImpl) -> Cow<'_, str> {
        match self {
            ForgeMergeRequest::GitLab(mr) => Cow::Owned(format!("{}/edit", mr.web_url)),
            ForgeMergeRequest::GitHub(pr) => Cow::Borrowed(&pr.html_url),
            ForgeMergeRequest::Forgejo(pr) => Cow::Borrowed(&pr.html_url),
            ForgeMergeRequest::Test(mr) => Cow::Borrowed(&mr.url),
            ForgeMergeRequest::AzureDevOps(mr) => match forge {
                ForgeImpl::AzureDevOps(forge) => Cow::Owned(mr.web_url(forge)),
                _ => panic!(
                    "Azure DevOps merge request URL can only be retrieved from an Azure DevOps forge"
                ),
            },
        }
    }

    pub fn author_username(&self) -> &str {
        match self {
            ForgeMergeRequest::GitLab(mr) => &mr.author.username,
            ForgeMergeRequest::GitHub(pr) => &pr.user.login,
            ForgeMergeRequest::Forgejo(pr) => &pr.user.login,
            ForgeMergeRequest::Test(mr) => &mr.author_username,
            ForgeMergeRequest::AzureDevOps(mr) => &mr.created_by.descriptor,
        }
    }

    pub fn created_at(&self) -> jiff::Timestamp {
        match self {
            ForgeMergeRequest::GitLab(mr) => mr
                .created_at
                .parse()
                .expect("Failed to parse created at timestamp from GitLab API response"),
            ForgeMergeRequest::GitHub(pr) => pr
                .created_at
                .parse()
                .expect("Failed to parse created at timestamp from GitHub API response"),
            ForgeMergeRequest::Forgejo(pr) => pr
                .created_at
                .parse()
                .expect("Failed to parse created at timestamp from Forgejo API response"),
            ForgeMergeRequest::Test(mr) => mr.created_at,
            ForgeMergeRequest::AzureDevOps(mr) => mr
                .creation_date
                .parse()
                .expect("Failed to parse created at timestamp from Azure DevOps API response"),
        }
    }

    pub fn assignees(&self) -> Vec<ForgeUser> {
        match self {
            ForgeMergeRequest::GitLab(mr) => mr
                .assignees
                .clone()
                .into_iter()
                .map(ForgeUser::from)
                .collect(),
            ForgeMergeRequest::GitHub(pr) => pr
                .assignees
                .clone()
                .into_iter()
                .map(ForgeUser::from)
                .collect(),
            ForgeMergeRequest::Forgejo(pr) => pr
                .assignees
                .clone()
                .unwrap_or_default()
                .into_iter()
                .map(ForgeUser::from)
                .collect(),
            ForgeMergeRequest::Test(mr) => mr.assignees.clone(),
            ForgeMergeRequest::AzureDevOps(mr) => mr
                .reviewers
                .clone()
                .into_iter()
                .map(ForgeUser::from)
                .collect(),
        }
    }

    pub fn reviewers(&self) -> Vec<ForgeUser> {
        match self {
            ForgeMergeRequest::GitLab(mr) => mr
                .reviewers
                .clone()
                .into_iter()
                .map(ForgeUser::from)
                .collect(),
            ForgeMergeRequest::GitHub(pr) => pr
                .requested_reviewers
                .clone()
                .into_iter()
                .map(ForgeUser::from)
                .collect(),
            ForgeMergeRequest::Forgejo(pr) => pr
                .requested_reviewers
                .clone()
                .unwrap_or_default()
                .into_iter()
                .map(ForgeUser::from)
                .collect(),
            ForgeMergeRequest::Test(mr) => mr.reviewers.clone(),
            ForgeMergeRequest::AzureDevOps(mr) => mr
                .reviewers
                .clone()
                .into_iter()
                .map(ForgeUser::from)
                .collect(),
        }
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
pub enum ForgeMergeRequestState {
    #[default]
    Open,
    Closed,
    Merged,
}

/// Status of CI/Pipeline checks
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum CheckStatus {
    /// All checks passed
    Success,
    /// Checks are still running
    Pending,
    /// Some checks failed
    Failed,
    /// No checks configured or required
    #[default]
    None,
}

/// Satisfaction of approval requirements
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ApprovalSatisfaction {
    /// All approval requirements are satisfied
    Satisfied,

    /// Some approval requirements are not satisfied
    Unsatisfied,

    /// Approval requirements are unknown
    Unknown,
}

/// Approval status of a merge request
#[derive(Debug, Clone)]
pub struct ApprovalStatus {
    /// Number of approvals received
    pub approved_count: u32,

    /// Number of approvals required
    pub required_count: u32,

    /// Number of approvals that are blocking the merge request
    pub blocking_count: u32,

    /// Whether approval requirements are satisfied
    pub satisfaction: ApprovalSatisfaction,
}

impl Default for ApprovalStatus {
    fn default() -> Self {
        Self {
            approved_count: 0,
            required_count: 0,
            blocking_count: 0,
            satisfaction: ApprovalSatisfaction::Unknown,
        }
    }
}

/// Complete status information for a merge request
#[derive(Debug, Clone)]
pub struct MergeRequestStatus {
    /// The internal ID of the merge request
    pub iid: String,

    /// CI/Pipeline check status
    pub check_status: CheckStatus,

    /// Approval status
    pub approval_status: ApprovalStatus,
}

impl MergeRequestStatus {
    pub fn ready_to_merge(&self) -> bool {
        self.approval_status.satisfaction == ApprovalSatisfaction::Satisfied
            && (self.check_status == CheckStatus::Success || self.check_status == CheckStatus::None)
    }
}

#[derive(Builder, Default)]
pub struct ForgeCreateMergeRequestOptions {
    /// The source branch of the merge request
    pub source_branch: String,

    /// The target branch of the merge request
    pub target_branch: String,

    /// The title of the merge request
    pub title: String,

    /// The description of the merge request
    #[builder(required)]
    pub description: Option<String>,

    /// The usernames of the initial assignees of the merge request
    pub assignee_usernames: Vec<String>,

    /// The usernames of the initial assignees of the merge request
    pub reviewer_usernames: Vec<String>,

    /// Whether to remove the source branch after the merge request is merged
    pub remove_source_branch: bool,

    /// Whether to squash the commits into a single commit
    pub squash: bool,

    /// Whether to open the merge request as a draft
    pub open_as_draft: bool,
}

#[derive(Debug, Clone, Default)]
pub struct DiscussionCount {
    /// The total number of discussions.
    pub all: u32,

    /// The number of unresolved (resolvable) discussions.
    pub unresolved: u32,

    /// The number of resolved discussions.
    pub resolved: u32,
}

/// A trait for a code forge (e.g. GitLab, GitHub, Forgejo, etc.)
#[enum_dispatch]
pub trait Forge: Send + Sync + FormatMergeRequest {
    /// The project ID of the project in the forge. E.g. "group/project" or
    /// "12345" for a numeric project ID. Combined with the base URL, this forms
    /// the full URL to the project in the forge.
    fn project_id(&self) -> &str;

    /// The project ID where branches are pushed (source/fork project).
    fn source_project_id(&self) -> &str;

    /// The project ID where MRs/PRs are created (target/upstream project).
    fn target_project_id(&self) -> &str;

    /// The base URL of the forge. E.g. <https://gitlab.example.com>.
    fn base_url(&self) -> &str;

    /// The full URL to the project in the forge. E.g. <https://gitlab.example.com/group/project>.
    fn project_url(&self) -> String {
        format!("{}/{}", self.base_url(), self.project_id())
    }

    /// Get the current authenticated user in the forge.
    async fn current_user(&self) -> Result<ForgeUser>;

    /// Gets a user in the forge by their username.
    async fn user_by_username(&self, username: &str) -> Result<Option<ForgeUser>>;

    /// Find merge request by source branch name. Returns the first MR found.
    /// with the given source branch, or None if not found
    async fn find_merge_request_by_source_branch(
        &self,
        branch: &str,
    ) -> Result<Option<ForgeMergeRequest>>;

    /// Create a new merge request in the forge for the project.
    async fn create_merge_request(
        &self,
        options: ForgeCreateMergeRequestOptions,
    ) -> Result<ForgeMergeRequest>;

    /// Update the target branch (base) of an existing merge request.
    async fn update_merge_request_base(
        &self,
        merge_request_iid: &str,
        new_base: &str,
    ) -> Result<ForgeMergeRequest>;

    /// Update the description of an existing merge request.
    async fn update_merge_request_description(
        &self,
        merge_request_iid: &str,
        new_description: &str,
    ) -> Result<ForgeMergeRequest>;

    /// Get a specific merge request by IID.
    async fn get_merge_request(&self, merge_request_iid: &str) -> Result<ForgeMergeRequest>;

    /// Get approval status for a merge request.
    async fn get_approval_status(&self, merge_request_iid: &str) -> Result<ApprovalStatus>;

    /// Get CI/pipeline check status for a merge request.
    async fn get_check_status(&self, merge_request_iid: &str) -> Result<CheckStatus>;

    /// Get complete status information for a merge request.
    async fn get_merge_request_status(&self, merge_request_iid: &str)
    -> Result<MergeRequestStatus>;

    /// Get the number of open discussions for a merge request.
    async fn num_open_discussions(&self, merge_request_iid: &str) -> Result<DiscussionCount>;

    /// Sync dependent merge requests for a merge request.
    /// Only currently supported for GitLab. No-op for other forges.
    /// Returns true if any changes were made.
    async fn sync_dependent_merge_requests(
        &self,
        merge_request_iid: &str,
        dependent_merge_request_iids: &[&str],
    ) -> Result<bool>;
}

#[enum_dispatch(Forge, FormatMergeRequest)]
pub enum ForgeImpl {
    GitLab(gitlab::GitLabForge),
    GitHub(github::GitHubForge),
    Forgejo(forgejo::ForgejoForge),
    Test(test::TestForge),
    AzureDevOps(azure::AzureDevOpsForge),
}

impl ForgeImpl {
    /// Create a new forge. Looks for a jj-vine config in the current directory.
    pub fn from_cwd() -> Result<Self> {
        let cwd = std::env::current_dir()?;
        let config = Config::load(&cwd)?;
        Self::new(&config)
    }

    pub fn new(config: &Config) -> Result<Self> {
        config.validate()?;

        match config.forge {
            ForgeType::GitLab => {
                let source = config.gitlab.source_project();
                let target = config.gitlab.target_project();
                gitlab::GitLabForge::new(
                    config.gitlab.host.clone(),
                    source.to_string(),
                    target.to_string(),
                    config.gitlab.token.clone(),
                    config.ca_bundle.clone(),
                    config.tls_accept_non_compliant_certs,
                    config.gitlab.create_merge_request_dependencies,
                )
                .map(|forge| forge.into())
            }
            ForgeType::GitHub => {
                let source = config.github.source_project();
                let target = config.github.target_project();
                github::GitHubForge::new(
                    config.github.host.clone(),
                    source.to_string(),
                    target.to_string(),
                    config.github.token.clone(),
                    config.ca_bundle.clone(),
                    config.tls_accept_non_compliant_certs,
                )
                .map(|forge| forge.into())
            }
            ForgeType::Forgejo => {
                let source = config.forgejo.source_project();
                let target = config.forgejo.target_project();
                forgejo::ForgejoForge::new(
                    config.forgejo.host.clone(),
                    source.to_string(),
                    target.to_string(),
                    config.forgejo.token.clone(),
                    config.ca_bundle.clone(),
                    config.tls_accept_non_compliant_certs,
                    config.forgejo.wip_prefix.clone(),
                )
                .map(|forge| forge.into())
            }
            ForgeType::AzureDevOps => azure::AzureDevOpsForge::builder()
                .base_url(config.azure.host.clone())
                .vssps_base_url(config.azure.vssps_host.clone())
                .source_project_id(config.azure.source_project_id())
                .target_project_id(config.azure.target_project_id())
                .token(config.azure.token.clone())
                .maybe_source_repository_name(config.azure.source_repository_name.clone())
                .maybe_target_repository_name(
                    config.azure.target_repository_name().map(str::to_string),
                )
                .maybe_source_repository_id(config.azure.source_repository_id.clone())
                .maybe_target_repository_id(config.azure.target_repository_id().map(str::to_string))
                .accept_non_compliant_certs(config.tls_accept_non_compliant_certs)
                .maybe_ca_bundle(config.ca_bundle.clone())
                .build()
                .map(Into::into),
        }
    }
}