Skip to content

Comments

feat: [#849] Add table support to the console context#1380

Merged
krishankumar01 merged 9 commits intomasterfrom
kkumar-gcc/#849
Feb 24, 2026
Merged

feat: [#849] Add table support to the console context#1380
krishankumar01 merged 9 commits intomasterfrom
kkumar-gcc/#849

Conversation

@krishankumar01
Copy link
Member

@krishankumar01 krishankumar01 commented Feb 22, 2026

📑 Description

Closes goravel/goravel#849

This PR adds a Table method to render data in a tabular format. The function accepts headers and rows, along with an optional third parameter, console.TableOption, to configure the table style.

Example

func (r *TestCommand) Handle(ctx console.Context) error {
	headers := []string{"LANGUAGE", "FORMAL", "INFORMAL"}
	rows := [][]string{
		{"Chinese", "您好", "你好"},
		{"Japanese", "こんにちは", "やあ"},
		{"Hindi", "नमस्ते", "नमस्ते"},
		{"Russian", "Здравствуйте", "Привет"},
		{"Spanish", "Hola", "¿Qué tal?"},
	}

	ctx.Table(headers, rows)
	return nil
}

TableOption

type TableOption struct {
	// BorderTop enables/disables the very top horizontal line.
	BorderTop *bool
	// BorderBottom enables/disables the very bottom horizontal line.
	BorderBottom *bool
	// BorderLeft enables/disables the leftmost vertical line.
	BorderLeft *bool
	// BorderRight enables/disables the rightmost vertical line.
	BorderRight *bool
	// BorderHeader enables/disables the separator line between the header and the first row.
	BorderHeader *bool
	// BorderColumn enables/disables vertical lines between columns.
	BorderColumn *bool
	// BorderRow enables/disables horizontal lines between every data row.
	BorderRow *bool

	// Border allows setting a custom lipgloss.Border (e.g., lipgloss.DoubleBorder()).
	Border lipgloss.Border
	// BorderStyle sets the color and style for the grid lines.
	BorderStyle lipgloss.Style
	// ColumnStyles allows specific styling for individual columns (key is column index).
	// Useful for right-aligning numbers: map[int]lipgloss.Style{1: lipgloss.NewStyle().Align(lipgloss.Right)}
	ColumnStyles map[int]lipgloss.Style
	// StyleFunc is an escape hatch for advanced cell-by-cell styling based on content or position.
	StyleFunc table.StyleFunc

	// Width sets a fixed total width for the table. Columns will auto-scale to fit.
	Width int
	// Height sets a fixed total height for the table.
	Height int
}

ScreenShot

image

✅ Checks

  • Added test cases for my code

Summary by CodeRabbit

Release Notes

  • New Features

    • Added customizable table rendering for CLI output with support for borders, styling, and sizing options
    • Introduced brand and muted color constants for consistent theming across CLI displays
    • Tables now support configurable border styles, cell formatting, and visual customization
  • Tests

    • Added test suite validating table rendering with default and custom styling configurations

@krishankumar01 krishankumar01 requested a review from a team as a code owner February 22, 2026 13:13
@codecov
Copy link

codecov bot commented Feb 22, 2026

Codecov Report

❌ Patch coverage is 57.95455% with 37 lines in your changes missing coverage. Please review.
✅ Project coverage is 68.79%. Comparing base (0373561) to head (b41fe32).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
console/cli_context.go 49.27% 23 Missing and 12 partials ⚠️
console/progress_bar.go 0.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1380      +/-   ##
==========================================
- Coverage   68.80%   68.79%   -0.02%     
==========================================
  Files         286      287       +1     
  Lines       18040    18118      +78     
==========================================
+ Hits        12413    12464      +51     
- Misses       5101     5116      +15     
- Partials      526      538      +12     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@hwbrzzl
Copy link
Contributor

hwbrzzl commented Feb 22, 2026

@coderabbitai review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 22, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 22, 2026

📝 Walkthrough

Walkthrough

This pull request adds a comprehensive table rendering feature to the console context, introducing a new Table method on CliContext that supports configurable styling, borders, and formatting using the lipgloss/table library, along with corresponding interface contracts and mock implementations.

Changes

Cohort / File(s) Summary
Core Table Implementation
console/cli_context.go
Added public color constants (BrandColor, MutedColor), default table styling options (DefaultTableHeaderColor, DefaultTableBorderColor, DefaultTableHeaderStyle, DefaultTableCellStyle, DefaultTableStyleFunc, DefaultTableOption), and new Table method that renders tables with customizable borders, styles, and dimensions. Updated spinner styling to use BrandColor.
Table Interface Contract
contracts/console/command.go
Extended Context interface with Table method signature and introduced TableOption struct with configuration fields for borders (Top, Bottom, Left, Right, Header, Column, Row), border styling, column styles, style functions, and dimensions.
Test Coverage
console/cli_context_test.go
Added TestTable test suite validating table rendering with default styling, borderless variants, and custom StyleFunc configurations.
Mock Implementation
mocks/console/Context.go
Added mock support for the Table method including Context_Table_Call wrapper struct and Context_Expecter helper with Run, Return, and RunAndReturn methods for test expectations.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant CliContext
    participant TableRenderer as lipgloss/table
    participant Output
    
    Client->>CliContext: Table(headers, rows, options...)
    CliContext->>CliContext: Merge user options with defaults
    CliContext->>TableRenderer: Create table with headers and rows
    CliContext->>TableRenderer: Apply border configuration
    CliContext->>TableRenderer: Apply styling (BorderStyle, StyleFunc)
    CliContext->>TableRenderer: Set dimensions (Width, Height)
    TableRenderer->>TableRenderer: Render formatted table
    CliContext->>Output: Write rendered table via Line()
    Output->>Client: Display formatted table
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 A table blooms in CLI's domain,
With borders neat and colors plain,
BrandColor bright and styles so fine,
Our console renders in design!
Rows and headers dance in place,
Terminal tables find their grace! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically identifies the main feature: adding table support to the console context, with reference to issue #849.
Linked Issues check ✅ Passed The PR fully implements the feature requested in issue #849: adds a Table method to cli_context that renders formatted tables with configurable options.
Out of Scope Changes check ✅ Passed All changes directly support the core objective: Table method implementation, contract/interface updates, test coverage, and mock updates—no unrelated modifications detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch kkumar-gcc/#849

Tip

Issue Planner is now in beta. Read the docs and try it out! Share your feedback on Discord.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
contracts/console/command.go (1)

7-8: Public contract leaks lipgloss types, coupling consumers to a specific rendering library.

TableOption exposes lipgloss.Border, lipgloss.Style, table.StyleFunc, and map[int]lipgloss.Style directly. Since contracts/console/command.go is the public interface that downstream consumers (and mocks) depend on, this forces every consumer to import lipgloss and lipgloss/table, even if they never render a table.

If the rendering library is ever swapped, this becomes a breaking change to the contract. Consider wrapping these types behind framework-owned abstractions or moving the lipgloss-specific types to the implementation layer. That said, this is a design trade-off — the direct exposure does provide maximum flexibility for users wanting to style tables.

Also applies to: 256-286

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@contracts/console/command.go` around lines 7 - 8, The public contract
currently leaks lipgloss types via TableOption (exposing lipgloss.Border,
lipgloss.Style, table.StyleFunc and map[int]lipgloss.Style) — remove direct
references to lipgloss/table from contracts/console/command.go by introducing
framework-level abstraction types (e.g., ConsoleBorder, ConsoleStyle,
ConsoleTableStyleFunc or simple interfaces) and use those in the TableOption API
and any other exposed signatures (including the region noted at lines ~256-286);
move the actual lipgloss/table imports and conversions into the implementation
package that builds renderers so consumers and mocks depend only on the new
lightweight abstractions rather than lipgloss types.
console/cli_context.go (1)

23-54: Shared *bool pointers between DefaultTableOption and local copies.

opt := DefaultTableOption (Line 597) performs a shallow struct copy, so the *bool fields (e.g., BorderTop) in both opt and DefaultTableOption point to the same underlying bool. Currently safe because the code only reassigns pointers (never mutates *opt.BorderTop), but a future refactor could accidentally corrupt the global default.

Consider either documenting this invariant or doing a deep copy of the pointer fields when cloning.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@console/cli_context.go` around lines 23 - 54, DefaultTableOption currently
holds several *bool pointer fields (BorderTop, BorderBottom, BorderLeft,
BorderRight, BorderHeader, BorderColumn, BorderRow) created with
convert.Pointer(...) which means shallow copies like opt := DefaultTableOption
will share underlying bools; add a proper deep-clone so callers don't
accidentally share mutable pointers: implement a CloneTableOption (or a Clone
method on console.TableOption) that copies the struct and allocates new bools
for each pointer field (copying their values) and update callers that do opt :=
DefaultTableOption to call the clone helper (e.g., opt :=
DefaultTableOption.Clone()) so each copy has independent *bool instances.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@console/cli_context.go`:
- Around line 594-675: The Table method in CliContext ignores
TableOption.ColumnStyles so per-column styles are never applied; update the
option-merging block in CliContext.Table to copy userOpt.ColumnStyles into
opt.ColumnStyles, and then replace or wrap the final StyleFunc (opt.StyleFunc /
DefaultTableStyleFunc) with a wrapper that consults opt.ColumnStyles for the
current column and falls back to the base StyleFunc (i.e., create a new
StyleFunc that takes (col, row, cell) -> if opt.ColumnStyles[col] != nil use
that style(cell) else call base StyleFunc), and set t.StyleFunc to this wrapped
function before calling r.Line(t.Render()). Ensure you reference
TableOption.ColumnStyles, CliContext.Table, opt.StyleFunc,
DefaultTableStyleFunc, and t.StyleFunc when making the change.

---

Nitpick comments:
In `@console/cli_context.go`:
- Around line 23-54: DefaultTableOption currently holds several *bool pointer
fields (BorderTop, BorderBottom, BorderLeft, BorderRight, BorderHeader,
BorderColumn, BorderRow) created with convert.Pointer(...) which means shallow
copies like opt := DefaultTableOption will share underlying bools; add a proper
deep-clone so callers don't accidentally share mutable pointers: implement a
CloneTableOption (or a Clone method on console.TableOption) that copies the
struct and allocates new bools for each pointer field (copying their values) and
update callers that do opt := DefaultTableOption to call the clone helper (e.g.,
opt := DefaultTableOption.Clone()) so each copy has independent *bool instances.

In `@contracts/console/command.go`:
- Around line 7-8: The public contract currently leaks lipgloss types via
TableOption (exposing lipgloss.Border, lipgloss.Style, table.StyleFunc and
map[int]lipgloss.Style) — remove direct references to lipgloss/table from
contracts/console/command.go by introducing framework-level abstraction types
(e.g., ConsoleBorder, ConsoleStyle, ConsoleTableStyleFunc or simple interfaces)
and use those in the TableOption API and any other exposed signatures (including
the region noted at lines ~256-286); move the actual lipgloss/table imports and
conversions into the implementation package that builds renderers so consumers
and mocks depend only on the new lightweight abstractions rather than lipgloss
types.

hwbrzzl
hwbrzzl previously approved these changes Feb 23, 2026
Copy link
Contributor

@hwbrzzl hwbrzzl left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pretty good 👍

Comment on lines 23 to 55
var (
BrandColor = lipgloss.CompleteColor{TrueColor: "#3D8C8D", ANSI256: "30", ANSI: "6"}
MutedColor = lipgloss.CompleteColor{TrueColor: "#4a4a4a", ANSI256: "240", ANSI: "8"}

DefaultTableHeaderColor = BrandColor
DefaultTableBorderColor = MutedColor

DefaultTableHeaderStyle = lipgloss.NewStyle().Foreground(DefaultTableHeaderColor).Bold(true).Padding(0, 1)
DefaultTableCellStyle = lipgloss.NewStyle().Padding(0, 1)

DefaultTableStyleFunc = func(row, col int) lipgloss.Style {
if row == table.HeaderRow {
return DefaultTableHeaderStyle
}
return DefaultTableCellStyle
}

DefaultTableOption = console.TableOption{
Border: lipgloss.RoundedBorder(),

BorderStyle: lipgloss.NewStyle().Foreground(DefaultTableBorderColor),

StyleFunc: DefaultTableStyleFunc,

BorderTop: convert.Pointer(true),
BorderBottom: convert.Pointer(true),
BorderLeft: convert.Pointer(true),
BorderRight: convert.Pointer(true),
BorderHeader: convert.Pointer(true),
BorderColumn: convert.Pointer(true),
BorderRow: convert.Pointer(false),
}
)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it better to move these code to an independent file?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sure

}

err := input.Value(&answer).Run()
err := input.Value(&answer).WithTheme(GlobalHuhTheme).Run()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add a screenshot for the theme?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

image image image image

Copy link
Contributor

@hwbrzzl hwbrzzl left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great 👍

@krishankumar01 krishankumar01 merged commit f028efa into master Feb 24, 2026
16 of 18 checks passed
@krishankumar01 krishankumar01 deleted the kkumar-gcc/#849 branch February 24, 2026 09:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add table support to the console context

2 participants