octorus 0.6.2

A TUI tool for GitHub PR review, designed for Helix editor users
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
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use super::client::{
    check_graphql_errors, gh_api, gh_api_graphql, gh_api_paginate, gh_command,
    gh_command_allow_exit_codes, FieldValue,
};
use crate::app::ReviewAction;

define_state_filter!(PrStateFilter);

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StatusCheckRollupItem {
    #[serde(rename = "__typename")]
    pub type_name: String,
    pub name: Option<String>,
    pub status: Option<String>,
    pub conclusion: Option<String>,
    pub context: Option<String>,
    pub state: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CiStatus {
    Success,
    Failure,
    Pending,
    None,
}

impl CiStatus {
    pub fn from_rollup(items: &[StatusCheckRollupItem]) -> Self {
        if items.is_empty() {
            return Self::None;
        }
        let mut has_pending = false;
        for item in items {
            match item.type_name.as_str() {
                "CheckRun" => match item.conclusion.as_deref() {
                    Some("SUCCESS") | Some("NEUTRAL") | Some("SKIPPED") => {}
                    // gh returns conclusion: "" for in-progress/queued checks
                    None | Some("") => {
                        has_pending = true;
                    }
                    Some(_) => return Self::Failure,
                },
                "StatusContext" => match item.state.as_deref() {
                    Some("SUCCESS") => {}
                    // gh returns state: "" for in-progress StatusContext entries
                    Some("PENDING") | Some("EXPECTED") | Some("") => has_pending = true,
                    Some(_) => return Self::Failure,
                    None => {}
                },
                _ => {}
            }
        }
        if has_pending {
            Self::Pending
        } else {
            Self::Success
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CheckItem {
    pub name: String,
    pub state: String,
    pub bucket: Option<String>,
    pub link: Option<String>,
    #[serde(default)]
    pub workflow: String,
    pub description: Option<String>,
    #[serde(rename = "startedAt")]
    pub started_at: Option<String>,
    #[serde(rename = "completedAt")]
    pub completed_at: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PullRequestSummary {
    pub number: u32,
    pub title: String,
    pub state: String,
    pub author: User,
    #[serde(rename = "isDraft")]
    pub is_draft: bool,
    pub labels: Vec<Label>,
    #[serde(rename = "updatedAt")]
    pub updated_at: String,
    #[serde(default, rename = "statusCheckRollup")]
    pub status_check_rollup: Vec<StatusCheckRollupItem>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Label {
    pub name: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PullRequest {
    pub number: u32,
    #[serde(default, rename = "node_id")]
    pub node_id: Option<String>,
    pub title: String,
    pub body: Option<String>,
    pub state: String,
    pub head: Branch,
    pub base: Branch,
    pub user: User,
    pub updated_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Branch {
    #[serde(rename = "ref")]
    pub ref_name: String,
    pub sha: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct User {
    pub login: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChangedFile {
    pub filename: String,
    pub status: String,
    pub additions: u32,
    pub deletions: u32,
    pub patch: Option<String>,
    #[serde(default)]
    pub viewed: bool,
}

pub async fn fetch_pr(repo: &str, pr_number: u32) -> Result<PullRequest> {
    let endpoint = format!("repos/{}/pulls/{}", repo, pr_number);
    let json = gh_api(&endpoint).await?;
    serde_json::from_value(json).context("Failed to parse PR response")
}

pub async fn fetch_changed_files(repo: &str, pr_number: u32) -> Result<Vec<ChangedFile>> {
    let endpoint = format!("repos/{}/pulls/{}/files?per_page=100", repo, pr_number);
    let json = gh_api_paginate(&endpoint).await?;
    serde_json::from_value(json).context("Failed to parse changed files response")
}

pub async fn submit_review(
    repo: &str,
    pr_number: u32,
    action: ReviewAction,
    body: &str,
) -> Result<()> {
    let action_flag = match action {
        ReviewAction::Approve => "--approve",
        ReviewAction::RequestChanges => "--request-changes",
        ReviewAction::Comment => "--comment",
    };

    gh_command(&[
        "pr",
        "review",
        &pr_number.to_string(),
        action_flag,
        "-b",
        body,
        "-R",
        repo,
    ])
    .await?;

    Ok(())
}

/// Fetch the raw diff for a PR using `gh pr diff`
pub async fn fetch_pr_diff(repo: &str, pr_number: u32) -> Result<String> {
    gh_command(&["pr", "diff", &pr_number.to_string(), "-R", repo]).await
}

#[derive(Debug, Deserialize)]
struct GraphqlPageInfo {
    #[serde(rename = "hasNextPage")]
    has_next_page: bool,
    #[serde(rename = "endCursor")]
    end_cursor: Option<String>,
}

#[derive(Debug, Deserialize)]
struct GraphqlPrFileNode {
    path: String,
    #[serde(rename = "viewerViewedState")]
    viewer_viewed_state: Option<String>,
}

#[derive(Debug, Deserialize)]
struct GraphqlPrFilesConnection {
    nodes: Vec<GraphqlPrFileNode>,
    #[serde(rename = "pageInfo")]
    page_info: GraphqlPageInfo,
}

#[derive(Debug, Deserialize)]
struct GraphqlPrNode {
    files: GraphqlPrFilesConnection,
}

#[derive(Debug, Deserialize)]
struct GraphqlFilesViewedStateData {
    node: Option<GraphqlPrNode>,
}

#[derive(Debug, Deserialize)]
struct GraphqlFilesViewedStateResponse {
    data: Option<GraphqlFilesViewedStateData>,
}

pub async fn fetch_files_viewed_state(
    _repo: &str,
    pr_node_id: &str,
) -> Result<HashMap<String, bool>> {
    let query = r#"
query($pullRequestId: ID!, $after: String) {
  node(id: $pullRequestId) {
    ... on PullRequest {
      files(first: 100, after: $after) {
        nodes {
          path
          viewerViewedState
        }
        pageInfo {
          hasNextPage
          endCursor
        }
      }
    }
  }
}
"#;

    let mut viewed_state = HashMap::new();
    let mut after: Option<String> = None;

    loop {
        let mut fields = vec![("pullRequestId", FieldValue::String(pr_node_id))];
        if let Some(cursor) = after.as_deref() {
            fields.push(("after", FieldValue::String(cursor)));
        }

        let response = gh_api_graphql(query, &fields).await?;

        check_graphql_errors(&response)?;

        let parsed: GraphqlFilesViewedStateResponse = serde_json::from_value(response)
            .context("Failed to parse files viewed-state GraphQL response")?;
        let Some(data) = parsed.data else {
            anyhow::bail!("GitHub GraphQL response missing data");
        };
        let Some(node) = data.node else {
            anyhow::bail!("Pull request node not found for viewed-state query");
        };

        for file in node.files.nodes {
            viewed_state.insert(
                file.path,
                matches!(file.viewer_viewed_state.as_deref(), Some("VIEWED")),
            );
        }

        if node.files.page_info.has_next_page {
            let Some(next_cursor) = node.files.page_info.end_cursor else {
                anyhow::bail!("GitHub GraphQL pageInfo missing endCursor");
            };
            after = Some(next_cursor);
        } else {
            break;
        }
    }

    Ok(viewed_state)
}

const MARK_VIEWED_QUERY: &str = r#"
mutation($pullRequestId: ID!, $path: String!) {
  markFileAsViewed(input: { pullRequestId: $pullRequestId, path: $path }) {
    clientMutationId
  }
}
"#;

const UNMARK_VIEWED_QUERY: &str = r#"
mutation($pullRequestId: ID!, $path: String!) {
  unmarkFileAsViewed(input: { pullRequestId: $pullRequestId, path: $path }) {
    clientMutationId
  }
}
"#;

pub async fn set_file_viewed(
    _repo: &str,
    pr_node_id: &str,
    path: &str,
    viewed: bool,
) -> Result<()> {
    let query = if viewed {
        MARK_VIEWED_QUERY
    } else {
        UNMARK_VIEWED_QUERY
    };

    let response = gh_api_graphql(
        query,
        &[
            ("pullRequestId", FieldValue::String(pr_node_id)),
            ("path", FieldValue::String(path)),
        ],
    )
    .await?;

    check_graphql_errors(&response)?;

    Ok(())
}

/// ページネーション結果
pub struct PrListPage {
    pub items: Vec<PullRequestSummary>,
    pub has_more: bool,
}

pub async fn fetch_pr_list(repo: &str, state: PrStateFilter, limit: u32) -> Result<PrListPage> {
    fetch_pr_list_with_offset(repo, state, 0, limit).await
}

/// PR一覧取得(オフセット付き、追加ロード用)
pub async fn fetch_pr_list_with_offset(
    repo: &str,
    state: PrStateFilter,
    offset: u32,
    limit: u32,
) -> Result<PrListPage> {
    // gh pr list doesn't support offset directly, so we fetch offset+limit+1 and skip
    let fetch_count = offset + limit + 1;
    let output = gh_command(&[
        "pr",
        "list",
        "-R",
        repo,
        "-s",
        state.as_gh_arg(),
        "--json",
        "number,title,state,author,isDraft,labels,updatedAt,statusCheckRollup",
        "--limit",
        &fetch_count.to_string(),
    ])
    .await?;

    let all_items: Vec<PullRequestSummary> =
        serde_json::from_str(&output).context("Failed to parse PR list response")?;

    // Check if there are more items beyond what we're returning
    let has_more = all_items.len() > (offset + limit) as usize;

    // Skip the offset items and take limit items
    let items: Vec<PullRequestSummary> = all_items
        .into_iter()
        .skip(offset as usize)
        .take(limit as usize)
        .collect();

    Ok(PrListPage { items, has_more })
}

pub async fn fetch_pr_checks(repo: &str, pr_number: u32) -> Result<Vec<CheckItem>> {
    let output = gh_command_allow_exit_codes(
        &[
            "pr",
            "checks",
            &pr_number.to_string(),
            "-R",
            repo,
            "--json",
            "name,state,bucket,link,workflow,description,startedAt,completedAt",
        ],
        &[8], // exit code 8 = checks pending
    )
    .await?;
    serde_json::from_str(&output).context("Failed to parse PR checks response")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_pr_state_filter_as_gh_arg() {
        assert_eq!(PrStateFilter::Open.as_gh_arg(), "open");
        assert_eq!(PrStateFilter::Closed.as_gh_arg(), "closed");
        assert_eq!(PrStateFilter::All.as_gh_arg(), "all");
    }

    #[test]
    fn test_pr_state_filter_display_name() {
        assert_eq!(PrStateFilter::Open.display_name(), "open");
        assert_eq!(PrStateFilter::Closed.display_name(), "closed");
        assert_eq!(PrStateFilter::All.display_name(), "all");
    }

    #[test]
    fn test_pr_state_filter_next_cycle() {
        assert_eq!(PrStateFilter::Open.next(), PrStateFilter::Closed);
        assert_eq!(PrStateFilter::Closed.next(), PrStateFilter::All);
        assert_eq!(PrStateFilter::All.next(), PrStateFilter::Open);
    }

    #[test]
    fn test_ci_status_from_rollup_empty() {
        assert_eq!(CiStatus::from_rollup(&[]), CiStatus::None);
    }

    #[test]
    fn test_ci_status_from_rollup_all_success() {
        let items = vec![
            StatusCheckRollupItem {
                type_name: "CheckRun".to_string(),
                name: Some("build".to_string()),
                status: Some("COMPLETED".to_string()),
                conclusion: Some("SUCCESS".to_string()),
                context: None,
                state: None,
            },
            StatusCheckRollupItem {
                type_name: "CheckRun".to_string(),
                name: Some("lint".to_string()),
                status: Some("COMPLETED".to_string()),
                conclusion: Some("NEUTRAL".to_string()),
                context: None,
                state: None,
            },
        ];
        assert_eq!(CiStatus::from_rollup(&items), CiStatus::Success);
    }

    #[test]
    fn test_ci_status_from_rollup_failure() {
        let items = vec![
            StatusCheckRollupItem {
                type_name: "CheckRun".to_string(),
                name: Some("build".to_string()),
                status: Some("COMPLETED".to_string()),
                conclusion: Some("SUCCESS".to_string()),
                context: None,
                state: None,
            },
            StatusCheckRollupItem {
                type_name: "CheckRun".to_string(),
                name: Some("test".to_string()),
                status: Some("COMPLETED".to_string()),
                conclusion: Some("FAILURE".to_string()),
                context: None,
                state: None,
            },
        ];
        assert_eq!(CiStatus::from_rollup(&items), CiStatus::Failure);
    }

    #[test]
    fn test_ci_status_from_rollup_pending() {
        let items = vec![
            StatusCheckRollupItem {
                type_name: "CheckRun".to_string(),
                name: Some("build".to_string()),
                status: Some("COMPLETED".to_string()),
                conclusion: Some("SUCCESS".to_string()),
                context: None,
                state: None,
            },
            StatusCheckRollupItem {
                type_name: "CheckRun".to_string(),
                name: Some("deploy".to_string()),
                status: Some("IN_PROGRESS".to_string()),
                conclusion: None,
                context: None,
                state: None,
            },
        ];
        assert_eq!(CiStatus::from_rollup(&items), CiStatus::Pending);
    }

    #[test]
    fn test_ci_status_from_rollup_status_context() {
        let items = vec![StatusCheckRollupItem {
            type_name: "StatusContext".to_string(),
            name: None,
            status: None,
            conclusion: None,
            context: Some("ci/test".to_string()),
            state: Some("PENDING".to_string()),
        }];
        assert_eq!(CiStatus::from_rollup(&items), CiStatus::Pending);
    }

    #[test]
    fn test_ci_status_from_rollup_skipped() {
        let items = vec![StatusCheckRollupItem {
            type_name: "CheckRun".to_string(),
            name: Some("skip-check".to_string()),
            status: Some("COMPLETED".to_string()),
            conclusion: Some("SKIPPED".to_string()),
            context: None,
            state: None,
        }];
        assert_eq!(CiStatus::from_rollup(&items), CiStatus::Success);
    }

    #[test]
    fn test_ci_status_from_rollup_empty_conclusion_is_pending() {
        // gh returns conclusion: "" (not null) for in-progress/queued checks
        let items = vec![
            StatusCheckRollupItem {
                type_name: "CheckRun".to_string(),
                name: Some("build".to_string()),
                status: Some("COMPLETED".to_string()),
                conclusion: Some("SUCCESS".to_string()),
                context: None,
                state: None,
            },
            StatusCheckRollupItem {
                type_name: "CheckRun".to_string(),
                name: Some("test".to_string()),
                status: Some("IN_PROGRESS".to_string()),
                conclusion: Some("".to_string()),
                context: None,
                state: None,
            },
        ];
        assert_eq!(CiStatus::from_rollup(&items), CiStatus::Pending);
    }

    #[test]
    fn test_ci_status_from_rollup_empty_state_is_pending() {
        // gh may return state: "" for in-progress StatusContext entries,
        // analogous to conclusion: "" for CheckRun.
        let items = vec![StatusCheckRollupItem {
            type_name: "StatusContext".to_string(),
            name: None,
            status: None,
            conclusion: None,
            context: Some("ci/in-progress".to_string()),
            state: Some("".to_string()),
        }];
        assert_eq!(CiStatus::from_rollup(&items), CiStatus::Pending);
    }

    #[test]
    fn test_check_item_deserialize() {
        let json = r#"{
            "name": "build",
            "state": "SUCCESS",
            "bucket": "pass",
            "link": "https://example.com/run/1",
            "workflow": "CI",
            "description": "Build succeeded",
            "startedAt": "2024-01-01T00:00:00Z",
            "completedAt": "2024-01-01T00:05:00Z"
        }"#;
        let item: CheckItem = serde_json::from_str(json).unwrap();
        assert_eq!(item.name, "build");
        assert_eq!(item.bucket.as_deref(), Some("pass"));
        assert_eq!(item.link.as_deref(), Some("https://example.com/run/1"));
    }

    #[test]
    fn test_check_item_deserialize_minimal() {
        let json = r#"{
            "name": "test",
            "state": "PENDING",
            "workflow": ""
        }"#;
        let item: CheckItem = serde_json::from_str(json).unwrap();
        assert_eq!(item.name, "test");
        assert!(item.bucket.is_none());
        assert!(item.link.is_none());
    }

    #[test]
    fn test_status_check_rollup_item_deserialize() {
        let json = r#"{
            "__typename": "CheckRun",
            "name": "build",
            "status": "COMPLETED",
            "conclusion": "SUCCESS"
        }"#;
        let item: StatusCheckRollupItem = serde_json::from_str(json).unwrap();
        assert_eq!(item.type_name, "CheckRun");
        assert_eq!(item.name.as_deref(), Some("build"));
        assert_eq!(item.conclusion.as_deref(), Some("SUCCESS"));
    }
}