-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy pathgh_cmd.rs
More file actions
1457 lines (1221 loc) · 45.1 KB
/
gh_cmd.rs
File metadata and controls
1457 lines (1221 loc) · 45.1 KB
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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! GitHub CLI (gh) command output compression.
//!
//! Provides token-optimized alternatives to verbose `gh` commands.
//! Focuses on extracting essential information from JSON outputs.
use crate::git;
use crate::json_cmd;
use crate::tracking;
use crate::utils::{ok_confirmation, truncate};
use anyhow::{Context, Result};
use regex::Regex;
use serde_json::Value;
use std::process::Command;
use std::sync::LazyLock;
static HTML_COMMENT_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?s)<!--.*?-->").unwrap());
static BADGE_LINE_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(?m)^\s*\[!\[[^\]]*\]\([^)]*\)\]\([^)]*\)\s*$").unwrap());
static IMAGE_ONLY_LINE_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(?m)^\s*!\[[^\]]*\]\([^)]*\)\s*$").unwrap());
static HORIZONTAL_RULE_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(?m)^\s*(?:---+|\*\*\*+|___+)\s*$").unwrap());
static MULTI_BLANK_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\n{3,}").unwrap());
/// Filter markdown body to remove noise while preserving meaningful content.
/// Removes HTML comments, badge lines, image-only lines, horizontal rules,
/// and collapses excessive blank lines. Preserves code blocks untouched.
fn filter_markdown_body(body: &str) -> String {
if body.is_empty() {
return String::new();
}
// Split into code blocks and non-code segments
let mut result = String::new();
let mut remaining = body;
loop {
// Find next code block opening (``` or ~~~)
let fence_pos = remaining
.find("```")
.or_else(|| remaining.find("~~~"))
.map(|pos| {
let fence = if remaining[pos..].starts_with("```") {
"```"
} else {
"~~~"
};
(pos, fence)
});
match fence_pos {
Some((start, fence)) => {
// Filter the text before the code block
let before = &remaining[..start];
result.push_str(&filter_markdown_segment(before));
// Find the closing fence
let after_open = start + fence.len();
// Skip past the opening fence line
let code_start = remaining[after_open..]
.find('\n')
.map(|p| after_open + p + 1)
.unwrap_or(remaining.len());
let close_pos = remaining[code_start..]
.find(fence)
.map(|p| code_start + p + fence.len());
match close_pos {
Some(end) => {
// Preserve the entire code block as-is
result.push_str(&remaining[start..end]);
// Include the rest of the closing fence line
let after_close = remaining[end..]
.find('\n')
.map(|p| end + p + 1)
.unwrap_or(remaining.len());
result.push_str(&remaining[end..after_close]);
remaining = &remaining[after_close..];
}
None => {
// Unclosed code block — preserve everything
result.push_str(&remaining[start..]);
remaining = "";
}
}
}
None => {
// No more code blocks, filter the rest
result.push_str(&filter_markdown_segment(remaining));
break;
}
}
}
// Final cleanup: trim trailing whitespace
result.trim().to_string()
}
/// Filter a markdown segment that is NOT inside a code block.
fn filter_markdown_segment(text: &str) -> String {
let mut s = HTML_COMMENT_RE.replace_all(text, "").to_string();
s = BADGE_LINE_RE.replace_all(&s, "").to_string();
s = IMAGE_ONLY_LINE_RE.replace_all(&s, "").to_string();
s = HORIZONTAL_RULE_RE.replace_all(&s, "").to_string();
s = MULTI_BLANK_RE.replace_all(&s, "\n\n").to_string();
s
}
/// Run a gh command with token-optimized output
pub fn run(subcommand: &str, args: &[String], verbose: u8, ultra_compact: bool) -> Result<()> {
match subcommand {
"pr" => run_pr(args, verbose, ultra_compact),
"issue" => run_issue(args, verbose, ultra_compact),
"run" => run_workflow(args, verbose, ultra_compact),
"repo" => run_repo(args, verbose, ultra_compact),
"api" => run_api(args, verbose),
_ => {
// Unknown subcommand, pass through
run_passthrough("gh", subcommand, args)
}
}
}
fn run_pr(args: &[String], verbose: u8, ultra_compact: bool) -> Result<()> {
if args.is_empty() {
return run_passthrough("gh", "pr", args);
}
match args[0].as_str() {
"list" => list_prs(&args[1..], verbose, ultra_compact),
"view" => view_pr(&args[1..], verbose, ultra_compact),
"checks" => pr_checks(&args[1..], verbose, ultra_compact),
"status" => pr_status(verbose, ultra_compact),
"create" => pr_create(&args[1..], verbose),
"merge" => pr_merge(&args[1..], verbose),
"diff" => pr_diff(&args[1..], verbose),
"comment" => pr_action("commented", &args[1..], verbose),
"edit" => pr_action("edited", &args[1..], verbose),
_ => run_passthrough("gh", "pr", args),
}
}
fn list_prs(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
let timer = tracking::TimedExecution::start();
let mut cmd = Command::new("gh");
cmd.args([
"pr",
"list",
"--json",
"number,title,state,author,updatedAt",
]);
// Pass through additional flags
for arg in args {
cmd.arg(arg);
}
let output = cmd.output().context("Failed to run gh pr list")?;
let raw = String::from_utf8_lossy(&output.stdout).to_string();
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
timer.track("gh pr list", "rtk gh pr list", &stderr, &stderr);
eprintln!("{}", stderr.trim());
std::process::exit(output.status.code().unwrap_or(1));
}
let json: Value =
serde_json::from_slice(&output.stdout).context("Failed to parse gh pr list output")?;
let mut filtered = String::new();
if let Some(prs) = json.as_array() {
if ultra_compact {
filtered.push_str("PRs\n");
println!("PRs");
} else {
filtered.push_str("📋 Pull Requests\n");
println!("📋 Pull Requests");
}
for pr in prs.iter().take(20) {
let number = pr["number"].as_i64().unwrap_or(0);
let title = pr["title"].as_str().unwrap_or("???");
let state = pr["state"].as_str().unwrap_or("???");
let author = pr["author"]["login"].as_str().unwrap_or("???");
let state_icon = if ultra_compact {
match state {
"OPEN" => "O",
"MERGED" => "M",
"CLOSED" => "C",
_ => "?",
}
} else {
match state {
"OPEN" => "🟢",
"MERGED" => "🟣",
"CLOSED" => "🔴",
_ => "⚪",
}
};
let line = format!(
" {} #{} {} ({})\n",
state_icon,
number,
truncate(title, 60),
author
);
filtered.push_str(&line);
print!("{}", line);
}
if prs.len() > 20 {
let more_line = format!(" ... {} more (use gh pr list for all)\n", prs.len() - 20);
filtered.push_str(&more_line);
print!("{}", more_line);
}
}
timer.track("gh pr list", "rtk gh pr list", &raw, &filtered);
Ok(())
}
fn view_pr(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
let timer = tracking::TimedExecution::start();
if args.is_empty() {
return Err(anyhow::anyhow!("PR number required"));
}
let pr_number = &args[0];
let mut cmd = Command::new("gh");
cmd.args([
"pr",
"view",
pr_number,
"--json",
"number,title,state,author,body,url,mergeable,reviews,statusCheckRollup",
]);
let output = cmd.output().context("Failed to run gh pr view")?;
let raw = String::from_utf8_lossy(&output.stdout).to_string();
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
timer.track(
&format!("gh pr view {}", pr_number),
&format!("rtk gh pr view {}", pr_number),
&stderr,
&stderr,
);
eprintln!("{}", stderr.trim());
std::process::exit(output.status.code().unwrap_or(1));
}
let json: Value =
serde_json::from_slice(&output.stdout).context("Failed to parse gh pr view output")?;
let mut filtered = String::new();
// Extract essential info
let number = json["number"].as_i64().unwrap_or(0);
let title = json["title"].as_str().unwrap_or("???");
let state = json["state"].as_str().unwrap_or("???");
let author = json["author"]["login"].as_str().unwrap_or("???");
let url = json["url"].as_str().unwrap_or("");
let mergeable = json["mergeable"].as_str().unwrap_or("UNKNOWN");
let state_icon = if ultra_compact {
match state {
"OPEN" => "O",
"MERGED" => "M",
"CLOSED" => "C",
_ => "?",
}
} else {
match state {
"OPEN" => "🟢",
"MERGED" => "🟣",
"CLOSED" => "🔴",
_ => "⚪",
}
};
let line = format!("{} PR #{}: {}\n", state_icon, number, title);
filtered.push_str(&line);
print!("{}", line);
let line = format!(" {}\n", author);
filtered.push_str(&line);
print!("{}", line);
let mergeable_str = match mergeable {
"MERGEABLE" => "✓",
"CONFLICTING" => "✗",
_ => "?",
};
let line = format!(" {} | {}\n", state, mergeable_str);
filtered.push_str(&line);
print!("{}", line);
// Show reviews summary
if let Some(reviews) = json["reviews"]["nodes"].as_array() {
let approved = reviews
.iter()
.filter(|r| r["state"].as_str() == Some("APPROVED"))
.count();
let changes = reviews
.iter()
.filter(|r| r["state"].as_str() == Some("CHANGES_REQUESTED"))
.count();
if approved > 0 || changes > 0 {
let line = format!(
" Reviews: {} approved, {} changes requested\n",
approved, changes
);
filtered.push_str(&line);
print!("{}", line);
}
}
// Show checks summary
if let Some(checks) = json["statusCheckRollup"].as_array() {
let total = checks.len();
let passed = checks
.iter()
.filter(|c| {
c["conclusion"].as_str() == Some("SUCCESS")
|| c["state"].as_str() == Some("SUCCESS")
})
.count();
let failed = checks
.iter()
.filter(|c| {
c["conclusion"].as_str() == Some("FAILURE")
|| c["state"].as_str() == Some("FAILURE")
})
.count();
if ultra_compact {
if failed > 0 {
let line = format!(" ✗{}/{} {} fail\n", passed, total, failed);
filtered.push_str(&line);
print!("{}", line);
} else {
let line = format!(" ✓{}/{}\n", passed, total);
filtered.push_str(&line);
print!("{}", line);
}
} else {
let line = format!(" Checks: {}/{} passed\n", passed, total);
filtered.push_str(&line);
print!("{}", line);
if failed > 0 {
let line = format!(" ⚠️ {} checks failed\n", failed);
filtered.push_str(&line);
print!("{}", line);
}
}
}
let line = format!(" {}\n", url);
filtered.push_str(&line);
print!("{}", line);
// Show filtered body
if let Some(body) = json["body"].as_str() {
if !body.is_empty() {
let body_filtered = filter_markdown_body(body);
if !body_filtered.is_empty() {
filtered.push('\n');
println!();
for line in body_filtered.lines() {
let formatted = format!(" {}\n", line);
filtered.push_str(&formatted);
print!("{}", formatted);
}
}
}
}
timer.track(
&format!("gh pr view {}", pr_number),
&format!("rtk gh pr view {}", pr_number),
&raw,
&filtered,
);
Ok(())
}
fn pr_checks(args: &[String], _verbose: u8, _ultra_compact: bool) -> Result<()> {
let timer = tracking::TimedExecution::start();
if args.is_empty() {
return Err(anyhow::anyhow!("PR number required"));
}
let pr_number = &args[0];
let mut cmd = Command::new("gh");
cmd.args(["pr", "checks", pr_number]);
let output = cmd.output().context("Failed to run gh pr checks")?;
let raw = String::from_utf8_lossy(&output.stdout).to_string();
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
timer.track(
&format!("gh pr checks {}", pr_number),
&format!("rtk gh pr checks {}", pr_number),
&stderr,
&stderr,
);
eprintln!("{}", stderr.trim());
std::process::exit(output.status.code().unwrap_or(1));
}
let stdout = String::from_utf8_lossy(&output.stdout);
// Parse and compress checks output
let mut passed = 0;
let mut failed = 0;
let mut pending = 0;
let mut failed_checks = Vec::new();
for line in stdout.lines() {
if line.contains('✓') || line.contains("pass") {
passed += 1;
} else if line.contains('✗') || line.contains("fail") {
failed += 1;
failed_checks.push(line.trim().to_string());
} else if line.contains('*') || line.contains("pending") {
pending += 1;
}
}
let mut filtered = String::new();
let line = "🔍 CI Checks Summary:\n";
filtered.push_str(line);
print!("{}", line);
let line = format!(" ✅ Passed: {}\n", passed);
filtered.push_str(&line);
print!("{}", line);
let line = format!(" ❌ Failed: {}\n", failed);
filtered.push_str(&line);
print!("{}", line);
if pending > 0 {
let line = format!(" ⏳ Pending: {}\n", pending);
filtered.push_str(&line);
print!("{}", line);
}
if !failed_checks.is_empty() {
let line = "\n Failed checks:\n";
filtered.push_str(line);
print!("{}", line);
for check in failed_checks {
let line = format!(" {}\n", check);
filtered.push_str(&line);
print!("{}", line);
}
}
timer.track(
&format!("gh pr checks {}", pr_number),
&format!("rtk gh pr checks {}", pr_number),
&raw,
&filtered,
);
Ok(())
}
fn pr_status(_verbose: u8, _ultra_compact: bool) -> Result<()> {
let timer = tracking::TimedExecution::start();
let mut cmd = Command::new("gh");
cmd.args([
"pr",
"status",
"--json",
"currentBranch,createdBy,reviewDecision,statusCheckRollup",
]);
let output = cmd.output().context("Failed to run gh pr status")?;
let raw = String::from_utf8_lossy(&output.stdout).to_string();
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
timer.track("gh pr status", "rtk gh pr status", &stderr, &stderr);
eprintln!("{}", stderr.trim());
std::process::exit(output.status.code().unwrap_or(1));
}
let json: Value =
serde_json::from_slice(&output.stdout).context("Failed to parse gh pr status output")?;
let mut filtered = String::new();
if let Some(created_by) = json["createdBy"].as_array() {
let line = format!("📝 Your PRs ({}):\n", created_by.len());
filtered.push_str(&line);
print!("{}", line);
for pr in created_by.iter().take(5) {
let number = pr["number"].as_i64().unwrap_or(0);
let title = pr["title"].as_str().unwrap_or("???");
let reviews = pr["reviewDecision"].as_str().unwrap_or("PENDING");
let line = format!(" #{} {} [{}]\n", number, truncate(title, 50), reviews);
filtered.push_str(&line);
print!("{}", line);
}
}
timer.track("gh pr status", "rtk gh pr status", &raw, &filtered);
Ok(())
}
fn run_issue(args: &[String], verbose: u8, ultra_compact: bool) -> Result<()> {
if args.is_empty() {
return run_passthrough("gh", "issue", args);
}
match args[0].as_str() {
"list" => list_issues(&args[1..], verbose, ultra_compact),
"view" => view_issue(&args[1..], verbose),
_ => run_passthrough("gh", "issue", args),
}
}
fn list_issues(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
let timer = tracking::TimedExecution::start();
let mut cmd = Command::new("gh");
cmd.args(["issue", "list", "--json", "number,title,state,author"]);
for arg in args {
cmd.arg(arg);
}
let output = cmd.output().context("Failed to run gh issue list")?;
let raw = String::from_utf8_lossy(&output.stdout).to_string();
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
timer.track("gh issue list", "rtk gh issue list", &stderr, &stderr);
eprintln!("{}", stderr.trim());
std::process::exit(output.status.code().unwrap_or(1));
}
let json: Value =
serde_json::from_slice(&output.stdout).context("Failed to parse gh issue list output")?;
let mut filtered = String::new();
if let Some(issues) = json.as_array() {
if ultra_compact {
filtered.push_str("Issues\n");
println!("Issues");
} else {
filtered.push_str("🐛 Issues\n");
println!("🐛 Issues");
}
for issue in issues.iter().take(20) {
let number = issue["number"].as_i64().unwrap_or(0);
let title = issue["title"].as_str().unwrap_or("???");
let state = issue["state"].as_str().unwrap_or("???");
let icon = if ultra_compact {
if state == "OPEN" {
"O"
} else {
"C"
}
} else {
if state == "OPEN" {
"🟢"
} else {
"🔴"
}
};
let line = format!(" {} #{} {}\n", icon, number, truncate(title, 60));
filtered.push_str(&line);
print!("{}", line);
}
if issues.len() > 20 {
let line = format!(" ... {} more\n", issues.len() - 20);
filtered.push_str(&line);
print!("{}", line);
}
}
timer.track("gh issue list", "rtk gh issue list", &raw, &filtered);
Ok(())
}
fn view_issue(args: &[String], _verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
if args.is_empty() {
return Err(anyhow::anyhow!("Issue number required"));
}
let issue_number = &args[0];
let mut cmd = Command::new("gh");
cmd.args([
"issue",
"view",
issue_number,
"--json",
"number,title,state,author,body,url",
]);
let output = cmd.output().context("Failed to run gh issue view")?;
let raw = String::from_utf8_lossy(&output.stdout).to_string();
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
timer.track(
&format!("gh issue view {}", issue_number),
&format!("rtk gh issue view {}", issue_number),
&stderr,
&stderr,
);
eprintln!("{}", stderr.trim());
std::process::exit(output.status.code().unwrap_or(1));
}
let json: Value =
serde_json::from_slice(&output.stdout).context("Failed to parse gh issue view output")?;
let number = json["number"].as_i64().unwrap_or(0);
let title = json["title"].as_str().unwrap_or("???");
let state = json["state"].as_str().unwrap_or("???");
let author = json["author"]["login"].as_str().unwrap_or("???");
let url = json["url"].as_str().unwrap_or("");
let icon = if state == "OPEN" { "🟢" } else { "🔴" };
let mut filtered = String::new();
let line = format!("{} Issue #{}: {}\n", icon, number, title);
filtered.push_str(&line);
print!("{}", line);
let line = format!(" Author: @{}\n", author);
filtered.push_str(&line);
print!("{}", line);
let line = format!(" Status: {}\n", state);
filtered.push_str(&line);
print!("{}", line);
let line = format!(" URL: {}\n", url);
filtered.push_str(&line);
print!("{}", line);
if let Some(body) = json["body"].as_str() {
if !body.is_empty() {
let body_filtered = filter_markdown_body(body);
if !body_filtered.is_empty() {
let line = "\n Description:\n";
filtered.push_str(line);
print!("{}", line);
for line in body_filtered.lines() {
let formatted = format!(" {}\n", line);
filtered.push_str(&formatted);
print!("{}", formatted);
}
}
}
}
timer.track(
&format!("gh issue view {}", issue_number),
&format!("rtk gh issue view {}", issue_number),
&raw,
&filtered,
);
Ok(())
}
fn run_workflow(args: &[String], verbose: u8, ultra_compact: bool) -> Result<()> {
if args.is_empty() {
return run_passthrough("gh", "run", args);
}
match args[0].as_str() {
"list" => list_runs(&args[1..], verbose, ultra_compact),
"view" => view_run(&args[1..], verbose),
_ => run_passthrough("gh", "run", args),
}
}
fn list_runs(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
let timer = tracking::TimedExecution::start();
let mut cmd = Command::new("gh");
cmd.args([
"run",
"list",
"--json",
"databaseId,name,status,conclusion,createdAt",
]);
cmd.arg("--limit").arg("10");
for arg in args {
cmd.arg(arg);
}
let output = cmd.output().context("Failed to run gh run list")?;
let raw = String::from_utf8_lossy(&output.stdout).to_string();
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
timer.track("gh run list", "rtk gh run list", &stderr, &stderr);
eprintln!("{}", stderr.trim());
std::process::exit(output.status.code().unwrap_or(1));
}
let json: Value =
serde_json::from_slice(&output.stdout).context("Failed to parse gh run list output")?;
let mut filtered = String::new();
if let Some(runs) = json.as_array() {
if ultra_compact {
filtered.push_str("Runs\n");
println!("Runs");
} else {
filtered.push_str("🏃 Workflow Runs\n");
println!("🏃 Workflow Runs");
}
for run in runs {
let id = run["databaseId"].as_i64().unwrap_or(0);
let name = run["name"].as_str().unwrap_or("???");
let status = run["status"].as_str().unwrap_or("???");
let conclusion = run["conclusion"].as_str().unwrap_or("");
let icon = if ultra_compact {
match conclusion {
"success" => "✓",
"failure" => "✗",
"cancelled" => "X",
_ => {
if status == "in_progress" {
"~"
} else {
"?"
}
}
}
} else {
match conclusion {
"success" => "✅",
"failure" => "❌",
"cancelled" => "🚫",
_ => {
if status == "in_progress" {
"⏳"
} else {
"⚪"
}
}
}
};
let line = format!(" {} {} [{}]\n", icon, truncate(name, 50), id);
filtered.push_str(&line);
print!("{}", line);
}
}
timer.track("gh run list", "rtk gh run list", &raw, &filtered);
Ok(())
}
/// Check if run view args should bypass filtering and pass through directly.
/// Flags like --log-failed, --log, and --json produce output that the filter
/// would incorrectly strip.
fn should_passthrough_run_view(extra_args: &[String]) -> bool {
extra_args
.iter()
.any(|a| a == "--log-failed" || a == "--log" || a == "--json")
}
fn view_run(args: &[String], _verbose: u8) -> Result<()> {
if args.is_empty() {
return Err(anyhow::anyhow!("Run ID required"));
}
let run_id = &args[0];
let extra_args = &args[1..];
// Pass through when user requests logs or JSON — the filter would strip them
if should_passthrough_run_view(extra_args) {
return run_passthrough_with_extra("gh", &["run", "view", run_id], extra_args);
}
let timer = tracking::TimedExecution::start();
let mut cmd = Command::new("gh");
cmd.args(["run", "view", run_id]);
let output = cmd.output().context("Failed to run gh run view")?;
let raw = String::from_utf8_lossy(&output.stdout).to_string();
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
timer.track(
&format!("gh run view {}", run_id),
&format!("rtk gh run view {}", run_id),
&stderr,
&stderr,
);
eprintln!("{}", stderr.trim());
std::process::exit(output.status.code().unwrap_or(1));
}
// Parse output and show only failures
let stdout = String::from_utf8_lossy(&output.stdout);
let mut in_jobs = false;
let mut filtered = String::new();
let line = format!("🏃 Workflow Run #{}\n", run_id);
filtered.push_str(&line);
print!("{}", line);
for line in stdout.lines() {
if line.contains("JOBS") {
in_jobs = true;
}
if in_jobs {
if line.contains('✓') || line.contains("success") {
// Skip successful jobs in compact mode
continue;
}
if line.contains('✗') || line.contains("fail") {
let formatted = format!(" ❌ {}\n", line.trim());
filtered.push_str(&formatted);
print!("{}", formatted);
}
} else if line.contains("Status:") || line.contains("Conclusion:") {
let formatted = format!(" {}\n", line.trim());
filtered.push_str(&formatted);
print!("{}", formatted);
}
}
timer.track(
&format!("gh run view {}", run_id),
&format!("rtk gh run view {}", run_id),
&raw,
&filtered,
);
Ok(())
}
fn run_repo(args: &[String], _verbose: u8, _ultra_compact: bool) -> Result<()> {
// Parse subcommand (default to "view")
let (subcommand, rest_args) = if args.is_empty() {
("view", args)
} else {
(args[0].as_str(), &args[1..])
};
if subcommand != "view" {
return run_passthrough("gh", "repo", args);
}
let timer = tracking::TimedExecution::start();
let mut cmd = Command::new("gh");
cmd.arg("repo").arg("view");
for arg in rest_args {
cmd.arg(arg);
}
cmd.args([
"--json",
"name,owner,description,url,stargazerCount,forkCount,isPrivate",
]);
let output = cmd.output().context("Failed to run gh repo view")?;
let raw = String::from_utf8_lossy(&output.stdout).to_string();
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
timer.track("gh repo view", "rtk gh repo view", &stderr, &stderr);
eprintln!("{}", stderr.trim());
std::process::exit(output.status.code().unwrap_or(1));
}
let json: Value =
serde_json::from_slice(&output.stdout).context("Failed to parse gh repo view output")?;
let name = json["name"].as_str().unwrap_or("???");
let owner = json["owner"]["login"].as_str().unwrap_or("???");
let description = json["description"].as_str().unwrap_or("");
let url = json["url"].as_str().unwrap_or("");
let stars = json["stargazerCount"].as_i64().unwrap_or(0);
let forks = json["forkCount"].as_i64().unwrap_or(0);
let private = json["isPrivate"].as_bool().unwrap_or(false);
let visibility = if private {
"🔒 Private"
} else {
"🌐 Public"
};
let mut filtered = String::new();
let line = format!("📦 {}/{}\n", owner, name);
filtered.push_str(&line);
print!("{}", line);
let line = format!(" {}\n", visibility);
filtered.push_str(&line);
print!("{}", line);
if !description.is_empty() {
let line = format!(" {}\n", truncate(description, 80));
filtered.push_str(&line);
print!("{}", line);
}
let line = format!(" ⭐ {} stars | 🔱 {} forks\n", stars, forks);
filtered.push_str(&line);
print!("{}", line);
let line = format!(" {}\n", url);
filtered.push_str(&line);
print!("{}", line);
timer.track("gh repo view", "rtk gh repo view", &raw, &filtered);
Ok(())
}
fn pr_create(args: &[String], _verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
let mut cmd = Command::new("gh");
cmd.args(["pr", "create"]);
for arg in args {
cmd.arg(arg);
}
let output = cmd.output().context("Failed to run gh pr create")?;
let stdout = String::from_utf8_lossy(&output.stdout).to_string();
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
if !output.status.success() {
timer.track("gh pr create", "rtk gh pr create", &stderr, &stderr);
eprintln!("{}", stderr.trim());
std::process::exit(output.status.code().unwrap_or(1));
}
// gh pr create outputs the URL on success
let url = stdout.trim();
// Try to extract PR number from URL (e.g., https://github.com/owner/repo/pull/42)
let pr_num = url.rsplit('/').next().unwrap_or("");
let detail = if !pr_num.is_empty() && pr_num.chars().all(|c| c.is_ascii_digit()) {
format!("#{} {}", pr_num, url)
} else {
url.to_string()
};
let filtered = ok_confirmation("created", &detail);
println!("{}", filtered);
timer.track("gh pr create", "rtk gh pr create", &stdout, &filtered);
Ok(())
}
fn pr_merge(args: &[String], _verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
let mut cmd = Command::new("gh");
cmd.args(["pr", "merge"]);
for arg in args {
cmd.arg(arg);
}
let output = cmd.output().context("Failed to run gh pr merge")?;
let stdout = String::from_utf8_lossy(&output.stdout).to_string();