Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Extract `render_data_table` helper for structured table construction (#1819)
Maximilian Roosec6f6f24c146
diff --git a/src/commands/config/state.rs b/src/commands/config/state.rsindex 5518d38d6..cf4910f4e 100644--- a/src/commands/config/state.rs+++ b/src/commands/config/state.rs@@ -94,31 +94,35 @@ fn render_log_table(out: &mut String, entries: &mut [std::fs::DirEntry]) -> std:.then_with(|| a.file_name().cmp(&b.file_name()))});- let mut table = String::from("| File | Size | Age |\n");- table.push_str("|------|------|-----|\n");-- for entry in entries.iter() {- let path = entry.path();- let name = path.file_name().unwrap_or_default().to_string_lossy();- let meta = entry.metadata().ok();-- let size = meta.as_ref().map(|m| m.len()).unwrap_or(0);- let size_str = if size < 1024 {- format!("{size}B")- } else {- format!("{}K", size / 1024)- };+ let rows: Vec<Vec<String>> = entries+ .iter()+ .map(|entry| {+ let path = entry.path();+ let name = path+ .file_name()+ .unwrap_or_default()+ .to_string_lossy()+ .to_string();+ let meta = entry.metadata().ok();++ let size = meta.as_ref().map(|m| m.len()).unwrap_or(0);+ let size_str = if size < 1024 {+ format!("{size}B")+ } else {+ format!("{}K", size / 1024)+ };- let age = meta- .and_then(|m| m.modified().ok())- .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())- .map(|d| format_relative_time_short(d.as_secs() as i64))- .unwrap_or_else(|| "?".to_string());+ let age = meta+ .and_then(|m| m.modified().ok())+ .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())+ .map(|d| format_relative_time_short(d.as_secs() as i64))+ .unwrap_or_else(|| "?".to_string());- table.push_str(&format!("| {name} | {size_str} | {age} |\n"));- }+ vec![name, size_str, age]+ })+ .collect();- let rendered = crate::md_help::render_markdown_table(&table);+ let rendered = crate::md_help::render_data_table(&["File", "Size", "Age"], &rows);write!(out, "{}", rendered.trim_end())?;Ok(())@@ -779,16 +783,14 @@ fn handle_state_show_table(repo: &Repository) -> anyhow::Result<()> {if markers.is_empty() {writeln!(out, "{}", format_with_gutter("(none)", None))?;} else {- let mut table = String::from("| Branch | Marker | Age |\n");- table.push_str("|--------|--------|-----|\n");- for entry in markers {- let age = format_relative_time_short(entry.set_at as i64);- table.push_str(&format!(- "| {} | {} | {} |\n",- entry.branch, entry.marker, age- ));- }- let rendered = crate::md_help::render_markdown_table(&table);+ let rows: Vec<Vec<String>> = markers+ .iter()+ .map(|entry| {+ let age = format_relative_time_short(entry.set_at as i64);+ vec![entry.branch.clone(), entry.marker.clone(), age]+ })+ .collect();+ let rendered = crate::md_help::render_data_table(&["Branch", "Marker", "Age"], &rows);writeln!(out, "{}", rendered.trim_end())?;}writeln!(out)?;@@ -830,24 +832,23 @@ fn handle_state_show_table(repo: &Repository) -> anyhow::Result<()> {if entries.is_empty() {writeln!(out, "{}", format_with_gutter("(none)", None))?;} else {- // Build markdown table- let mut table = String::from("| Branch | Status | Age | Head |\n");- table.push_str("|--------|--------|-----|------|\n");- for (branch, cached) in entries {- let status = match &cached.status {- Some(pr_status) => {- let status: &'static str = pr_status.ci_status.into();- status.to_string()- }- None => "none".to_string(),- };- let age = format_relative_time_short(cached.checked_at as i64);- let head: String = cached.head.chars().take(8).collect();-- table.push_str(&format!("| {branch} | {status} | {age} | {head} |\n"));- }-- let rendered = crate::md_help::render_markdown_table(&table);+ let rows: Vec<Vec<String>> = entries+ .iter()+ .map(|(branch, cached)| {+ let status = match &cached.status {+ Some(pr_status) => {+ let s: &'static str = pr_status.ci_status.into();+ s.to_string()+ }+ None => "none".to_string(),+ };+ let age = format_relative_time_short(cached.checked_at as i64);+ let head: String = cached.head.chars().take(8).collect();+ vec![branch.clone(), status, age, head]+ })+ .collect();+ let rendered =+ crate::md_help::render_data_table(&["Branch", "Status", "Age", "Head"], &rows);writeln!(out, "{}", rendered.trim_end())?;}writeln!(out)?;diff --git a/src/md_help.rs b/src/md_help.rsindex ed6fbcb89..61626024b 100644--- a/src/md_help.rs+++ b/src/md_help.rs@@ -184,12 +184,22 @@ fn render_table(lines: &[&str], max_width: Option<usize>) -> String {render_table_with_termimad(lines, "", max_width)}-/// Render a markdown table from markdown source string (no indent)-pub(crate) fn render_markdown_table(markdown: &str) -> String {- let lines: Vec<&str> = markdown- .lines()- .filter(|l| l.trim().starts_with('|') && l.trim().ends_with('|'))+/// Render a table from headers and rows using termimad.+///+/// Column widths are computed by termimad based on content.+pub(crate) fn render_data_table(headers: &[&str], rows: &[Vec<String>]) -> String {+ let header_line = format!("| {} |", headers.join(" | "));+ let separator = format!("|{}|", vec!["---"; headers.len()].join("|"));+ let row_lines: Vec<String> = rows+ .iter()+ .map(|row| format!("| {} |", row.join(" | "))).collect();++ let mut lines: Vec<&str> = Vec::with_capacity(rows.len() + 2);+ lines.push(&header_line);+ lines.push(&separator);+ lines.extend(row_lines.iter().map(|s| s.as_str()));+render_table_with_termimad(&lines, "", None)}@@ -608,33 +618,30 @@ mod tests {}// ============================================================================- // render_markdown_table+ // render_data_table// ============================================================================#[test]- fn test_render_markdown_table_basic() {- let result = render_markdown_table("| Col1 | Col2 |\n| ---- | ---- |\n| A | B |");+ fn test_render_data_table_basic() {+ let rows = vec![+ vec!["Alice".into(), "42".into()],+ vec!["Bob".into(), "7".into()],+ ];+ let result = render_data_table(&["Name", "Score"], &rows);assert_snapshot!(result, @"- Col1 Col2- ──── ────- A B+ Name Score+ ───── ─────+ Alice 42+ Bob 7");}#[test]- fn test_render_markdown_table_empty() {- let result = render_markdown_table("");- assert!(result.is_empty());- }-- #[test]- fn test_render_markdown_table_with_non_table_lines() {- let result =- render_markdown_table("Not a table\n| A | B |\nAlso not\n| - | - |\n| 1 | 2 |");+ fn test_render_data_table_empty_rows() {+ let result = render_data_table(&["A", "B"], &[]);assert_snapshot!(result, @"A B- ─── ───- 1 2+ ─── ───");}