@sigit / si Mirror · read-only
Fork 0

Mirror of github.com/getsigit/si.

Mirrored from https://github.com/getsigit/si.git

Synced Nov 24, 09:30 UTC

1 //! Human-readable renderers. Each is the `--json` counterpart of one command's
2 //! output; see [`crate::ui::emit`].
3
4 use {
5 super::{bold, dim, highlight, relative_time, state_badge},
6 console::style,
7 sigit_si_api::models::{
8 AgentRun, Billing, CloudSession, CodeHit, CombinedStatus, Comment, Hook, Issue,
9 IssueSummary, Model, PullRequest, PullRequestSummary, Repository, RepositorySummary, Site,
10 User,
11 },
12 tabled::{builder::Builder, settings::Style},
13 };
14
15 /// Print a table, or a placeholder line when there is nothing to show.
16 fn table(headers: &[&str], rows: Vec<Vec<String>>, empty: &str) {
17 if rows.is_empty() {
18 println!("{}", dim(empty));
19 return;
20 }
21
22 let mut builder = Builder::default();
23 builder.push_record(headers.iter().map(|h| h.to_string()));
24 for row in rows {
25 builder.push_record(row);
26 }
27
28 let mut table = builder.build();
29 table.with(Style::rounded());
30 println!("{table}");
31 }
32
33 /// A `label value` line, skipped when the value is empty.
34 fn field(label: &str, value: Option<&str>) {
35 if let Some(value) = value.map(str::trim).filter(|v| !v.is_empty()) {
36 println!(" {:<14}{}", label, value);
37 }
38 }
39
40 fn truncate(text: &str, max: usize) -> String {
41 let text = text.replace(['\n', '\r'], " ");
42 if text.chars().count() <= max {
43 return text;
44 }
45 let kept: String = text.chars().take(max.saturating_sub(1)).collect();
46 format!("{kept}…")
47 }
48
49 // ── Account ─────────────────────────────────────────────────────────────────
50
51 pub fn user(user: &User) {
52 println!();
53 println!(" {}", highlight(&user.username));
54 field("Name", user.display_name.as_deref());
55 field("Email", Some(&user.email));
56 field("ID", Some(&user.id.to_string()));
57 field(
58 "Joined",
59 Some(&user.created_at.format("%Y-%m-%d").to_string()),
60 );
61 println!();
62 }
63
64 // ── Repositories ────────────────────────────────────────────────────────────
65
66 pub fn repos(repos: &[Repository]) {
67 let rows = repos
68 .iter()
69 .map(|repo| {
70 vec![
71 repo.full_name.clone(),
72 repo.visibility().to_string(),
73 truncate(repo.description.as_deref().unwrap_or("—"), 48),
74 repo.stars_count.to_string(),
75 relative_time(repo.updated_at),
76 ]
77 })
78 .collect();
79
80 table(
81 &[
82 "Repository",
83 "Visibility",
84 "Description",
85 "Stars",
86 "Updated",
87 ],
88 rows,
89 "You have no repositories yet. Create one with `si repo create <name>`.",
90 );
91 }
92
93 pub fn repo_summaries(repos: &[RepositorySummary]) {
94 let rows = repos
95 .iter()
96 .map(|repo| {
97 vec![
98 repo.full_name.clone(),
99 if repo.private { "private" } else { "public" }.to_string(),
100 truncate(repo.description.as_deref().unwrap_or("—"), 56),
101 repo.default_branch.clone(),
102 ]
103 })
104 .collect();
105
106 table(
107 &["Repository", "Visibility", "Description", "Branch"],
108 rows,
109 "No repositories matched.",
110 );
111 }
112
113 pub fn repo_detail(repo: &Repository) {
114 println!();
115 println!(
116 " {} {}",
117 highlight(&repo.full_name),
118 dim(repo.visibility())
119 );
120 if let Some(description) = repo.description.as_deref().filter(|d| !d.is_empty()) {
121 println!(" {description}");
122 }
123 println!();
124 field("Default branch", Some(&repo.default_branch));
125 field("Stars", Some(&repo.stars_count.to_string()));
126 field(
127 "State",
128 Some(if repo.initialized {
129 "initialized"
130 } else {
131 "empty — push something to get started"
132 }),
133 );
134 field("Updated", Some(&relative_time(repo.updated_at)));
135 field("Clone", Some(&repo.clone_url));
136 field("Web", Some(&repo.web_url));
137 println!();
138 }
139
140 // ── Pull requests ───────────────────────────────────────────────────────────
141
142 pub fn pulls(pulls: &[PullRequestSummary]) {
143 let rows = pulls
144 .iter()
145 .map(|pr| {
146 vec![
147 format!("#{}", pr.number),
148 truncate(&pr.title, 52),
149 state_badge(&pr.state),
150 format!("{} → {}", pr.head, pr.base),
151 ]
152 })
153 .collect();
154
155 table(
156 &["#", "Title", "State", "Branch"],
157 rows,
158 "No pull requests match this filter.",
159 );
160 }
161
162 pub fn pull_detail(pr: &PullRequest) {
163 println!();
164 println!(" {}", bold(&pr.title));
165 println!(
166 " {} · {} · {} wants to merge {} into {}",
167 dim(&format!("#{}", pr.number)),
168 state_badge(&pr.state),
169 pr.author,
170 highlight(&pr.head),
171 highlight(&pr.base),
172 );
173 println!();
174
175 if let Some(body) = pr.body.as_deref().filter(|b| !b.trim().is_empty()) {
176 println!("{body}");
177 println!();
178 }
179
180 comments(&pr.comments);
181
182 if let Some(note) = &pr.diff_note {
183 println!(" {}", dim(note));
184 }
185 let changed = pr.diff.as_deref().map_or(0, count_changed_files);
186 if changed > 0 {
187 println!(
188 " {}",
189 dim(&format!(
190 "{changed} changed file(s) — see them with `si pr diff {}`",
191 pr.number
192 ))
193 );
194 }
195 println!(" {}", dim(&pr.url));
196 println!();
197 }
198
199 /// Count `diff --git` headers, which is one per changed file.
200 fn count_changed_files(diff: &str) -> usize {
201 diff.lines()
202 .filter(|l| l.starts_with("diff --git "))
203 .count()
204 }
205
206 // ── Issues ──────────────────────────────────────────────────────────────────
207
208 pub fn issues(issues: &[IssueSummary]) {
209 let rows = issues
210 .iter()
211 .map(|issue| {
212 vec![
213 format!("#{}", issue.number),
214 truncate(&issue.title, 60),
215 state_badge(&issue.state),
216 issue.author.clone(),
217 ]
218 })
219 .collect();
220
221 table(
222 &["#", "Title", "State", "Author"],
223 rows,
224 "No issues match this filter.",
225 );
226 }
227
228 pub fn issue_detail(issue: &Issue) {
229 println!();
230 println!(" {}", bold(&issue.title));
231 println!(
232 " {} · {} · opened by {}",
233 dim(&format!("#{}", issue.number)),
234 state_badge(&issue.state),
235 issue.author
236 );
237 println!();
238
239 if let Some(body) = issue.body.as_deref().filter(|b| !b.trim().is_empty()) {
240 println!("{body}");
241 println!();
242 }
243
244 comments(&issue.comments);
245 println!(" {}", dim(&issue.url));
246 println!();
247 }
248
249 pub fn comments(comments: &[Comment]) {
250 for comment in comments {
251 println!(
252 " {} {}",
253 highlight(&comment.author),
254 dim(&relative_time(comment.created_at))
255 );
256 for line in comment.body.lines() {
257 println!(" {line}");
258 }
259 println!();
260 }
261 }
262
263 // ── Code search ─────────────────────────────────────────────────────────────
264
265 pub fn code_hits(hits: &[CodeHit]) {
266 if hits.is_empty() {
267 println!("{}", dim("No matches."));
268 return;
269 }
270
271 for hit in hits {
272 println!(
273 "{}{}{}",
274 highlight(&hit.path),
275 dim(":"),
276 dim(&hit.line.to_string())
277 );
278 println!(" {}", hit.snippet.trim_end());
279 }
280 }
281
282 // ── Webhooks ────────────────────────────────────────────────────────────────
283
284 pub fn hooks(hooks: &[Hook]) {
285 let rows = hooks
286 .iter()
287 .map(|hook| {
288 vec![
289 hook.id.to_string(),
290 truncate(&hook.url, 52),
291 hook.events.join(", "),
292 if hook.active { "active" } else { "paused" }.to_string(),
293 hook.last_delivered_at
294 .map(relative_time)
295 .unwrap_or_else(|| "never".to_string()),
296 ]
297 })
298 .collect();
299
300 table(
301 &["ID", "URL", "Events", "State", "Last delivery"],
302 rows,
303 "This repository has no webhooks.",
304 );
305 }
306
307 // ── Cloud Sessions ──────────────────────────────────────────────────────────
308
309 pub fn sessions(sessions: &[CloudSession]) {
310 let rows = sessions
311 .iter()
312 .map(|session| {
313 vec![
314 session.id.to_string(),
315 truncate(session.title.as_deref().unwrap_or("(untitled)"), 48),
316 session.model.clone().unwrap_or_else(|| "—".to_string()),
317 session
318 .last_message_at
319 .map(relative_time)
320 .unwrap_or_else(|| "—".to_string()),
321 ]
322 })
323 .collect();
324
325 table(
326 &["ID", "Title", "Model", "Last message"],
327 rows,
328 "You have no cloud sessions yet. Start one with `si session new`.",
329 );
330 }
331
332 pub fn session_detail(session: &CloudSession) {
333 println!();
334 println!(
335 " {}",
336 highlight(session.title.as_deref().unwrap_or("(untitled session)"))
337 );
338 field("ID", Some(&session.id.to_string()));
339 field("Model", session.model.as_deref());
340 field("Created", Some(&relative_time(session.created_at)));
341 println!();
342
343 let Some(messages) = &session.messages else {
344 return;
345 };
346 if messages.is_empty() {
347 println!("{}", dim(" No messages yet."));
348 println!();
349 return;
350 }
351
352 for message in messages {
353 println!(
354 " {} {}",
355 highlight(&message.role),
356 dim(&relative_time(message.created_at))
357 );
358 for line in message.content.lines() {
359 println!(" {line}");
360 }
361 println!();
362 }
363 }
364
365 // ── Commit statuses ─────────────────────────────────────────────────────────
366
367 fn status_badge(state: &str) -> String {
368 match state {
369 "success" => style("success").green().to_string(),
370 "failure" | "error" => style(state).red().to_string(),
371 "pending" => style("pending").yellow().to_string(),
372 other => style(other).dim().to_string(),
373 }
374 }
375
376 pub fn combined_status(combined: &CombinedStatus) {
377 println!();
378 println!(
379 " {} {}",
380 highlight(&combined.sha[..combined.sha.len().min(12)]),
381 status_badge(&combined.state)
382 );
383 println!();
384
385 let rows = combined
386 .statuses
387 .iter()
388 .map(|status| {
389 vec![
390 status.context.clone(),
391 status_badge(&status.state),
392 truncate(status.description.as_deref().unwrap_or("—"), 48),
393 relative_time(status.updated_at),
394 ]
395 })
396 .collect();
397
398 table(
399 &["Check", "State", "Description", "Updated"],
400 rows,
401 "No statuses have been reported on this commit.",
402 );
403 }
404
405 // ── Agent runs ──────────────────────────────────────────────────────────────
406
407 fn run_badge(status: &str) -> String {
408 match status {
409 "succeeded" | "completed" => style(status).green().to_string(),
410 "failed" | "errored" | "timed_out" => style(status).red().to_string(),
411 "running" | "queued" | "pending" => style(status).yellow().to_string(),
412 other => style(other).dim().to_string(),
413 }
414 }
415
416 pub fn agent_runs(runs: &[AgentRun]) {
417 let rows = runs
418 .iter()
419 .map(|run| {
420 vec![
421 run.id.to_string(),
422 truncate(run.title.as_deref().unwrap_or("(untitled)"), 40),
423 run.repo_full_name.clone(),
424 run_badge(&run.status),
425 relative_time(run.created_at),
426 ]
427 })
428 .collect();
429
430 table(
431 &["ID", "Title", "Repository", "Status", "Started"],
432 rows,
433 "You have no agent runs yet. Start one with `si run start`.",
434 );
435 }
436
437 pub fn agent_run_detail(run: &AgentRun) {
438 println!();
439 println!(
440 " {} {}",
441 highlight(run.title.as_deref().unwrap_or("(untitled run)")),
442 run_badge(&run.status)
443 );
444 field("ID", Some(&run.id.to_string()));
445 field("Repository", Some(&run.repo_full_name));
446 field("Triggered by", Some(&run.trigger_kind));
447 field("Base", run.base_branch.as_deref());
448 field("Branch", run.head_branch.as_deref());
449 field("Pull request", run.pull_request_url.as_deref());
450 field("Exit reason", run.exit_reason.as_deref());
451 field("Requests", Some(&run.inference_requests_used.to_string()));
452 if run.cancel_requested {
453 field("Cancel", Some("requested"));
454 }
455 field("Created", Some(&relative_time(run.created_at)));
456 field("Finished", run.finished_at.map(relative_time).as_deref());
457 println!();
458
459 if let Some(tail) = run
460 .transcript_tail
461 .as_deref()
462 .filter(|t| !t.trim().is_empty())
463 {
464 println!(" {}", dim("Transcript (end)"));
465 for line in tail.lines() {
466 println!(" {line}");
467 }
468 println!();
469 }
470 }
471
472 // ── Sites ───────────────────────────────────────────────────────────────────
473
474 pub fn site(site: &Site) {
475 let state = match site.state.as_str() {
476 "live" => style("live").green().to_string(),
477 "failed" => style("failed").red().to_string(),
478 "publishing" => style("publishing").yellow().to_string(),
479 other => style(other).dim().to_string(),
480 };
481 println!();
482 println!(" {} {}", highlight(&site.url), state);
483 field("Error", site.error.as_deref());
484 field(
485 "Published",
486 site.last_published_at.map(relative_time).as_deref(),
487 );
488 if site.files > 0 {
489 field(
490 "Size",
491 Some(&format!("{} files, {} bytes", site.files, site.bytes)),
492 );
493 }
494 println!();
495 }
496
497 // ── Models ──────────────────────────────────────────────────────────────────
498
499 pub fn models(models: &[Model]) {
500 let rows = models
501 .iter()
502 .map(|model| {
503 vec![
504 model.id.clone(),
505 model
506 .display_name
507 .clone()
508 .unwrap_or_else(|| "—".to_string()),
509 model.capability.clone().unwrap_or_else(|| "—".to_string()),
510 if model.vision { "yes" } else { "no" }.to_string(),
511 if model.default { "default" } else { "" }.to_string(),
512 ]
513 })
514 .collect();
515
516 table(
517 &["Model", "Name", "Capability", "Vision", ""],
518 rows,
519 "No models are available right now.",
520 );
521 }
522
523 // ── Billing ─────────────────────────────────────────────────────────────────
524
525 pub fn billing(billing: &Billing) {
526 println!();
527 println!(" {} {}", highlight(&billing.plan), dim(&billing.status));
528 field(
529 "Cloud",
530 Some(if billing.entitled_to_cloud {
531 "entitled"
532 } else {
533 "not included on this plan"
534 }),
535 );
536 field(
537 "Usage",
538 Some(&format!(
539 "{} / {} requests",
540 billing.cloud_requests_used, billing.cloud_allowance
541 )),
542 );
543 if let Some(period_end) = billing.current_period_end {
544 field("Renews", Some(&period_end.format("%Y-%m-%d").to_string()));
545 }
546 println!();
547 }
548
549 #[cfg(test)]
550 mod tests {
551 use super::*;
552
553 #[test]
554 fn long_text_is_truncated_with_an_ellipsis() {
555 assert_eq!(truncate("abcdefghij", 5), "abcd…");
556 assert_eq!(truncate("abc", 5), "abc");
557 }
558
559 #[test]
560 fn newlines_are_flattened_so_a_row_stays_one_line() {
561 assert_eq!(truncate("a\nb", 10), "a b");
562 }
563
564 #[test]
565 fn changed_files_are_counted_from_diff_headers() {
566 let diff = "diff --git a/x b/x\n@@ -1 +1 @@\n-a\n+b\ndiff --git a/y b/y\n";
567 assert_eq!(count_changed_files(diff), 2);
568 assert_eq!(count_changed_files(""), 0);
569 }
570 }