Debian Codegraph @

MIGRATION.md

raw
1 # Migration Guide: tablewriter v0.0.5 to v1.0.x
2 > **NOTE:** This document is work in progress, use with `caution`. This document is a comprehensive guide. For specific issues or advanced scenarios, please refer to the source code or open an issue.
3
4 The `tablewriter` library has undergone a significant redesign between versions **v0.0.5** and **v1.0.x**, transitioning from a primarily method-driven API to a more robust, modular, and configuration-driven framework. This guide provides a detailed roadmap for migrating your v0.0.5 codebase to v1.0.x. It includes mappings of old methods to new approaches, practical examples, and explanations of new features.
5
6 We believe these changes significantly improve the library's flexibility, maintainability, and power, enabling new features and making complex table configurations more manageable.
7
8 ## Why Migrate to v1.0.x?
9
10 The v1.0.x redesign enhances `tablewriter`’s flexibility, maintainability, and feature set:
11 - **Extensibility**: Decoupled rendering supports diverse output formats (e.g., HTML, Markdown, CSV).
12 - **Robust Configuration**: Centralized `Config` struct and fluent builders ensure atomic, predictable setups.
13 - **Streaming Capability**: Dedicated API for row-by-row rendering, ideal for large or real-time datasets.
14 - **Type Safety**: Specific types (e.g., `tw.State`, `tw.Align`) reduce errors and improve clarity.
15 - **Consistent API**: Unified interface for intuitive usage across simple and complex use cases.
16 - **New Features**: Hierarchical merging, granular padding, table captions, and fixed column widths.
17
18 These improvements make v1.0.x more powerful, but they require updating code to leverage the new configuration-driven framework and take advantage of advanced functionalities.
19
20 ## Key New Features in v1.0.x
21
22 - **Fluent Configuration Builders**: `NewConfigBuilder()` enables chained, readable setups (`config.go:NewConfigBuilder`).
23 - **Centralized Configuration**: `Config` struct governs table behavior and data processing (`config.go:Config`).
24 - **Decoupled Renderer**: `tw.Renderer` interface with `tw.Rendition` for visual styling, allowing custom renderers (`tw/renderer.go`).
25 - **True Streaming Support**: `Start()`, `Append()`, `Close()` for incremental rendering (`stream.go`).
26 - **Hierarchical Cell Merging**: `tw.MergeHierarchical` for complex data structures (`tw/tw.go:MergeMode` constant, logic in `zoo.go`).
27 - **Granular Padding Control**: Per-side (`Top`, `Bottom`, `Left`, `Right`) and per-column padding (`tw/cell.go:CellPadding`, `tw/types.go:Padding`).
28 - **Enhanced Type System**: `tw.State`, `tw.Align`, `tw.Spot`, and others for clarity and safety (`tw/state.go`, `tw/types.go`).
29 - **Comprehensive Error Handling**: Methods like `Render()` and `Append()` return errors (`tablewriter.go`, `stream.go`).
30 - **Fixed Column Width System**: `Config.Widths` for precise column sizing, especially in streaming (`config.go:Config`, `tw/cell.go:CellWidth`).
31 - **Table Captioning**: Flexible placement and styling with `tw.Caption` (`tw/types.go:Caption`).
32 - **Advanced Data Processing**: Support for `tw.Formatter`, per-column filters, and stringer caching (`tw/cell.go:CellFilter`, `tablewriter.go:WithStringer`).
33
34 ## Core Philosophy Changes in v1.0.x
35
36 Understanding these shifts is essential for a successful migration:
37
38 1. **Configuration-Driven Approach**:
39 - **Old**: Relied on `table.SetXxx()` methods for incremental, stateful modifications to table properties.
40 - **New**: Table behavior is defined by a `tablewriter.Config` struct (`config.go:Config`), while visual styling is managed by a `tw.Rendition` struct (`tw/renderer.go:Rendition`). These are typically set at table creation using `NewTable()` with `Option` functions or via a fluent `ConfigBuilder`, ensuring atomic and predictable configuration changes.
41
42 2. **Decoupled Rendering Engine**:
43 - **Old**: Rendering logic was tightly integrated into the `Table` struct, limiting output flexibility.
44 - **New**: The `tw.Renderer` interface (`tw/renderer.go:Renderer`) defines rendering logic, with `renderer.NewBlueprint()` as the default text-based renderer. The renderer’s appearance (e.g., borders, symbols) is controlled by `tw.Rendition`, enabling support for alternative formats like HTML or Markdown.
45
46 3. **Unified Section Configuration**:
47 - **Old**: Headers, rows, and footers had separate, inconsistent configuration methods.
48 - **New**: `tw.CellConfig` (`tw/cell.go:CellConfig`) standardizes configuration across headers, rows, and footers, encompassing formatting (`tw.CellFormatting`), padding (`tw.CellPadding`), column widths (`tw.CellWidth`), alignments (`tw.CellAlignment`), and filters (`tw.CellFilter`).
49
50 4. **Fluent Configuration Builders**:
51 - **Old**: Configuration was done via individual setters, often requiring multiple method calls.
52 - **New**: `tablewriter.NewConfigBuilder()` (`config.go:NewConfigBuilder`) provides a chained, fluent API for constructing `Config` objects, with nested builders for `Header()`, `Row()`, `Footer()`, `Alignment()`, `Behavior()`, and `ForColumn()` to simplify complex setups.
53
54 5. **Explicit Streaming Mode**:
55 - **Old**: No dedicated streaming support; tables were rendered in batch mode.
56 - **New**: Streaming for row-by-row rendering is enabled via `Config.Stream.Enable` or `WithStreaming(tw.StreamConfig{Enable: true})` and managed with `Table.Start()`, `Table.Append()` (or `Table.Header()`, `Table.Footer()`), and `Table.Close()` (`stream.go`). This is ideal for large datasets or continuous output.
57
58 6. **Enhanced Error Handling**:
59 - **Old**: Methods like `Render()` did not return errors, making error detection difficult.
60 - **New**: Key methods (`Render()`, `Start()`, `Close()`, `Append()`, `Bulk()`) return errors to promote robust error handling and improve application reliability (`tablewriter.go`, `stream.go`).
61
62 7. **Richer Type System & `tw` Package**:
63 - **Old**: Used integer constants (e.g., `ALIGN_CENTER`) and booleans, leading to potential errors.
64 - **New**: The `tw` sub-package introduces type-safe constructs like `tw.State` (`tw/state.go`), `tw.Align` (`tw/types.go`), `tw.Position` (`tw/types.go`), and `tw.CellConfig` (`tw/cell.go`), replacing magic constants and enhancing code clarity.
65
66 ## Configuration Methods in v1.0.x
67
68 v1.0.x offers four flexible methods to configure tables, catering to different use cases and complexity levels. Each method can be used independently or combined, providing versatility for both simple and advanced setups.
69
70 1. **Using `WithConfig` Option**:
71 - **Description**: Pass a fully populated `tablewriter.Config` struct during `NewTable` initialization using the `WithConfig` option.
72 - **Use Case**: Ideal for predefined, reusable configurations that can be serialized or shared across multiple tables.
73 - **Pros**: Explicit, portable, and suitable for complex setups; allows complete control over all configuration aspects.
74 - **Cons**: Verbose for simple changes, requiring manual struct population.
75 - **Example**:
76
77 ```go
78 package main
79
80 import (
81 "github.com/olekukonko/tablewriter"
82 "github.com/olekukonko/tablewriter/tw"
83 "os"
84 )
85
86 func main() {
87 cfg := tablewriter.Config{
88 Header: tw.CellConfig{
89 Alignment: tw.CellAlignment{Global: tw.AlignCenter},
90 Formatting: tw.CellFormatting{AutoFormat: tw.On},
91 },
92 Row: tw.CellConfig{
93 Alignment: tw.CellAlignment{Global: tw.AlignLeft},
94 },
95 MaxWidth: 80,
96 Behavior: tw.Behavior{TrimSpace: tw.On},
97 }
98 table := tablewriter.NewTable(os.Stdout, tablewriter.WithConfig(cfg))
99 table.Header("Name", "Status")
100 table.Append("Node1", "Ready")
101 table.Render()
102 }
103 ```
104 **Output**:
105 ```
106 ┌───────┬────────┐
107 │ NAME │ STATUS │
108 ├───────┼────────┤
109 │ Node1 │ Ready │
110 └───────┴────────┘
111 ```
112
113 2. **Using `Table.Configure` method**:
114 - **Description**: After creating a `Table` instance, use the `Configure` method with a function that modifies the table's `Config` struct.
115 - **Use Case**: Suitable for quick, ad-hoc tweaks post-initialization, especially for simple or dynamic adjustments.
116 - **Pros**: Straightforward for minor changes; no need for additional structs or builders if you already have a `Table` instance.
117 - **Cons**: Less readable for complex configurations compared to a builder; modifications are applied to an existing instance.
118 - **Example**:
119 ```go
120 package main
121
122 import (
123 "github.com/olekukonko/tablewriter"
124 "github.com/olekukonko/tablewriter/tw"
125 "os"
126 )
127
128 func main() {
129 table := tablewriter.NewTable(os.Stdout)
130 table.Configure(func(cfg *tablewriter.Config) {
131 cfg.Header.Alignment.Global = tw.AlignCenter
132 cfg.Row.Alignment.Global = tw.AlignLeft
133 })
134
135 table.Header("Name", "Status")
136 table.Append("Node1", "Ready")
137 table.Render()
138 }
139 ```
140 **Output**: Same as above.
141
142 3. **Standalone `Option` Functions**:
143 - **Description**: Use `WithXxx` functions (e.g., `WithHeaderAlignment`, `WithDebug`) during `NewTable` initialization or via `table.Options()` to apply targeted settings.
144 - **Use Case**: Best for simple, specific configuration changes without needing a full `Config` struct.
145 - **Pros**: Concise, readable, and intuitive for common settings; ideal for minimal setups.
146 - **Cons**: Limited for complex, multi-faceted configurations; requires multiple options for extensive changes.
147 - **Example**:
148 ```go
149 package main
150
151 import (
152 "github.com/olekukonko/tablewriter"
153 "github.com/olekukonko/tablewriter/tw"
154 "os"
155 )
156
157 func main() {
158 table := tablewriter.NewTable(os.Stdout,
159 tablewriter.WithHeaderAlignment(tw.AlignCenter),
160 tablewriter.WithRowAlignment(tw.AlignLeft),
161 tablewriter.WithDebug(true),
162 )
163 table.Header("Name", "Status")
164 table.Append("Node1", "Ready")
165 table.Render()
166 }
167 ```
168 **Output**: Same as above.
169
170 4. **Fluent `ConfigBuilder`**:
171 - **Description**: Use `tablewriter.NewConfigBuilder()` to construct a `Config` struct through a chained, fluent API, then apply it with `WithConfig(builder.Build())`.
172 - **Use Case**: Optimal for complex, dynamic, or programmatically generated configurations requiring fine-grained control.
173 - **Pros**: Highly readable, maintainable, and expressive; supports nested builders for sections and columns.
174 - **Cons**: Slightly verbose; requires understanding builder methods and `Build()` call.
175 - **Example**:
176 ```go
177 package main
178
179 import (
180 "github.com/olekukonko/tablewriter"
181 "github.com/olekukonko/tablewriter/tw"
182 "os"
183 )
184
185 func main() {
186 cnfBuilder := tablewriter.NewConfigBuilder()
187 cnfBuilder.Header().Alignment().WithGlobal(tw.AlignCenter)
188 // Example of configuring a specific column (less emphasis on this for now)
189 // cnfBuilder.ForColumn(0).WithAlignment(tw.AlignLeft).Build() // Call Build() to return to ConfigBuilder
190
191 table := tablewriter.NewTable(os.Stdout, tablewriter.WithConfig(cnfBuilder.Build()))
192 table.Header("Name", "Status")
193 table.Append("Node1", "Ready")
194 table.Render()
195 }
196 ```
197 **Output**: Same as above.
198
199 **Best Practices**:
200 - Use `WithConfig` or `ConfigBuilder` for complex setups or reusable configurations.
201 - Opt for `Option` functions for simple, targeted changes.
202 - Use `Table.Configure` for direct modifications after table creation, but avoid changes during rendering.
203 - Combine methods as needed (e.g., `ConfigBuilder` for initial setup, `Option` functions for overrides).
204
205 ## Default Parameters in v1.0.x
206
207 The `defaultConfig()` function (`config.go:defaultConfig`) establishes baseline settings for new tables, ensuring predictable behavior unless overridden. Below is a detailed table of default parameters, organized by configuration section, to help you understand the starting point for table behavior and appearance.
208
209 | Section | Parameter | Default Value | Description |
210 |---------------|--------------------------|-----------------------------------|-----------------------------------------------------------------------------|
211 | **Header** | `Alignment.Global` | `tw.AlignCenter` | Centers header text globally unless overridden by `PerColumn`. |
212 | Header | `Alignment.PerColumn` | `[]tw.Align{}` | Empty; falls back to `Global` unless specified. |
213 | Header | `Formatting.AutoFormat` | `tw.On` | Applies title case (e.g., "col_one" → "COL ONE") to header content. |
214 | Header | `Formatting.AutoWrap` | `tw.WrapTruncate` | Truncates long header text with "…" based on width constraints. |
215 | Header | `Merging.Mode` | `tw.MergeNone` | Disables cell merging in headers by default. |
216 | Header | `Padding.Global` | `tw.PaddingDefault` (`" "`) | Adds one space on left and right of header cells. |
217 | Header | `Padding.PerColumn` | `[]tw.Padding{}` | Empty; falls back to `Global` unless specified. |
218 | Header | `ColMaxWidths.Global` | `0` (unlimited) | No maximum content width for header cells unless set. |
219 | Header | `ColMaxWidths.PerColumn` | `tw.NewMapper[int, int]()` | Empty map; no per-column content width limits unless specified. |
220 | Header | `Filter.Global` | `nil` | No global content transformation for header cells. |
221 | Header | `Filter.PerColumn` | `[]func(string) string{}` | No per-column content transformations unless specified. |
222 | **Row** | `Alignment.Global` | `tw.AlignLeft` | Left-aligns row text globally unless overridden by `PerColumn`. |
223 | Row | `Alignment.PerColumn` | `[]tw.Align{}` | Empty; falls back to `Global`. |
224 | Row | `Formatting.AutoFormat` | `tw.Off` | Disables auto-formatting (e.g., title case) for row content. |
225 | Row | `Formatting.AutoWrap` | `tw.WrapNormal` | Wraps long row text naturally at word boundaries based on width constraints.|
226 | Row | `Merging.Mode` | `tw.MergeNone` | Disables cell merging in rows by default. |
227 | Row | `Padding.Global` | `tw.PaddingDefault` (`" "`) | Adds one space on left and right of row cells. |
228 | Row | `Padding.PerColumn` | `[]tw.Padding{}` | Empty; falls back to `Global`. |
229 | Row | `ColMaxWidths.Global` | `0` (unlimited) | No maximum content width for row cells. |
230 | Row | `ColMaxWidths.PerColumn` | `tw.NewMapper[int, int]()` | Empty map; no per-column content width limits. |
231 | Row | `Filter.Global` | `nil` | No global content transformation for row cells. |
232 | Row | `Filter.PerColumn` | `[]func(string) string{}` | No per-column content transformations. |
233 | **Footer** | `Alignment.Global` | `tw.AlignRight` | Right-aligns footer text globally unless overridden by `PerColumn`. |
234 | Footer | `Alignment.PerColumn` | `[]tw.Align{}` | Empty; falls back to `Global`. |
235 | Footer | `Formatting.AutoFormat` | `tw.Off` | Disables auto-formatting for footer content. |
236 | Footer | `Formatting.AutoWrap` | `tw.WrapNormal` | Wraps long footer text naturally. |
237 | Footer | `Formatting.MergeMode` | `tw.MergeNone` | Disables cell merging in footers. |
238 | Footer | `Padding.Global` | `tw.PaddingDefault` (`" "`) | Adds one space on left and right of footer cells. |
239 | Footer | `Padding.PerColumn` | `[]tw.Padding{}` | Empty; falls back to `Global`. |
240 | Footer | `ColMaxWidths.Global` | `0` (unlimited) | No maximum content width for footer cells. |
241 | Footer | `ColMaxWidths.PerColumn` | `tw.NewMapper[int, int]()` | Empty map; no per-column content width limits. |
242 | Footer | `Filter.Global` | `nil` | No global content transformation for footer cells. |
243 | Footer | `Filter.PerColumn` | `[]func(string) string{}` | No per-column content transformations. |
244 | **Global** | `MaxWidth` | `0` (unlimited) | No overall table width limit. |
245 | Global | `Behavior.AutoHide` | `tw.Off` | Displays empty columns (ignored in streaming). |
246 | Global | `Behavior.TrimSpace` | `tw.On` | Trims leading/trailing spaces from cell content. |
247 | Global | `Behavior.Header` | `tw.Control{Hide: tw.Off}` | Shows header if content is provided. |
248 | Global | `Behavior.Footer` | `tw.Control{Hide: tw.Off}` | Shows footer if content is provided. |
249 | Global | `Behavior.Compact` | `tw.Compact{Merge: tw.Off}` | No compact width optimization for merged cells. |
250 | Global | `Debug` | `false` | Disables debug logging. |
251 | Global | `Stream.Enable` | `false` | Disables streaming mode by default. |
252 | Global | `Widths.Global` | `0` (unlimited) | No fixed column width unless specified. |
253 | Global | `Widths.PerColumn` | `tw.NewMapper[int, int]()` | Empty map; no per-column fixed widths unless specified. |
254
255 **Notes**:
256 - Defaults can be overridden using any configuration method.
257 - `tw.PaddingDefault` is `{Left: " ", Right: " "}` (`tw/preset.go`).
258 - Alignment within `tw.CellFormatting` is deprecated; `tw.CellAlignment` is preferred. `tw.AlignDefault` falls back to `Global` or `tw.AlignLeft` (`tw/types.go`).
259 - Streaming mode uses `Widths` for fixed column sizing (`stream.go`).
260
261 ## Renderer Types and Customization
262
263 v1.0.x introduces a flexible rendering system via the `tw.Renderer` interface (`tw/renderer.go:Renderer`), allowing for both default text-based rendering and custom output formats. This decouples rendering logic from table data processing, enabling support for diverse formats like HTML, CSV, or JSON.
264
265 ### Default Renderer: `renderer.NewBlueprint`
266 - **Description**: `renderer.NewBlueprint()` creates a text-based renderer. Its visual styles are configured using `tw.Rendition`.
267 - **Use Case**: Standard terminal or text output with configurable borders, symbols, and separators.
268 - **Configuration**: Styled via `tw.Rendition`, which controls:
269 - `Borders`: Outer table borders (`tw.Border`) with `tw.State` for each side (`tw/renderer.go`).
270 - `Settings`: Internal lines (`tw.Lines`) and separators (`tw.Separators`) (`tw/renderer.go`).
271 - `Symbols`: Characters for drawing table lines and junctions (`tw.Symbols`) (`tw/symbols.go`).
272 - **Example**:
273 ```go
274 package main
275
276 import (
277 "github.com/olekukonko/tablewriter"
278 "github.com/olekukonko/tablewriter/renderer" // Import the renderer package
279 "github.com/olekukonko/tablewriter/tw"
280 "os"
281 )
282
283 func main() {
284 table := tablewriter.NewTable(os.Stdout,
285 tablewriter.WithRenderer(renderer.NewBlueprint()), // Default Blueprint renderer
286 tablewriter.WithRendition(tw.Rendition{ // Apply custom rendition
287 Symbols: tw.NewSymbols(tw.StyleRounded),
288 Borders: tw.Border{Top: tw.On, Bottom: tw.On, Left: tw.On, Right: tw.On},
289 Settings: tw.Settings{
290 Separators: tw.Separators{BetweenRows: tw.On},
291 Lines: tw.Lines{ShowHeaderLine: tw.On},
292 },
293 }),
294 )
295 table.Header("Name", "Status")
296 table.Append("Node1", "Ready")
297 table.Render()
298 }
299 ```
300 **Output**:
301 ```
302 ╭───────┬────────╮
303 │ Name │ Status │
304 ├───────┼────────┤
305 │ Node1 │ Ready │
306 ╰───────┴────────╯
307 ```
308
309 ### Custom Renderer Implementation
310 - **Description**: Implement the `tw.Renderer` interface to create custom output formats (e.g., HTML, CSV).
311 - **Use Case**: Non-text outputs, specialized formatting, or integration with other systems.
312 - **Interface Methods**:
313 - `Start(w io.Writer) error`: Initializes rendering.
314 - `Header(headers [][]string, ctx tw.Formatting)`: Renders header rows.
315 - `Row(row []string, ctx tw.Formatting)`: Renders a data row.
316 - `Footer(footers [][]string, ctx tw.Formatting)`: Renders footer rows.
317 - `Line(ctx tw.Formatting)`: Renders separator lines.
318 - `Close() error`: Finalizes rendering.
319 - `Config() tw.Rendition`: Returns renderer's current rendition configuration.
320 - `Logger(logger *ll.Logger)`: Sets logger for debugging.
321 - **Example (HTML Renderer)**:
322
323 ```go
324 package main
325
326 import (
327 "fmt"
328 "github.com/olekukonko/ll" // For logger type
329 "github.com/olekukonko/tablewriter"
330 "github.com/olekukonko/tablewriter/tw"
331 "io"
332 "os"
333 )
334
335 // BasicHTMLRenderer implements tw.Renderer
336 type BasicHTMLRenderer struct {
337 writer io.Writer
338 config tw.Rendition // Store the rendition
339 logger *ll.Logger
340 err error
341 }
342
343 func (r *BasicHTMLRenderer) Start(w io.Writer) error {
344 r.writer = w
345 _, r.err = r.writer.Write([]byte("<table border='1'>\n"))
346 return r.err
347 }
348
349 // Header expects [][]string for potentially multi-line headers
350 func (r *BasicHTMLRenderer) Header(headers [][]string, ctx tw.Formatting) {
351 if r.err != nil { return }
352 _, r.err = r.writer.Write([]byte(" <tr>\n"))
353 if r.err != nil { return }
354 // Iterate over cells from the context for the current line
355 for _, cellCtx := range ctx.Row.Current {
356 content := fmt.Sprintf(" <th>%s</th>\n", cellCtx.Data)
357 _, r.err = r.writer.Write([]byte(content))
358 if r.err != nil { return }
359 }
360 _, r.err = r.writer.Write([]byte(" </tr>\n"))
361 }
362
363 // Row expects []string for a single line row, but uses ctx for actual data
364 func (r *BasicHTMLRenderer) Row(row []string, ctx tw.Formatting) { // row param is less relevant here, ctx.Row.Current is key
365 if r.err != nil { return }
366 _, r.err = r.writer.Write([]byte(" <tr>\n"))
367 if r.err != nil { return }
368 for _, cellCtx := range ctx.Row.Current {
369 content := fmt.Sprintf(" <td>%s</td>\n", cellCtx.Data)
370 _, r.err = r.writer.Write([]byte(content))
371 if r.err != nil { return }
372 }
373 _, r.err = r.writer.Write([]byte(" </tr>\n"))
374 }
375
376 func (r *BasicHTMLRenderer) Footer(footers [][]string, ctx tw.Formatting) {
377 if r.err != nil { return }
378 // Similar to Header/Row, using ctx.Row.Current for the footer line data
379 // The footers [][]string param might be used if the renderer needs multi-line footer logic
380 r.Row(nil, ctx) // Reusing Row logic, passing nil for the direct row []string as ctx contains the data
381 }
382
383 func (r *BasicHTMLRenderer) Line(ctx tw.Formatting) { /* No lines in basic HTML */ }
384
385 func (r *BasicHTMLRenderer) Close() error {
386 if r.err != nil {
387 return r.err
388 }
389 _, r.err = r.writer.Write([]byte("</table>\n"))
390 return r.err
391 }
392
393 func (r *BasicHTMLRenderer) Config() tw.Rendition { return r.config }
394 func (r *BasicHTMLRenderer) Logger(logger *ll.Logger) { r.logger = logger }
395
396 func main() {
397 table := tablewriter.NewTable(os.Stdout, tablewriter.WithRenderer(&BasicHTMLRenderer{
398 config: tw.Rendition{Symbols: tw.NewSymbols(tw.StyleASCII)}, // Provide a default Rendition
399 }))
400 table.Header("Name", "Status")
401 table.Append("Node1", "Ready")
402 table.Render()
403 }
404 ```
405 **Output**:
406 ```html
407 <table border='1'>
408 <tr>
409 <th>NAME</th>
410 <th>STATUS</th>
411 </tr>
412 <tr>
413 <td>Node1</td>
414 <td>Ready</td>
415 </tr>
416 </table>
417 ```
418
419
420 #### Custom Invoice Renderer
421
422 ```go
423
424 package main
425
426 import (
427 "fmt"
428 "io"
429 "os"
430 "strings"
431
432 "github.com/olekukonko/ll"
433 "github.com/olekukonko/tablewriter"
434 "github.com/olekukonko/tablewriter/tw"
435 )
436
437 // InvoiceRenderer implements tw.Renderer for a basic invoice style.
438 type InvoiceRenderer struct {
439 writer io.Writer
440 logger *ll.Logger
441 rendition tw.Rendition
442 }
443
444 func NewInvoiceRenderer() *InvoiceRenderer {
445 rendition := tw.Rendition{
446 Borders: tw.BorderNone,
447 Symbols: tw.NewSymbols(tw.StyleNone),
448 Settings: tw.Settings{Separators: tw.SeparatorsNone, Lines: tw.LinesNone},
449 Streaming: false,
450 }
451 defaultLogger := ll.New("simple-invoice-renderer").Disable()
452 return &InvoiceRenderer{logger: defaultLogger, rendition: rendition}
453 }
454
455 func (r *InvoiceRenderer) Logger(logger *ll.Logger) {
456 if logger != nil {
457 r.logger = logger
458 }
459 }
460
461 func (r *InvoiceRenderer) Config() tw.Rendition {
462 return r.rendition
463 }
464
465 func (r *InvoiceRenderer) Start(w io.Writer) error {
466 r.writer = w
467 r.logger.Debug("InvoiceRenderer: Start")
468 return nil
469 }
470
471 func (r *InvoiceRenderer) formatLine(cells []string, widths tw.Mapper[int, int], cellContexts map[int]tw.CellContext) string {
472 var sb strings.Builder
473 numCols := 0
474 if widths != nil { // Ensure widths is not nil before calling Len
475 numCols = widths.Len()
476 }
477
478 for i := 0; i < numCols; i++ {
479 data := ""
480 if i < len(cells) {
481 data = cells[i]
482 }
483
484 width := 0
485 if widths != nil { // Check again before Get
486 width = widths.Get(i)
487 }
488
489 align := tw.AlignDefault
490 if cellContexts != nil { // Check cellContexts
491 if ctx, ok := cellContexts[i]; ok {
492 align = ctx.Align
493 }
494 }
495
496 paddedCell := tw.Pad(data, " ", width, align)
497 sb.WriteString(paddedCell)
498
499 if i < numCols-1 {
500 sb.WriteString(" ") // Column separator
501 }
502 }
503 return sb.String()
504 }
505
506 func (r *InvoiceRenderer) Header(headers [][]string, ctx tw.Formatting) {
507 if r.writer == nil {
508 return
509 }
510 r.logger.Debugf("InvoiceRenderer: Header (lines: %d)", len(headers))
511
512 for _, headerLineCells := range headers {
513 lineStr := r.formatLine(headerLineCells, ctx.Row.Widths, ctx.Row.Current)
514 fmt.Fprintln(r.writer, lineStr)
515 }
516
517 if len(headers) > 0 {
518 totalWidth := 0
519 if ctx.Row.Widths != nil {
520 ctx.Row.Widths.Each(func(_ int, w int) { totalWidth += w })
521 if ctx.Row.Widths.Len() > 1 {
522 totalWidth += (ctx.Row.Widths.Len() - 1) * 3 // Separator spaces
523 }
524 }
525 if totalWidth > 0 {
526 fmt.Fprintln(r.writer, strings.Repeat("-", totalWidth))
527 }
528 }
529 }
530
531 func (r *InvoiceRenderer) Row(row []string, ctx tw.Formatting) {
532 if r.writer == nil {
533 return
534 }
535 r.logger.Debug("InvoiceRenderer: Row")
536 lineStr := r.formatLine(row, ctx.Row.Widths, ctx.Row.Current)
537 fmt.Fprintln(r.writer, lineStr)
538 }
539
540 func (r *InvoiceRenderer) Footer(footers [][]string, ctx tw.Formatting) {
541 if r.writer == nil {
542 return
543 }
544 r.logger.Debugf("InvoiceRenderer: Footer (lines: %d)", len(footers))
545
546 if len(footers) > 0 {
547 totalWidth := 0
548 if ctx.Row.Widths != nil {
549 ctx.Row.Widths.Each(func(_ int, w int) { totalWidth += w })
550 if ctx.Row.Widths.Len() > 1 {
551 totalWidth += (ctx.Row.Widths.Len() - 1) * 3
552 }
553 }
554 if totalWidth > 0 {
555 fmt.Fprintln(r.writer, strings.Repeat("-", totalWidth))
556 }
557 }
558
559 for _, footerLineCells := range footers {
560 lineStr := r.formatLine(footerLineCells, ctx.Row.Widths, ctx.Row.Current)
561 fmt.Fprintln(r.writer, lineStr)
562 }
563 }
564
565 func (r *InvoiceRenderer) Line(ctx tw.Formatting) {
566 r.logger.Debug("InvoiceRenderer: Line (no-op)")
567 // This simple renderer draws its own lines in Header/Footer.
568 }
569
570 func (r *InvoiceRenderer) Close() error {
571 r.logger.Debug("InvoiceRenderer: Close")
572 r.writer = nil
573 return nil
574 }
575
576 func main() {
577 data := [][]string{
578 {"Product A", "2", "10.00", "20.00"},
579 {"Super Long Product Name B", "1", "125.50", "125.50"},
580 {"Item C", "10", "1.99", "19.90"},
581 }
582
583 header := []string{"Description", "Qty", "Unit Price", "Total Price"}
584 footer := []string{"", "", "Subtotal:\nTax (10%):\nGRAND TOTAL:", "165.40\n16.54\n181.94"}
585 invoiceRenderer := NewInvoiceRenderer()
586
587 // Create table and set custom renderer using Options
588 table := tablewriter.NewTable(os.Stdout,
589 tablewriter.WithRenderer(invoiceRenderer),
590 tablewriter.WithAlignment([]tw.Align{
591 tw.AlignLeft, tw.AlignCenter, tw.AlignRight, tw.AlignRight,
592 }),
593 )
594
595 table.Header(header)
596 for _, v := range data {
597 table.Append(v)
598 }
599
600 // Use the Footer method with strings containing newlines for multi-line cells
601 table.Footer(footer)
602
603 fmt.Println("Rendering with InvoiceRenderer:")
604 table.Render()
605
606 // For comparison, render with default Blueprint renderer
607 // Re-create the table or reset it to use a different renderer
608 table2 := tablewriter.NewTable(os.Stdout,
609 tablewriter.WithAlignment([]tw.Align{
610 tw.AlignLeft, tw.AlignCenter, tw.AlignRight, tw.AlignRight,
611 }),
612 )
613
614 table2.Header(header)
615 for _, v := range data {
616 table2.Append(v)
617 }
618 table2.Footer(footer)
619 fmt.Println("\nRendering with Default Blueprint Renderer (for comparison):")
620 table2.Render()
621 }
622
623 ```
624
625
626 ```
627 Rendering with InvoiceRenderer:
628 DESCRIPTION QTY UNIT PRICE TOTAL PRICE
629 --------------------------------------------------------------------
630 Product A 2 10.00 20.00
631 Super Long Product Name B 1 125.50 125.50
632 Item C 10 1.99 19.90
633 --------------------------------------------------------------------
634 Subtotal: 165.40
635 --------------------------------------------------------------------
636 Tax (10%): 16.54
637 --------------------------------------------------------------------
638 GRAND TOTAL: 181.94
639 ```
640
641
642 ```
643 Rendering with Default Blueprint Renderer (for comparison):
644 ┌───────────────────────────┬─────┬──────────────┬─────────────┐
645 │ DESCRIPTION │ QTY │ UNIT PRICE │ TOTAL PRICE │
646 ├───────────────────────────┼─────┼──────────────┼─────────────┤
647 │ Product A │ 2 │ 10.00 │ 20.00 │
648 │ Super Long Product Name B │ 1 │ 125.50 │ 125.50 │
649 │ Item C │ 10 │ 1.99 │ 19.90 │
650 ├───────────────────────────┼─────┼──────────────┼─────────────┤
651 │ │ │ Subtotal: │ 165.40 │
652 │ │ │ Tax (10%): │ 16.54 │
653 │ │ │ GRAND TOTAL: │ 181.94 │
654 └───────────────────────────┴─────┴──────────────┴─────────────┘
655
656 ```
657 **Notes**:
658 - The `renderer.NewBlueprint()` is sufficient for most text-based use cases.
659 - Custom renderers require implementing all interface methods to handle table structure correctly. `tw.Formatting` (which includes `tw.RowContext`) provides cell content and metadata.
660
661 ## Function Mapping Table (v0.0.5 → v1.0.x)
662
663 The following table maps v0.0.5 methods to their v1.0.x equivalents, ensuring a quick reference for migration. All deprecated methods are retained for compatibility but should be replaced with new APIs.
664
665 | v0.0.5 Method | v1.0.x Equivalent(s) | Notes |
666 |-----------------------------------|--------------------------------------------------------------------------------------|----------------------------------------------------------------------|
667 | `NewWriter(w)` | `NewTable(w, opts...)` | `NewWriter` deprecated; wraps `NewTable` (`tablewriter.go`). |
668 | `SetHeader([]string)` | `Header(...any)` | Variadic or slice; supports any type (`tablewriter.go`). |
669 | `Append([]string)` | `Append(...any)` | Variadic, slice, or struct (`tablewriter.go`). |
670 | `AppendBulk([][]string)` | `Bulk([]any)` | Slice of rows; supports any type (`tablewriter.go`). |
671 | `SetFooter([]string)` | `Footer(...any)` | Variadic or slice; supports any type (`tablewriter.go`). |
672 | `Render()` | `Render()` (returns `error`) | Batch mode; streaming uses `Start/Close` (`tablewriter.go`). |
673 | `SetBorder(bool)` | `WithRendition(tw.Rendition{Borders: ...})` or `WithBorders(tw.Border)` (deprecated) | Use `tw.Border` (`deprecated.go`, `tw/renderer.go`). |
674 | `SetRowLine(bool)` | `WithRendition(tw.Rendition{Settings: {Separators: {BetweenRows: tw.On}}})` | `tw.Separators` (`tw/renderer.go`). |
675 | `SetHeaderLine(bool)` | `WithRendition(tw.Rendition{Settings: {Lines: {ShowHeaderLine: tw.On}}})` | `tw.Lines` (`tw/renderer.go`). |
676 | `SetColumnSeparator(string)` | `WithRendition(tw.Rendition{Symbols: ...})` or `WithSymbols(tw.Symbols)` (deprecated)| `tw.NewSymbols` or custom `tw.Symbols` (`tw/symbols.go`). |
677 | `SetCenterSeparator(string)` | `WithRendition(tw.Rendition{Symbols: ...})` or `WithSymbols(tw.Symbols)` (deprecated)| `tw.Symbols` (`tw/symbols.go`). |
678 | `SetRowSeparator(string)` | `WithRendition(tw.Rendition{Symbols: ...})` or `WithSymbols(tw.Symbols)` (deprecated)| `tw.Symbols` (`tw/symbols.go`). |
679 | `SetAlignment(int)` | `WithRowAlignment(tw.Align)` or `Config.Row.Alignment.Global` | `tw.Align` type (`config.go`). |
680 | `SetHeaderAlignment(int)` | `WithHeaderAlignment(tw.Align)` or `Config.Header.Alignment.Global` | `tw.Align` type (`config.go`). |
681 | `SetAutoFormatHeaders(bool)` | `WithHeaderAutoFormat(tw.State)` or `Config.Header.Formatting.AutoFormat` | `tw.State` (`config.go`). |
682 | `SetAutoWrapText(bool)` | `WithRowAutoWrap(int)` or `Config.Row.Formatting.AutoWrap` (uses `tw.Wrap...` const) | `tw.WrapNormal`, `tw.WrapTruncate`, etc. (`config.go`). |
683 | `SetAutoMergeCells(bool)` | `WithRowMergeMode(int)` or `Config.Row.Formatting.MergeMode` (uses `tw.Merge...` const) | Supports `Vertical`, `Hierarchical` (`config.go`). |
684 | `SetColMinWidth(col, w)` | `WithColumnWidths(tw.NewMapper[int,int]().Set(col, w))` or `Config.Widths.PerColumn` | `Config.Widths` for fixed widths (`config.go`). |
685 | `SetTablePadding(string)` | Use `Config.<Section>.Padding.Global` with `tw.Padding` | No direct equivalent; manage via cell padding (`tw/cell.go`). |
686 | `SetDebug(bool)` | `WithDebug(bool)` or `Config.Debug` | Logs via `table.Debug()` (`config.go`). |
687 | `Clear()` | `Reset()` | Clears data and state (`tablewriter.go`). |
688 | `SetNoWhiteSpace(bool)` | `WithTrimSpace(tw.Off)` (if `true`) or `WithPadding(tw.PaddingNone)` | Manage via `Config.Behavior.TrimSpace` or padding (`config.go`). |
689 | `SetColumnColor(Colors)` | Embed ANSI codes in cell data, use `tw.Formatter`, or `Config.<Section>.Filter` | Colors via data or filters (`tw/cell.go`). |
690 | `SetHeaderColor(Colors)` | Embed ANSI codes in cell data, use `tw.Formatter`, or `Config.Header.Filter` | Colors via data or filters (`tw/cell.go`). |
691 | `SetFooterColor(Colors)` | Embed ANSI codes in cell data, use `tw.Formatter`, or `Config.Footer.Filter` | Colors via data or filters (`tw/cell.go`). |
692
693 **Notes**:
694 - Deprecated methods are in `deprecated.go` but should be replaced.
695 - `tw` package types (e.g., `tw.Align`, `tw.State`) are required for new APIs.
696 - Examples for each mapping are provided in the migration steps below.
697
698 ## Detailed Migration Steps: Initialization, Data Input, Rendering
699
700 This section provides step-by-step guidance for migrating core table operations, with code examples and explanations to ensure clarity. Each step maps v0.0.5 methods to v1.0.x equivalents, highlighting changes, best practices, and potential pitfalls.
701
702 ### 1. Table Initialization
703 Initialization has shifted from `NewWriter` to `NewTable`, which supports flexible configuration via `Option` functions, `Config` structs, or `ConfigBuilder`.
704
705 **Old (v0.0.5):**
706 ```go
707 package main
708
709 import (
710 "github.com/olekukonko/tablewriter"
711 "os"
712 )
713
714 func main() {
715 table := tablewriter.NewWriter(os.Stdout)
716 // ... use table
717 _ = table // Avoid "declared but not used"
718 }
719 ```
720
721 **New (v1.0.x):**
722 ```go
723 package main
724
725 import (
726 "fmt" // Added for FormattableEntry example
727 "github.com/olekukonko/tablewriter"
728 "github.com/olekukonko/tablewriter/renderer" // Import renderer
729 "github.com/olekukonko/tablewriter/tw"
730 "os"
731 "strings" // Added for Formatter example
732 )
733
734 func main() {
735 // Minimal Setup (Default Configuration)
736 tableMinimal := tablewriter.NewTable(os.Stdout)
737 _ = tableMinimal // Avoid "declared but not used"
738
739 // Using Option Functions for Targeted Configuration
740 tableWithOptions := tablewriter.NewTable(os.Stdout,
741 tablewriter.WithHeaderAlignment(tw.AlignCenter), // Center header text
742 tablewriter.WithRowAlignment(tw.AlignLeft), // Left-align row text
743 tablewriter.WithDebug(true), // Enable debug logging
744 )
745 _ = tableWithOptions // Avoid "declared but not used"
746
747 // Using a Full Config Struct for Comprehensive Control
748 cfg := tablewriter.Config{
749 Header: tw.CellConfig{
750 Alignment: tw.CellAlignment{
751 Global: tw.AlignCenter,
752 PerColumn: []tw.Align{tw.AlignLeft, tw.AlignRight}, // Column-specific alignment
753 },
754 Formatting: tw.CellFormatting{AutoFormat: tw.On},
755 },
756 Row: tw.CellConfig{
757 Alignment: tw.CellAlignment{Global: tw.AlignLeft},
758 Formatting: tw.CellFormatting{AutoWrap: tw.WrapNormal},
759 },
760 Footer: tw.CellConfig{
761 Alignment: tw.CellAlignment{Global: tw.AlignRight},
762 },
763 MaxWidth: 80, // Constrain total table width
764 Behavior: tw.Behavior{
765 AutoHide: tw.Off, // Show empty columns
766 TrimSpace: tw.On, // Trim cell spaces
767 },
768 Widths: tw.CellWidth{
769 Global: 20, // Default fixed column width
770 PerColumn: tw.NewMapper[int, int]().Set(0, 15), // Column 0 fixed at 15
771 },
772 }
773 tableWithConfig := tablewriter.NewTable(os.Stdout, tablewriter.WithConfig(cfg))
774 _ = tableWithConfig // Avoid "declared but not used"
775
776 // Using ConfigBuilder for Fluent, Complex Configuration
777 builder := tablewriter.NewConfigBuilder().
778 WithMaxWidth(80).
779 WithAutoHide(tw.Off).
780 WithTrimSpace(tw.On).
781 WithDebug(true). // Enable debug logging
782 Header().
783 Alignment().
784 WithGlobal(tw.AlignCenter).
785 Build(). // Returns *ConfigBuilder
786 Header().
787 Formatting().
788 WithAutoFormat(tw.On).
789 WithAutoWrap(tw.WrapTruncate). // Test truncation
790 WithMergeMode(tw.MergeNone). // Explicit merge mode
791 Build(). // Returns *HeaderConfigBuilder
792 Padding().
793 WithGlobal(tw.Padding{Left: "[", Right: "]", Overwrite: true}).
794 Build(). // Returns *HeaderConfigBuilder
795 Build(). // Returns *ConfigBuilder
796 Row().
797 Formatting().
798 WithAutoFormat(tw.On). // Uppercase rows
799 Build(). // Returns *RowConfigBuilder
800 Build(). // Returns *ConfigBuilder
801 Row().
802 Alignment().
803 WithGlobal(tw.AlignLeft).
804 Build(). // Returns *ConfigBuilder
805 Build() // Finalize Config
806
807 tableWithFluent := tablewriter.NewTable(os.Stdout, tablewriter.WithConfig(builder))
808 _ = tableWithFluent // Avoid "declared but not used"
809 }
810 ```
811
812 **Key Changes**:
813 - **Deprecation**: `NewWriter` is deprecated but retained for compatibility, internally calling `NewTable` (`tablewriter.go:NewWriter`). Transition to `NewTable` for new code.
814 - **Flexibility**: `NewTable` accepts an `io.Writer` and variadic `Option` functions (`tablewriter.go:NewTable`), enabling configuration via:
815 - `WithConfig(Config)`: Applies a complete `Config` struct (`config.go:WithConfig`).
816 - `WithRenderer(tw.Renderer)`: Sets a custom renderer, defaulting to `renderer.NewBlueprint()` (`tablewriter.go:WithRenderer`).
817 - `WithRendition(tw.Rendition)`: Configures visual styles for the renderer (`tablewriter.go:WithRendition`).
818 - `WithStreaming(tw.StreamConfig)`: Enables streaming mode (`tablewriter.go:WithStreaming`).
819 - Other `WithXxx` functions for specific settings (e.g., `WithHeaderAlignment`, `WithDebug`).
820 - **ConfigBuilder**: Provides a fluent API for complex setups; `Build()` finalizes the `Config` (`config.go:ConfigBuilder`).
821 - **Method Chaining in Builder**: Remember to call `Build()` on nested builders to return to the parent builder (e.g., `builder.Header().Alignment().WithGlobal(...).Build().Formatting()...`).
822
823 **Migration Tips**:
824 - Replace `NewWriter` with `NewTable` and specify configurations explicitly.
825 - Use `ConfigBuilder` for complex setups or when readability is paramount.
826 - Apply `Option` functions for quick, targeted changes.
827 - Ensure `tw` package is imported for types like `tw.Align` and `tw.CellConfig`.
828 - Verify renderer settings if custom styling is needed, as `renderer.NewBlueprint()` is the default.
829
830 **Potential Pitfalls**:
831 - **Unintended Defaults**: Without explicit configuration, `defaultConfig()` applies (see Default Parameters), which may differ from v0.0.5 behavior (e.g., `Header.Formatting.AutoFormat = tw.On`).
832 - **Renderer Absence**: If no renderer is set, `NewTable` defaults to `renderer.NewBlueprint()`; explicitly set for custom formats.
833 - **ConfigBuilder Errors**: Always call `Build()` at the end of a builder chain and on nested builders; omitting it can lead to incomplete configurations or runtime errors.
834 - **Concurrent Modification**: Avoid modifying `Table.config` (if using the `Configure` method or direct access) in concurrent scenarios or during rendering to prevent race conditions.
835
836 ### 2. Data Input
837 Data input methods in v1.0.x are more flexible, accepting `any` type for headers, rows, and footers, with robust conversion logic to handle strings, structs, and custom types.
838
839 #### 2.1. Setting Headers
840 Headers define the table’s column labels and are typically the first data added.
841
842 **Old (v0.0.5):**
843 ```go
844 package main
845
846 import (
847 "github.com/olekukonko/tablewriter"
848 "os"
849 )
850
851 func main() {
852 table := tablewriter.NewWriter(os.Stdout)
853 table.SetHeader([]string{"Name", "Sign", "Rating"})
854 // ...
855 }
856 ```
857
858 **New (v1.0.x):**
859 ```go
860 package main
861
862 import (
863 "fmt"
864 "github.com/olekukonko/tablewriter"
865 "github.com/olekukonko/tablewriter/tw" // For tw.Formatter
866 "os"
867 "strings"
868 )
869
870 // Struct with Formatter
871 type HeaderData struct { // Renamed to avoid conflict
872 Label string
873 }
874
875 func (h HeaderData) Format() string { return strings.ToUpper(h.Label) } // Implements tw.Formatter
876
877 func main() {
878 table := tablewriter.NewTable(os.Stdout)
879
880 // Variadic Arguments (Preferred for Simplicity)
881 table.Header("Name", "Sign", "Rating")
882
883 // Slice of Strings
884 // table.Header([]string{"Name", "Sign", "Rating"}) // Example, comment out if using variadic
885
886 // Slice of Any Type (Flexible)
887 // table.Header([]any{"Name", "Sign", 123}) // Numbers converted to strings
888
889 // Using Formatter
890 // table.Header(HeaderData{"name"}, HeaderData{"sign"}, HeaderData{"rating"}) // Outputs "NAME", "SIGN", "RATING"
891
892 table.Append("Example", "Row", "Data") // Add some data to render
893 table.Render()
894 }
895 ```
896
897 **Key Changes**:
898 - **Method**: `SetHeader([]string)` replaced by `Header(...any)` (`tablewriter.go:Header`).
899 - **Flexibility**: Accepts variadic arguments or a single slice; supports any type, not just strings.
900 - **Conversion**: Elements are processed by `processVariadic` (`zoo.go:processVariadic`) and converted to strings via `convertCellsToStrings` (`zoo.go:convertCellsToStrings`), supporting:
901 - Basic types (e.g., `string`, `int`, `float64`).
902 - `fmt.Stringer` implementations.
903 - `tw.Formatter` implementations (custom string conversion).
904 - Structs (exported fields as cells or single cell if `Stringer`/`Formatter`).
905 - **Streaming**: In streaming mode, `Header()` renders immediately via `streamRenderHeader` (`stream.go:streamRenderHeader`).
906 - **Formatting**: Headers are formatted per `Config.Header` settings (e.g., `AutoFormat`, `Alignment`) during rendering (`zoo.go:prepareContent`).
907
908 **Migration Tips**:
909 - Replace `SetHeader` with `Header`, using variadic arguments for simplicity.
910 - Use slices for dynamic header lists or when passing from a variable.
911 - Implement `tw.Formatter` for custom header formatting (e.g., uppercase).
912 - Ensure header count matches expected columns to avoid width mismatches.
913 - In streaming mode, call `Header()` before rows, as it fixes column widths (`stream.go`).
914
915 **Potential Pitfalls**:
916 - **Type Mismatch**: Non-string types are converted to strings; ensure desired formatting (e.g., use `tw.Formatter` for custom types).
917 - **Streaming Widths**: Headers influence column widths in streaming; set `Config.Widths` explicitly if specific widths are needed (`stream.go:streamCalculateWidths`).
918 - **Empty Headers**: Missing headers may cause rendering issues; provide placeholders (e.g., `""`) if needed.
919 - **AutoFormat**: Default `Header.Formatting.AutoFormat = tw.On` applies title case; disable with `WithHeaderAutoFormat(tw.Off)` if unwanted (`config.go`).
920
921 #### 2.2. Appending Rows
922 Rows represent the table’s data entries, and v1.0.x enhances flexibility with support for varied input types.
923
924 **Old (v0.0.5):**
925 ```go
926 package main
927
928 import (
929 "github.com/olekukonko/tablewriter"
930 "os"
931 )
932
933 func main() {
934 table := tablewriter.NewWriter(os.Stdout)
935 table.SetHeader([]string{"ColA", "ColB", "ColC"}) // Add header for context
936 table.Append([]string{"A", "The Good", "500"})
937 table.Append([]string{"B", "The Very Bad", "288"})
938 data := [][]string{
939 {"C", "The Ugly", "120"},
940 {"D", "The Gopher", "800"},
941 }
942 table.AppendBulk(data)
943 table.Render()
944 }
945 ```
946
947 **New (v1.0.x):**
948 ```go
949 package main
950
951 import (
952 "fmt"
953 "github.com/olekukonko/tablewriter"
954 "github.com/olekukonko/tablewriter/tw" // For tw.Formatter
955 "log"
956 "os"
957 )
958
959 // Struct for examples
960 type Entry struct {
961 ID string
962 Label string
963 Score int
964 }
965
966 // Struct with Formatter
967 type FormattableEntry struct {
968 ID string
969 Label string
970 Score int
971 }
972
973 func (e FormattableEntry) Format() string { return fmt.Sprintf("%s (%d)", e.Label, e.Score) } // Implements tw.Formatter
974
975 func main() {
976 table := tablewriter.NewTable(os.Stdout)
977 table.Header("ID", "Description", "Value") // Header for context
978
979 // Variadic Arguments (Single Row)
980 table.Append("A", "The Good", 500) // Numbers converted to strings
981
982 // Slice of Any Type (Single Row)
983 table.Append([]any{"B", "The Very Bad", "288"})
984
985 // Struct with Fields
986 table.Append(Entry{ID: "C", Label: "The Ugly", Score: 120}) // Fields as cells
987
988 // Struct with Formatter (will produce a single cell for this row based on Format())
989 // To make it fit 3 columns, the formatter would need to produce a string that looks like 3 cells, or the table config would need to adapt.
990 // For this example, let's assume it's meant to be one wide cell, or adjust the header.
991 // For now, let's simplify and append it to a table with one header.
992 tableOneCol := tablewriter.NewTable(os.Stdout)
993 tableOneCol.Header("Formatted Entry")
994 tableOneCol.Append(FormattableEntry{ID: "D", Label: "The Gopher", Score: 800}) // Single cell "The Gopher (800)"
995 tableOneCol.Render()
996 fmt.Println("---")
997
998
999 // Re-initialize main table for Bulk example
1000 table = tablewriter.NewTable(os.Stdout)
1001 table.Header("ID", "Description", "Value")
1002
1003 // Multiple Rows with Bulk
1004 data := []any{
1005 []any{"E", "The Fast", 300},
1006 Entry{ID: "F", Label: "The Swift", Score: 400}, // Struct instance
1007 // FormattableEntry{ID: "G", Label: "The Bold", Score: 500}, // Would also be one cell
1008 }
1009 if err := table.Bulk(data); err != nil {
1010 log.Fatalf("Bulk append failed: %v", err)
1011 }
1012 table.Render()
1013 }
1014 ```
1015
1016 **Key Changes**:
1017 - **Method**: `Append([]string)` replaced by `Append(...any)`; `AppendBulk([][]string)` replaced by `Bulk([]any)` (`tablewriter.go`).
1018 - **Input Flexibility**: `Append` accepts:
1019 - Multiple arguments as cells of a single row.
1020 - A single slice (e.g., `[]string`, `[]any`) as cells of a single row.
1021 - A single struct, processed by `convertItemToCells` (`zoo.go`):
1022 - Uses `tw.Formatter` or `fmt.Stringer` for single-cell output.
1023 - Extracts exported fields as multiple cells otherwise.
1024 - **Bulk Input**: `Bulk` accepts a slice where each element is a row (e.g., `[][]any`, `[]Entry`), processed by `appendSingle` (`zoo.go:appendSingle`).
1025 - **Streaming**: Rows render immediately in streaming mode via `streamAppendRow` (`stream.go:streamAppendRow`).
1026 - **Error Handling**: `Append` and `Bulk` return errors for invalid conversions or streaming issues (`tablewriter.go`).
1027
1028 **Migration Tips**:
1029 - Replace `Append([]string)` with `Append(...any)` for variadic input.
1030 - Use `Bulk` for multiple rows, ensuring each element is a valid row representation.
1031 - Implement `tw.Formatter` for custom struct formatting to control cell output.
1032 - Match row cell count to headers to avoid alignment issues.
1033 - In streaming mode, append rows after `Start()` and before `Close()` (`stream.go`).
1034
1035 **Potential Pitfalls**:
1036 - **Cell Count Mismatch**: Uneven row lengths may cause rendering errors; pad with empty strings (e.g., `""`) if needed.
1037 - **Struct Conversion**: Unexported fields are ignored; ensure fields are public or use `Formatter`/`Stringer` (`zoo.go`).
1038 - **Streaming Order**: Rows must be appended after headers in streaming to maintain width consistency (`stream.go`).
1039 - **Error Ignored**: Always check `Bulk` errors, as invalid data can cause failures.
1040
1041 #### 2.3. Setting Footers
1042 Footers provide summary or closing data for the table, often aligned differently from rows.
1043
1044 **Old (v0.0.5):**
1045 ```go
1046 package main
1047
1048 import (
1049 "github.com/olekukonko/tablewriter"
1050 "os"
1051 )
1052
1053 func main() {
1054 table := tablewriter.NewWriter(os.Stdout)
1055 table.SetHeader([]string{"ColA", "ColB", "ColC", "ColD"}) // Add header for context
1056 table.SetFooter([]string{"", "", "Total", "1408"})
1057 table.Render()
1058 }
1059 ```
1060
1061 **New (v1.0.x):**
1062 ```go
1063 package main
1064
1065 import (
1066 "fmt"
1067 "github.com/olekukonko/tablewriter"
1068 "github.com/olekukonko/tablewriter/tw" // For tw.Formatter
1069 "os"
1070 )
1071
1072 // Using Formatter
1073 type FooterSummary struct { // Renamed to avoid conflict
1074 Label string
1075 Value float64
1076 }
1077
1078 func (s FooterSummary) Format() string { return fmt.Sprintf("%s: %.2f", s.Label, s.Value) } // Implements tw.Formatter
1079
1080 func main() {
1081 table := tablewriter.NewTable(os.Stdout)
1082 table.Header("ColA", "ColB", "ColC", "ColD") // Header for context
1083
1084 // Variadic Arguments
1085 table.Footer("", "", "Total", 1408)
1086
1087 // Slice of Any Type
1088 // table.Footer([]any{"", "", "Total", 1408.50})
1089
1090 table.Render() // Render this table
1091
1092 fmt.Println("--- Another Table with Formatter Footer ---")
1093 table2 := tablewriter.NewTable(os.Stdout)
1094 table2.Header("Summary Info") // Single column header
1095 // Using Formatter for a single cell footer
1096 table2.Footer(FooterSummary{Label: "Grand Total", Value: 1408.50}) // Single cell: "Grand Total: 1408.50"
1097 table2.Render()
1098 }
1099 ```
1100
1101 **Key Changes**:
1102 - **Method**: `SetFooter([]string)` replaced by `Footer(...any)` (`tablewriter.go:Footer`).
1103 - **Input Flexibility**: Like `Header`, accepts variadic arguments, slices, or structs with `Formatter`/`Stringer` support (`zoo.go:processVariadic`).
1104 - **Streaming**: Footers are buffered via `streamStoreFooter` and rendered during `Close()` (`stream.go:streamStoreFooter`, `stream.go:streamRenderFooter`).
1105 - **Formatting**: Controlled by `Config.Footer` settings (e.g., `Alignment`, `AutoWrap`) (`zoo.go:prepareTableSection`).
1106
1107 **Migration Tips**:
1108 - Replace `SetFooter` with `Footer`, preferring variadic input for simplicity.
1109 - Use `tw.Formatter` for custom footer formatting (e.g., formatted numbers).
1110 - Ensure footer cell count matches headers/rows to maintain alignment.
1111 - In streaming mode, call `Footer()` before `Close()` to include it in rendering.
1112
1113 **Potential Pitfalls**:
1114 - **Alignment Differences**: Default `Footer.Alignment.Global = tw.AlignRight` differs from rows (`tw.AlignLeft`); adjust if needed (`config.go`).
1115 - **Streaming Timing**: Footers not rendered until `Close()`; ensure `Close()` is called (`stream.go`).
1116 - **Empty Footers**: Missing footers may affect table appearance; use placeholders if needed.
1117
1118 ### 3. Rendering the Table
1119 Rendering has been overhauled to support both batch and streaming modes, with mandatory error handling for robustness.
1120
1121 **Old (v0.0.5):**
1122 ```go
1123 package main
1124
1125 import (
1126 "github.com/olekukonko/tablewriter"
1127 "os"
1128 )
1129
1130 func main() {
1131 table := tablewriter.NewWriter(os.Stdout)
1132 table.SetHeader([]string{"Data"})
1133 table.Append([]string{"Example"})
1134 table.Render()
1135 }
1136 ```
1137
1138 **New (v1.0.x) - Batch Mode:**
1139 ```go
1140 package main
1141
1142 import (
1143 "github.com/olekukonko/tablewriter"
1144 "log"
1145 "os"
1146 )
1147
1148 func main() {
1149 table := tablewriter.NewTable(os.Stdout)
1150 table.Header("Data")
1151 table.Append("Example")
1152 if err := table.Render(); err != nil {
1153 log.Fatalf("Table rendering failed: %v", err)
1154 }
1155 }
1156 ```
1157
1158 **New (v1.0.x) - Streaming Mode:**
1159 ```go
1160 package main
1161
1162 import (
1163 "fmt"
1164 "github.com/olekukonko/tablewriter"
1165 "github.com/olekukonko/tablewriter/tw"
1166 "log"
1167 "os"
1168 )
1169
1170 func main() {
1171 tableStream := tablewriter.NewTable(os.Stdout,
1172 tablewriter.WithConfig(tablewriter.Config{
1173 Stream: tw.StreamConfig{Enable: true},
1174 Widths: tw.CellWidth{
1175 Global: 12, // Fixed column width for streaming
1176 PerColumn: tw.NewMapper[int, int]().Set(0, 15), // Column 0 at 15
1177 },
1178 }),
1179 )
1180 // Alternative: Using WithStreaming Option
1181 // tableStream := tablewriter.NewTable(os.Stdout,
1182 // tablewriter.WithStreaming(tw.StreamConfig{Enable: true}),
1183 // tablewriter.WithColumnMax(12), // Sets Config.Widths.Global
1184 // )
1185
1186 if err := tableStream.Start(); err != nil {
1187 log.Fatalf("Failed to start table stream: %v", err)
1188 }
1189 tableStream.Header("Column 1", "Column 2")
1190 for i := 0; i < 3; i++ {
1191 if err := tableStream.Append(fmt.Sprintf("Data %d-1", i), fmt.Sprintf("Data %d-2", i)); err != nil {
1192 log.Printf("Failed to append row %d: %v", i, err) // Log and continue or handle differently
1193 }
1194 }
1195 tableStream.Footer("End", "Summary")
1196 if err := tableStream.Close(); err != nil {
1197 log.Fatalf("Failed to close table stream: %v", err)
1198 }
1199 }
1200 ```
1201
1202 **Key Changes**:
1203 - **Batch Mode**:
1204 - `Render()` processes all data (headers, rows, footers) in one go (`tablewriter.go:render`).
1205 - Calculates column widths dynamically based on content, `Config.Widths`, `ColMaxWidths`, and `MaxWidth` (`zoo.go:calculateAndNormalizeWidths`).
1206 - Invokes renderer methods: `Start()`, `Header()`, `Row()`, `Footer()`, `Line()`, `Close()` (`tw/renderer.go`).
1207 - Returns errors for invalid configurations or I/O issues.
1208 - **Streaming Mode**:
1209 - Enabled via `Config.Stream.Enable` or `WithStreaming(tw.StreamConfig{Enable: true})` (`tablewriter.go:WithStreaming`).
1210 - `Start()` initializes the stream, fixing column widths based on `Config.Widths` or first data (header/row) (`stream.go:streamCalculateWidths`).
1211 - `Header()`, `Append()` render immediately (`stream.go:streamRenderHeader`, `stream.go:streamAppendRow`).
1212 - `Footer()` buffers data, rendered by `Close()` (`stream.go:streamStoreFooter`, `stream.go:streamRenderFooter`).
1213 - `Close()` finalizes rendering with footer and borders (`stream.go:Close`).
1214 - All methods return errors for robust handling.
1215 - **Error Handling**: Mandatory error checks replace silent failures, improving reliability.
1216
1217 **Migration Tips**:
1218 - Replace `Render()` calls with error-checked versions in batch mode.
1219 - For streaming, adopt `Start()`, `Append()`, `Close()` workflow, ensuring `Start()` precedes data input.
1220 - Set `Config.Widths` for consistent column widths in streaming mode (`config.go`).
1221 - Use `WithRendition` to customize visual output, as renderer settings are decoupled (`tablewriter.go`).
1222 - Test rendering with small datasets to verify configuration before scaling.
1223
1224 **Potential Pitfalls**:
1225 - **Missing Error Checks**: Failing to check errors can miss rendering failures; always use `if err != nil`.
1226 - **Streaming Widths**: Widths are fixed after `Start()`; inconsistent data may cause truncation (`stream.go`).
1227 - **Renderer Misconfiguration**: Ensure `tw.Rendition` matches desired output style (`tw/renderer.go`).
1228 - **Incomplete Streaming**: Forgetting `Close()` in streaming mode omits footer and final borders (`stream.go`).
1229 - **Batch vs. Streaming**: Using `Render()` in streaming mode causes errors; use `Start()`/`Close()` instead (`tablewriter.go`).
1230
1231
1232 ## Styling and Appearance Configuration
1233
1234 Styling in v1.0.x is split between `tablewriter.Config` for data processing (e.g., alignment, padding, wrapping) and `tw.Rendition` for visual rendering (e.g., borders, symbols, lines). This section details how to migrate v0.0.5 styling methods to v1.0.x, providing examples, best practices, and migration tips to maintain or enhance table appearance.
1235
1236 ### 4.1. Table Styles
1237 Table styles define the visual structure through border and separator characters. In v0.0.5, styles were set via individual separator methods, whereas v1.0.x uses `tw.Rendition.Symbols` for a cohesive approach, offering predefined styles and custom symbol sets.
1238
1239 **Available Table Styles**:
1240 The `tw.Symbols` interface (`tw/symbols.go`) supports a variety of predefined styles, each tailored to specific use cases, as well as custom configurations for unique requirements.
1241
1242 | Style Name | Use Case | Symbols Example | Recommended Context |
1243 |----------------|-----------------------------------|-------------------------------------|-----------------------------------------|
1244 | `StyleASCII` | Simple, terminal-friendly | `+`, `-`, `|` | Basic CLI output, minimal dependencies; ensures compatibility across all terminals, including older or non-Unicode systems. |
1245 | `StyleLight` | Clean, lightweight borders | `┌`, `└`, `─`, `│` | Modern terminals, clean and professional aesthetics; suitable for most CLI applications requiring a modern look. |
1246 | `StyleHeavy` | Thick, prominent borders | `┏`, `┗`, `━`, `┃` | High-visibility reports, dashboards, or logs; emphasizes table structure for critical data presentation. |
1247 | `StyleDouble` | Double-line borders | `╔`, `╚`, `═`, `║` | Formal documents, structured data exports; visually distinct for presentations or printed outputs. |
1248 | `StyleRounded` | Rounded corners, aesthetic | `╭`, `╰`, `─`, `│` | User-friendly CLI applications, reports; enhances visual appeal with smooth, rounded edges. |
1249 | `StyleMarkdown`| Markdown-compatible | `|`, `-`, `:` | Documentation, GitHub READMEs, or Markdown-based platforms; ensures proper rendering in Markdown viewers. |
1250 *Note: `StyleBold` was mentioned but not defined in the symbols code, `StyleHeavy` is similar.*
1251
1252 **Old (v0.0.5):**
1253 ```go
1254 package main
1255
1256 import (
1257 "github.com/olekukonko/tablewriter"
1258 "os"
1259 )
1260
1261 func main() {
1262 table := tablewriter.NewWriter(os.Stdout)
1263 // table.SetCenterSeparator("*") // Example, actual v0.0.5 method might vary
1264 // table.SetColumnSeparator("!")
1265 // table.SetRowSeparator("=")
1266 // table.SetBorder(true)
1267 table.SetHeader([]string{"Header1", "Header2"})
1268 table.Append([]string{"Cell1", "Cell2"})
1269 table.Render()
1270 }
1271 ```
1272
1273 **New (v1.0.x):**
1274 ```go
1275 package main
1276
1277 import (
1278 "github.com/olekukonko/tablewriter"
1279 "github.com/olekukonko/tablewriter/renderer"
1280 "github.com/olekukonko/tablewriter/tw"
1281 "os"
1282 )
1283
1284 func main() {
1285 // Using a Predefined Style (Rounded Corners for Aesthetic Output)
1286 tableStyled := tablewriter.NewTable(os.Stdout,
1287 tablewriter.WithRenderer(renderer.NewBlueprint()), // Ensure renderer is set
1288 tablewriter.WithRendition(tw.Rendition{
1289 Symbols: tw.NewSymbols(tw.StyleRounded), // Predefined rounded style
1290 Borders: tw.Border{Top: tw.On, Bottom: tw.On, Left: tw.On, Right: tw.On},
1291 Settings: tw.Settings{
1292 Separators: tw.Separators{BetweenRows: tw.On}, // Lines between rows
1293 },
1294 }),
1295 )
1296 tableStyled.Header("Name", "Status")
1297 tableStyled.Append("Node1", "Ready")
1298 tableStyled.Render()
1299
1300 // Using Fully Custom Symbols (Mimicking v0.0.5 Custom Separators)
1301 mySymbols := tw.NewSymbolCustom("my-style"). // Fluent builder for custom symbols
1302 WithCenter("*"). // Junction of lines
1303 WithColumn("!"). // Vertical separator
1304 WithRow("="). // Horizontal separator
1305 WithTopLeft("/").
1306 WithTopMid("-").
1307 WithTopRight("\\").
1308 WithMidLeft("[").
1309 WithMidRight("]"). // Corrected from duplicate WithMidRight("+")
1310 // WithMidMid was not a method in SymbolCustom
1311 WithBottomLeft("\\").
1312 WithBottomMid("_").
1313 WithBottomRight("/").
1314 WithHeaderLeft("(").
1315 WithHeaderMid("-").
1316 WithHeaderRight(")") // Header-specific
1317 tableCustomSymbols := tablewriter.NewTable(os.Stdout,
1318 tablewriter.WithRenderer(renderer.NewBlueprint()),
1319 tablewriter.WithRendition(tw.Rendition{
1320 Symbols: mySymbols,
1321 Borders: tw.Border{Top: tw.On, Bottom: tw.On, Left: tw.On, Right: tw.On},
1322 }),
1323 )
1324 tableCustomSymbols.Header("Name", "Status")
1325 tableCustomSymbols.Append("Node1", "Ready")
1326 tableCustomSymbols.Render()
1327 }
1328 ```
1329
1330 **Output (Styled, Rounded):**
1331 ```
1332 ╭───────┬────────╮
1333 │ NAME │ STATUS │
1334 ├───────┼────────┤
1335 │ Node1 │ Ready │
1336 ╰───────┴────────╯
1337 ```
1338
1339 **Output (Custom Symbols):**
1340 ```
1341 /=======-========\
1342 ! NAME ! STATUS !
1343 [=======*========]
1344 ! Node1 ! Ready !
1345 \=======_========/
1346 ```
1347
1348 **Key Changes**:
1349 - **Deprecated Methods**: `SetCenterSeparator`, `SetColumnSeparator`, `SetRowSeparator`, and `SetBorder` are deprecated and moved to `deprecated.go`. These are replaced by `tw.Rendition.Symbols` and `tw.Rendition.Borders` for a unified styling approach (`tablewriter.go`).
1350 - **Symbol System**: The `tw.Symbols` interface defines all drawing characters used for table lines, junctions, and corners (`tw/symbols.go:Symbols`).
1351 - `tw.NewSymbols(tw.BorderStyle)` provides predefined styles (e.g., `tw.StyleASCII`, `tw.StyleMarkdown`, `tw.StyleRounded`) for common use cases. (Note: `tw.Style` should be `tw.BorderStyle`)
1352 - `tw.NewSymbolCustom(name string)` enables fully custom symbol sets via a fluent builder, allowing precise control over each character (e.g., `WithCenter`, `WithTopLeft`).
1353 - **Renderer Dependency**: Styling requires a renderer, set via `WithRenderer`; the default is `renderer.NewBlueprint()` if not specified (`tablewriter.go:WithRenderer`).
1354 - **Border Control**: `tw.Rendition.Borders` uses `tw.State` (`tw.On`, `tw.Off`) to enable or disable borders on each side (Top, Bottom, Left, Right) (`tw/renderer.go:Border`).
1355 - **Extensibility**: Custom styles can be combined with custom renderers for non-text outputs, enhancing flexibility (`tw/renderer.go`).
1356
1357 **Migration Tips**:
1358 - Replace individual separator setters (`SetCenterSeparator`, etc.) with `tw.NewSymbols` for predefined styles or `tw.NewSymbolCustom` for custom designs to maintain or enhance v0.0.5 styling.
1359 - Use `WithRendition` to apply `tw.Rendition` settings, ensuring a renderer is explicitly set to avoid default behavior (`tablewriter.go`).
1360 - Test table styles in your target environment (e.g., terminal, Markdown viewer, or log file) to ensure compatibility with fonts and display capabilities.
1361 - For Markdown-based outputs (e.g., GitHub READMEs), use `tw.StyleMarkdown` to ensure proper rendering in Markdown parsers (`tw/symbols.go`).
1362 - Combine `tw.Rendition.Symbols` with `tw.Rendition.Borders` and `tw.Rendition.Settings` to replicate or improve v0.0.5’s border and line configurations (`tw/renderer.go`).
1363 - Document custom symbol sets in code comments to aid maintenance, as they can be complex (`tw/symbols.go`).
1364
1365 **Potential Pitfalls**:
1366 - **Missing Renderer**: If `WithRenderer` is omitted, `NewTable` defaults to `renderer.NewBlueprint` with minimal styling, which may not match v0.0.5’s `SetBorder(true)` behavior; always specify for custom styles (`tablewriter.go`).
1367 - **Incomplete Custom Symbols**: When using `tw.NewSymbolCustom`, failing to set all required symbols (e.g., `TopLeft`, `Center`, `HeaderLeft`) can cause rendering errors or inconsistent visuals; ensure all necessary characters are defined (`tw/symbols.go`).
1368 - **Terminal Compatibility Issues**: Advanced styles like `StyleDouble` or `StyleHeavy` may not render correctly in older terminals or non-Unicode environments; use `StyleASCII` for maximum compatibility across platforms (`tw/symbols.go`).
1369 - **Border and Symbol Mismatch**: Inconsistent `tw.Rendition.Borders` and `tw.Symbols` settings (e.g., enabling borders but using minimal symbols) can lead to visual artifacts; test with small tables to verify alignment (`tw/renderer.go`).
1370 - **Markdown Rendering**: Non-Markdown styles (e.g., `StyleRounded`) may not render correctly in Markdown viewers; use `StyleMarkdown` for documentation or web-based outputs (`tw/symbols.go`).
1371
1372 ### 4.2. Borders and Separator Lines
1373 Borders and internal lines define the table’s structural appearance, controlling the visibility of outer edges and internal divisions. In v0.0.5, these were set via specific methods, while v1.0.x uses `tw.Rendition` fields for a more integrated approach.
1374
1375 **Old (v0.0.5):**
1376 ```go
1377 package main
1378
1379 import (
1380 "github.com/olekukonko/tablewriter"
1381 "os"
1382 )
1383
1384 func main() {
1385 table := tablewriter.NewWriter(os.Stdout)
1386 // table.SetBorder(false) // Disable all outer borders
1387 // table.SetRowLine(true) // Enable lines between data rows
1388 // table.SetHeaderLine(true) // Enable line below header
1389 table.SetHeader([]string{"Header1", "Header2"})
1390 table.Append([]string{"Cell1", "Cell2"})
1391 table.Render()
1392 }
1393 ```
1394
1395 **New (v1.0.x):**
1396 ```go
1397 package main
1398
1399 import (
1400 "github.com/olekukonko/tablewriter"
1401 "github.com/olekukonko/tablewriter/renderer"
1402 "github.com/olekukonko/tablewriter/tw"
1403 "os"
1404 )
1405
1406 func main() {
1407 // Standard Bordered Table with Internal Lines
1408 table := tablewriter.NewTable(os.Stdout,
1409 tablewriter.WithRenderer(renderer.NewBlueprint()),
1410 tablewriter.WithRendition(tw.Rendition{
1411 Borders: tw.Border{ // Outer table borders
1412 Left: tw.On,
1413 Right: tw.On,
1414 Top: tw.On,
1415 Bottom: tw.On,
1416 },
1417 Settings: tw.Settings{
1418 Lines: tw.Lines{ // Major internal separator lines
1419 ShowHeaderLine: tw.On, // Line after header
1420 ShowFooterLine: tw.On, // Line before footer (if footer exists)
1421 },
1422 Separators: tw.Separators{ // General row and column separators
1423 BetweenRows: tw.On, // Horizontal lines between data rows
1424 BetweenColumns: tw.On, // Vertical lines between columns
1425 },
1426 },
1427 }),
1428 )
1429 table.Header("Name", "Status")
1430 table.Append("Node1", "Ready")
1431 table.Render()
1432
1433 // Borderless Table (kubectl-style, No Lines or Separators)
1434 // Configure the table with a borderless, kubectl-style layout
1435 config := tablewriter.NewConfigBuilder().
1436 Header().
1437 Padding().
1438 WithGlobal(tw.PaddingNone). // No header padding
1439 Build().
1440 Alignment().
1441 WithGlobal(tw.AlignLeft). // Left-align header
1442 Build().
1443 Row().
1444 Padding().
1445 WithGlobal(tw.PaddingNone). // No row padding
1446 Build().
1447 Alignment().
1448 WithGlobal(tw.AlignLeft). // Left-align rows
1449 Build().
1450 Footer().
1451 Padding().
1452 WithGlobal(tw.PaddingNone). // No footer padding
1453 Build().
1454 Alignment().
1455 WithGlobal(tw.AlignLeft). // Left-align footer (if used)
1456 Build().
1457 WithDebug(true). // Enable debug logging
1458 Build()
1459
1460 // Create borderless table
1461 tableBorderless := tablewriter.NewTable(os.Stdout,
1462 tablewriter.WithRenderer(renderer.NewBlueprint()), // Assumes valid renderer
1463 tablewriter.WithRendition(tw.Rendition{
1464 Borders: tw.BorderNone, // No borders
1465 Symbols: tw.NewSymbols(tw.StyleNone), // No border symbols
1466 Settings: tw.Settings{
1467 Lines: tw.LinesNone, // No header/footer lines
1468 Separators: tw.SeparatorsNone, // No row/column separators
1469 },
1470 }),
1471 tablewriter.WithConfig(config),
1472 )
1473
1474 // Set headers and data
1475 tableBorderless.Header("Name", "Status")
1476 tableBorderless.Append("Node1", "Ready")
1477 tableBorderless.Render()
1478 }
1479 ```
1480
1481 **Output (Standard Bordered):**
1482 ```
1483 ┌───────┬────────┐
1484 │ Name │ Status │
1485 ├───────┼────────┤
1486 │ Node1 │ Ready │
1487 └───────┴────────┘
1488 ```
1489
1490 **Output (Borderless):**
1491 ```
1492 NAME STATUS
1493 Node1 Ready
1494 ```
1495
1496 **Key Changes**:
1497 - **Deprecated Methods**: `SetBorder`, `SetRowLine`, and `SetHeaderLine` are deprecated and moved to `deprecated.go`. These are replaced by fields in `tw.Rendition` (`tw/renderer.go`):
1498 - `Borders`: Controls outer table borders (`tw.Border`) with `tw.State` (`tw.On`, `tw.Off`) for each side (Top, Bottom, Left, Right).
1499 - `Settings.Lines`: Manages major internal lines (`ShowHeaderLine` for header, `ShowFooterLine` for footer) (`tw.Lines`).
1500 - `Settings.Separators`: Controls general separators between rows (`BetweenRows`) and columns (`BetweenColumns`) (`tw.Separators`).
1501 - **Presets for Simplicity**: `tw.BorderNone`, `tw.LinesNone`, and `tw.SeparatorsNone` provide quick configurations for minimal or borderless tables (`tw/preset.go`).
1502 - **Renderer Integration**: Border and line settings are applied via `WithRendition`, requiring a renderer to be set (`tablewriter.go:WithRendition`).
1503 - **Granular Control**: Each border side and line type can be independently configured, offering greater flexibility than v0.0.5’s boolean toggles.
1504 - **Dependency on Symbols**: The appearance of borders and lines depends on `tw.Rendition.Symbols`; ensure compatible symbol sets (`tw/symbols.go`).
1505
1506 **Migration Tips**:
1507 - Replace `SetBorder(false)` with `tw.Rendition.Borders = tw.BorderNone` to disable all outer borders (`tw/preset.go`).
1508 - Use `tw.Rendition.Settings.Separators.BetweenRows = tw.On` to replicate `SetRowLine(true)`, ensuring row separators are visible (`tw/renderer.go`).
1509 - Set `tw.Rendition.Settings.Lines.ShowHeaderLine = tw.On` to mimic `SetHeaderLine(true)` for a line below the header (`tw/renderer.go`).
1510 - For kubectl-style borderless tables, combine `tw.BorderNone`, `tw.LinesNone`, `tw.SeparatorsNone`, and `WithPadding(tw.PaddingNone)` (applied via `ConfigBuilder` or `WithConfig`) to eliminate all lines and spacing (`tw/preset.go`, `config.go`).
1511 - Test border and line configurations with small tables to verify visual consistency, especially when combining with custom `tw.Symbols`.
1512 - Use `WithDebug(true)` to log rendering details if borders or lines appear incorrectly (`config.go`).
1513
1514 **Potential Pitfalls**:
1515 - **Separator Absence**: If `tw.Rendition.Settings.Separators.BetweenColumns` is `tw.Off` and borders are disabled, columns may lack visual separation; use `tw.CellPadding` or ensure content spacing (`tw/cell.go`).
1516 - **Line and Border Conflicts**: Mismatched settings (e.g., enabling `ShowHeaderLine` but disabling `Borders.Top`) can cause uneven rendering; align `Borders`, `Lines`, and `Separators` settings (`tw/renderer.go`).
1517 - **Renderer Dependency**: Border settings require a renderer; omitting `WithRenderer` defaults to `renderer.NewBlueprint` with minimal styling, which may not match v0.0.5 expectations (`tablewriter.go`).
1518 - **Streaming Limitations**: In streaming mode, separator rendering is fixed after `Start()`; ensure `tw.Rendition` is set correctly before rendering begins (`stream.go`).
1519 - **Symbol Mismatch**: Using minimal `tw.Symbols` (e.g., `StyleASCII`) with complex `Borders` settings may lead to visual artifacts; test with matching symbol sets (`tw/symbols.go`).
1520
1521 ### 4.3. Alignment
1522 Alignment controls the positioning of text within table cells, now configurable per section (Header, Row, Footer) with both global and per-column options for greater precision.
1523
1524 **Old (v0.0.5):**
1525 ```go
1526 package main
1527
1528 import (
1529 "github.com/olekukonko/tablewriter" // Assuming ALIGN_CENTER etc. were constants here
1530 "os"
1531 )
1532
1533 const ( // Mocking v0.0.5 constants for example completeness
1534 ALIGN_CENTER = 1 // Example values
1535 ALIGN_LEFT = 2
1536 )
1537
1538
1539 func main() {
1540 table := tablewriter.NewWriter(os.Stdout)
1541 // table.SetAlignment(ALIGN_CENTER) // Applied to data rows
1542 // table.SetHeaderAlignment(ALIGN_LEFT) // Applied to header
1543 // No specific footer alignment setter
1544 table.SetHeader([]string{"Header1", "Header2"})
1545 table.Append([]string{"Cell1", "Cell2"})
1546 table.Render()
1547 }
1548 ```
1549
1550 **New (v1.0.x):**
1551 ```go
1552 package main
1553
1554 import (
1555 "github.com/olekukonko/tablewriter"
1556 "github.com/olekukonko/tablewriter/tw"
1557 "os"
1558 )
1559
1560 func main() {
1561 cfg := tablewriter.Config{
1562 Header: tw.CellConfig{
1563 Alignment: tw.CellAlignment{Global: tw.AlignLeft},
1564 },
1565 Row: tw.CellConfig{
1566 Alignment: tw.CellAlignment{
1567 Global: tw.AlignCenter,
1568 PerColumn: []tw.Align{tw.AlignLeft, tw.AlignRight}, // Col 0 left, Col 1 right
1569 },
1570 },
1571 Footer: tw.CellConfig{
1572 Alignment: tw.CellAlignment{Global: tw.AlignRight},
1573 },
1574 }
1575 table := tablewriter.NewTable(os.Stdout, tablewriter.WithConfig(cfg))
1576
1577 table.Header("Name", "Status")
1578 table.Append("Node1", "Ready")
1579 table.Footer("", "Active") // Ensure footer has content to show alignment
1580 table.Render()
1581 }
1582 ```
1583
1584 **Output:**
1585 ```
1586 ┌───────┬────────┐
1587 │ NAME │ STATUS │
1588 ├───────┼────────┤
1589 │ Node1 │ Ready │
1590 ├───────┼────────┤
1591 │ │ Active │
1592 └───────┴────────┘
1593 ```
1594
1595 **Key Changes**:
1596 - **Deprecated Methods**: `SetAlignment` and `SetHeaderAlignment` are replaced by `WithRowAlignment`, `WithHeaderAlignment`, `WithFooterAlignment`, or direct `Config` settings (`config.go`). These old methods are retained in `deprecated.go` for compatibility but should be migrated.
1597 - **Alignment Structure**: Alignment is managed within `tw.CellConfig.Alignment` (`tw/cell.go:CellAlignment`), which includes:
1598 - `Global`: A single `tw.Align` value applied to all cells in the section (`tw.AlignLeft`, `tw.AlignCenter`, `tw.AlignRight`, `tw.AlignNone`).
1599 - `PerColumn`: A slice of `tw.Align` values for column-specific alignment, overriding `Global` for specified columns.
1600 - **Footer Alignment**: v1.0.x introduces explicit footer alignment via `WithFooterAlignment` or `Config.Footer.Alignment`, addressing v0.0.5’s lack of footer-specific control (`config.go`).
1601 - **Type Safety**: `tw.Align` string constants replace v0.0.5’s integer constants (e.g., `ALIGN_CENTER`), improving clarity and reducing errors (`tw/types.go`).
1602 - **Builder Support**: `ConfigBuilder` provides `Alignment()` methods for each section. `ForColumn(idx).WithAlignment()` applies alignment to a specific column across all sections (`config.go:ConfigBuilder`, `config.go:ColumnConfigBuilder`).
1603 - **Deprecated Fields**: `tw.CellConfig.ColumnAligns` (slice) and `tw.CellFormatting.Alignment` (single value) are supported for backward compatibility but should be migrated to `tw.CellAlignment.Global` and `tw.CellAlignment.PerColumn` (`tw/cell.go`).
1604
1605 **Migration Tips**:
1606 - Replace `SetAlignment(ALIGN_X)` with `WithRowAlignment(tw.AlignX)` or `Config.Row.Alignment.Global = tw.AlignX` to set row alignment (`config.go`).
1607 - Use `WithHeaderAlignment(tw.AlignX)` for headers and `WithFooterAlignment(tw.AlignX)` for footers to maintain or adjust v0.0.5 behavior (`config.go`).
1608 - Specify per-column alignments with `ConfigBuilder.Row().Alignment().WithPerColumn([]tw.Align{...})` or by setting `Config.Row.Alignment.PerColumn` for fine-grained control (`config.go`).
1609 - Use `ConfigBuilder.ForColumn(idx).WithAlignment(tw.AlignX)` to apply consistent alignment to a specific column across all sections (Header, Row, Footer) (`config.go`).
1610 - Verify alignment settings against defaults (`Header: tw.AlignCenter`, `Row: tw.AlignLeft`, `Footer: tw.AlignRight`) to ensure expected output (`config.go:defaultConfig`).
1611 - Test alignment with varied cell content lengths to confirm readability, especially when combined with wrapping or padding settings (`zoo.go:prepareContent`).
1612
1613 **Potential Pitfalls**:
1614 - **Alignment Precedence**: `PerColumn` settings override `Global` within a section; ensure column-specific alignments are intentional (`tw/cell.go:CellAlignment`).
1615 - **Deprecated Fields**: Relying on `ColumnAligns` or `tw.CellFormatting.Alignment` is temporary; migrate to `tw.CellAlignment` to avoid future issues (`tw/cell.go`).
1616 - **Cell Count Mismatch**: Rows or footers with fewer cells than headers can cause alignment errors; pad with empty strings (`""`) to match column count (`zoo.go`).
1617 - **Streaming Width Impact**: In streaming mode, alignment depends on fixed column widths set by `Config.Widths`; narrow widths may truncate content, misaligning text (`stream.go:streamCalculateWidths`).
1618 - **Default Misalignment**: The default `Footer.Alignment.Global = tw.AlignRight` differs from rows (`tw.AlignLeft`); explicitly set `WithFooterAlignment` if consistency is needed (`config.go`).
1619
1620 ### 4.4. Auto-Formatting (Header Title Case)
1621 Auto-formatting applies transformations like title case to cell content, primarily for headers to enhance readability, but it can be enabled for rows or footers in v1.0.x.
1622
1623 **Old (v0.0.5):**
1624 ```go
1625 package main
1626
1627 import (
1628 "github.com/olekukonko/tablewriter"
1629 "os"
1630 )
1631
1632 func main() {
1633 table := tablewriter.NewWriter(os.Stdout)
1634 // table.SetAutoFormatHeaders(true) // Default: true; applies title case to headers
1635 table.SetHeader([]string{"col_one", "status_report"})
1636 table.Append([]string{"Node1", "Ready"})
1637 table.Render()
1638 }
1639 ```
1640
1641 **New (v1.0.x):**
1642 ```go
1643 package main
1644
1645 import (
1646 "github.com/olekukonko/tablewriter"
1647 "github.com/olekukonko/tablewriter/tw"
1648 "os"
1649 )
1650
1651 func main() {
1652 // Using Direct Config Struct to turn OFF default AutoFormat for Header
1653 cfg := tablewriter.Config{
1654 Header: tw.CellConfig{Formatting: tw.CellFormatting{AutoFormat: tw.Off}}, // Turn OFF title case for headers
1655 Row: tw.CellConfig{Formatting: tw.CellFormatting{AutoFormat: tw.Off}}, // No formatting for rows (default)
1656 Footer: tw.CellConfig{Formatting: tw.CellFormatting{AutoFormat: tw.Off}}, // No formatting for footers (default)
1657 }
1658 tableNoAutoFormat := tablewriter.NewTable(os.Stdout, tablewriter.WithConfig(cfg))
1659
1660 tableNoAutoFormat.Header("col_one", "status_report") // Stays as "col_one", "status_report"
1661 tableNoAutoFormat.Append("Node1", "Ready")
1662 tableNoAutoFormat.Render()
1663
1664 // Using Option Function for Headers (default is ON, this makes it explicit)
1665 tableWithAutoFormat := tablewriter.NewTable(os.Stdout,
1666 tablewriter.WithHeaderAutoFormat(tw.On), // Explicitly enable title case (default behavior)
1667 )
1668
1669 tableWithAutoFormat.Header("col_one", "status_report") // Becomes "COL ONE", "STATUS REPORT"
1670 tableWithAutoFormat.Append("Node1", "Ready")
1671 tableWithAutoFormat.Render()
1672 }
1673 ```
1674
1675 **Output:**
1676 ```
1677 ┌─────────┬───────────────┐
1678 │ col_one │ status_report │
1679 ├─────────┼───────────────┤
1680 │ Node1 │ Ready │
1681 └─────────┴───────────────┘
1682 ┌─────────┬───────────────┐
1683 │ COL ONE │ STATUS REPORT │
1684 ├─────────┼───────────────┤
1685 │ Node1 │ Ready │
1686 └─────────┴───────────────┘
1687 ```
1688
1689 **Key Changes**:
1690 - **Method**: `SetAutoFormatHeaders` is replaced by `Config.Header.Formatting.AutoFormat`, or equivalent builder methods (`config.go`).
1691 - **Extended Scope**: Auto-formatting can now be applied to rows and footers via `Config.Row.Formatting.AutoFormat` and `Config.Footer.Formatting.AutoFormat`, unlike v0.0.5’s header-only support (`tw/cell.go`).
1692 - **Type Safety**: `tw.State` (`tw.On`, `tw.Off`, `tw.Unknown`) controls formatting state, replacing boolean flags (`tw/state.go`).
1693 - **Behavior**: When `tw.On`, the `tw.Title` function converts text to uppercase and replaces underscores and some periods with spaces (e.g., "col_one" → "COL ONE") (`tw/fn.go:Title`, `zoo.go:prepareContent`).
1694 - **Defaults**: `Header.Formatting.AutoFormat = tw.On`, `Row.Formatting.AutoFormat = tw.Off`, `Footer.Formatting.AutoFormat = tw.Off` (`config.go:defaultConfig`).
1695
1696 **Migration Tips**:
1697 - To maintain v0.0.5’s default header title case behavior, no explicit action is needed as `WithHeaderAutoFormat(tw.On)` is the default. If you were using `SetAutoFormatHeaders(false)`, you'd use `WithHeaderAutoFormat(tw.Off)`.
1698 - Explicitly set `WithRowAutoFormat(tw.Off)` or `WithFooterAutoFormat(tw.Off)` if you want to ensure rows and footers remain unformatted, as v1.0.x allows enabling formatting for these sections (`config.go`).
1699 - Use `ConfigBuilder.Header().Formatting().WithAutoFormat(tw.State)` for precise control over formatting per section (`config.go`).
1700 - Test header output with underscores or periods (e.g., "my_column") to verify title case transformation meets expectations.
1701 - For custom formatting beyond title case (e.g., custom capitalization), use `tw.CellFilter` instead of `AutoFormat` (`tw/cell.go`).
1702
1703 **Potential Pitfalls**:
1704 - **Default Header Formatting**: `Header.Formatting.AutoFormat = tw.On` by default may unexpectedly alter header text (e.g., "col_one" → "COL ONE"); disable with `WithHeaderAutoFormat(tw.Off)` if raw headers are preferred (`config.go`).
1705 - **Row/Footer Formatting**: Enabling `AutoFormat` for rows or footers (not default) applies title case, which may not suit data content; verify with `tw.Off` unless intended (`tw/cell.go`).
1706 - **Filter Conflicts**: Combining `AutoFormat` with `tw.CellFilter` can lead to overlapping transformations; prioritize filters for complex formatting (`zoo.go:prepareContent`).
1707 - **Performance Overhead**: Auto-formatting large datasets may add minor processing time; disable for performance-critical applications (`zoo.go`).
1708
1709 ### 4.5. Text Wrapping
1710 Text wrapping determines how long cell content is handled within width constraints, offering more options in v1.0.x compared to v0.0.5’s binary toggle.
1711
1712 **Old (v0.0.5):**
1713 ```go
1714 package main
1715
1716 import (
1717 "github.com/olekukonko/tablewriter"
1718 "os"
1719 )
1720
1721 func main() {
1722 table := tablewriter.NewWriter(os.Stdout)
1723 // table.SetAutoWrapText(true) // Enable normal word wrapping
1724 // table.SetAutoWrapText(false) // Disable wrapping
1725 table.SetHeader([]string{"Long Header Text Example", "Status"})
1726 table.Append([]string{"This is some very long cell content that might wrap", "Ready"})
1727 table.Render()
1728 }
1729 ```
1730
1731 **New (v1.0.x):**
1732 ```go
1733 package main
1734
1735 import (
1736 "github.com/olekukonko/tablewriter"
1737 "github.com/olekukonko/tablewriter/tw" // For tw.WrapNormal etc.
1738 "os"
1739 )
1740
1741 func main() {
1742 // Using Option Functions for Quick Wrapping Settings on a specific section (e.g., Row)
1743 // To actually see wrapping, a MaxWidth for the table or columns is needed.
1744 table := tablewriter.NewTable(os.Stdout,
1745 tablewriter.WithRowAutoWrap(tw.WrapNormal), // Set row wrapping
1746 tablewriter.WithHeaderAutoWrap(tw.WrapTruncate), // Header truncates (default)
1747 tablewriter.WithMaxWidth(30), // Force wrapping by setting table max width
1748 )
1749 table.Header("Long Header Text", "Status")
1750 table.Append("This is a very long cell content", "Ready")
1751 table.Footer("Summary", "Active")
1752 table.Render()
1753
1754 // For more fine-grained control (e.g., different wrapping for header, row, footer):
1755 cfgBuilder := tablewriter.NewConfigBuilder()
1756 cfgBuilder.Header().Formatting().WithAutoWrap(tw.WrapTruncate) // Header: Truncate
1757 cfgBuilder.Row().Formatting().WithAutoWrap(tw.WrapNormal) // Row: Normal wrap
1758 cfgBuilder.Footer().Formatting().WithAutoWrap(tw.WrapBreak) // Footer: Break words
1759 cfgBuilder.WithMaxWidth(40) // Overall table width constraint
1760
1761 tableFullCfg := tablewriter.NewTable(os.Stdout, tablewriter.WithConfig(cfgBuilder.Build()))
1762 tableFullCfg.Header("Another Very Long Header Example That Will Be Truncated", "Info")
1763 tableFullCfg.Append("This is an example of row content that should wrap normally based on available space.", "Detail")
1764 tableFullCfg.Footer("FinalSummaryInformationThatMightBreakAcrossLines", "End")
1765 tableFullCfg.Render()
1766 }
1767 ```
1768
1769 **Output (tableOpt):**
1770 ```
1771 ┌──────────────┬────────┐
1772 │ LONG HEADER… │ STATUS │
1773 ├──────────────┼────────┤
1774 │ This is a │ Ready │
1775 │ very long │ │
1776 │ cell content │ │
1777 ├──────────────┼────────┤
1778 │ Summary │ Active │
1779 └──────────────┴────────┘
1780 ```
1781 *(Second table output will vary based on content and width)*
1782
1783 **Key Changes**:
1784 - **Method**: `SetAutoWrapText` is replaced by `Config.<Section>.Formatting.AutoWrap` or specific `With<Section>AutoWrap` options (`config.go`).
1785 - **Wrapping Modes**: `int` constants for `AutoWrap` (e.g., `tw.WrapNone`, `tw.WrapNormal`, `tw.WrapTruncate`, `tw.WrapBreak`) replace v0.0.5’s binary toggle (`tw/tw.go`).
1786 - **Section-Specific Control**: Wrapping is configurable per section (Header, Row, Footer), unlike v0.0.5’s global setting (`tw/cell.go`).
1787 - **Defaults**: `Header: tw.WrapTruncate`, `Row: tw.WrapNormal`, `Footer: tw.WrapNormal` (`config.go:defaultConfig`).
1788 - **Width Dependency**: Wrapping behavior relies on width constraints set by `Config.Widths` (fixed column widths), `Config.<Section>.ColMaxWidths` (max content width), or `Config.MaxWidth` (total table width) (`zoo.go:calculateContentMaxWidth`, `zoo.go:prepareContent`).
1789
1790 **Migration Tips**:
1791 - Replace `SetAutoWrapText(true)` with `WithRowAutoWrap(tw.WrapNormal)` to maintain v0.0.5’s default wrapping for rows (`config.go`).
1792 - Use `WithHeaderAutoWrap(tw.WrapTruncate)` to align with v1.0.x’s default header behavior, ensuring long headers are truncated (`config.go`).
1793 - Set `Config.Widths` or `Config.MaxWidth` explicitly to enforce wrapping, as unconstrained widths may prevent wrapping (`config.go`).
1794 - Use `ConfigBuilder.<Section>().Formatting().WithAutoWrap(int_wrap_mode)` for precise control over wrapping per section (`config.go`).
1795 - Test wrapping with varied content lengths (e.g., short and long text) to ensure readability and proper width allocation.
1796 - Consider `tw.WrapNormal` for data rows to preserve content integrity, reserving `tw.WrapTruncate` for headers or footers (`tw/tw.go`).
1797
1798 **Potential Pitfalls**:
1799 - **Missing Width Constraints**: Without `Config.Widths`, `ColMaxWidths`, or `MaxWidth`, wrapping may not occur, leading to overflow; always define width limits for wrapping (`zoo.go`).
1800 - **Streaming Width Impact**: In streaming mode, wrapping depends on fixed widths set at `Start()`; narrow widths may truncate content excessively (`stream.go:streamCalculateWidths`).
1801 - **Truncation Data Loss**: `tw.WrapTruncate` may obscure critical data in rows; use `tw.WrapNormal` or wider columns to retain content (`tw/tw.go`).
1802 - **Performance Overhead**: Wrapping large datasets with `tw.WrapNormal` or `tw.WrapBreak` can add processing time; optimize widths for performance-critical applications (`zoo.go:prepareContent`).
1803 - **Inconsistent Section Wrapping**: Default wrapping differs (`Header: tw.WrapTruncate`, `Row/Footer: tw.WrapNormal`); align settings if uniform behavior is needed (`config.go`).
1804
1805 ### 4.6. Padding
1806 Padding adds spacing within cells, enhancing readability and affecting cell width calculations. v1.0.x introduces granular, per-side padding, replacing v0.0.5’s single inter-column padding control.
1807
1808 **Old (v0.0.5):**
1809 ```go
1810 package main
1811
1812 import (
1813 "github.com/olekukonko/tablewriter"
1814 "os"
1815 )
1816
1817 func main() {
1818 table := tablewriter.NewWriter(os.Stdout)
1819 // table.SetTablePadding("\t") // Set inter-column space character when borders are off
1820 // Default: single space within cells
1821 table.SetHeader([]string{"Header1"})
1822 table.Append([]string{"Cell1"})
1823 table.Render()
1824 }
1825 ```
1826
1827 **New (v1.0.x):**
1828 ```go
1829 package main
1830
1831 import (
1832 "github.com/olekukonko/tablewriter"
1833 "github.com/olekukonko/tablewriter/tw"
1834 "os"
1835 )
1836
1837 func main() {
1838 // Using Direct Config Struct
1839 cfg := tablewriter.Config{
1840 Header: tw.CellConfig{
1841 Padding: tw.CellPadding{
1842 Global: tw.Padding{Left: "[", Right: "]", Top: "-", Bottom: "-"}, // Padding for all header cells
1843 PerColumn: []tw.Padding{ // Specific padding for header column 0
1844 {Left: ">>", Right: "<<", Top: "=", Bottom: "="}, // Overrides Global for column 0
1845 },
1846 },
1847 },
1848 Row: tw.CellConfig{
1849 Padding: tw.CellPadding{
1850 Global: tw.PaddingDefault, // One space left/right for all row cells
1851 },
1852 },
1853 Footer: tw.CellConfig{
1854 Padding: tw.CellPadding{
1855 Global: tw.Padding{Top: "~", Bottom: "~"}, // Top/bottom padding for all footer cells
1856 },
1857 },
1858 }
1859 table := tablewriter.NewTable(os.Stdout, tablewriter.WithConfig(cfg))
1860
1861 table.Header("Name", "Status") // Two columns
1862 table.Append("Node1", "Ready")
1863 table.Footer("End", "Active")
1864 table.Render()
1865 }
1866 ```
1867
1868 **Output:**
1869 ```
1870 ┌────────┬────────┐
1871 │========│[------]│
1872 │>>NAME<<│[STATUS]│
1873 │========│[------]│
1874 ├────────┼────────┤
1875 │ Node1 │ Ready │
1876 │~~~~~~~~│~~~~~~~~│
1877 │End │Active │
1878 │~~~~~~~~│~~~~~~~~│
1879 └────────┴────────┘
1880 ```
1881
1882 **Key Changes**:
1883 - **No Direct Equivalent for `SetTablePadding`**: `SetTablePadding` controlled inter-column spacing when borders were off in v0.0.5; v1.0.x has no direct equivalent for *inter-column* spacing separate from cell padding. Inter-column visual separation is now primarily handled by `tw.Rendition.Settings.Separators.BetweenColumns` and the chosen `tw.Symbols`.
1884 - **Granular Cell Padding**: `tw.CellPadding` (`tw/cell.go:CellPadding`) supports:
1885 - `Global`: A `tw.Padding` struct with `Left`, `Right`, `Top`, `Bottom` strings and an `Overwrite` flag (`tw/types.go:Padding`). This padding is *inside* the cell.
1886 - `PerColumn`: A slice of `tw.Padding` for column-specific padding, overriding `Global` for specified columns.
1887 - **Per-Side Control**: `Top` and `Bottom` padding add extra lines *within* cells, unlike v0.0.5’s left/right-only spacing (`zoo.go:prepareContent`).
1888 - **Defaults**: `tw.PaddingDefault` is `{Left: " ", Right: " "}` for all sections (applied inside cells); `Top` and `Bottom` are empty by default (`tw/preset.go`).
1889 - **Width Impact**: Cell padding contributes to column widths, calculated in `Config.Widths` (`zoo.go:calculateAndNormalizeWidths`).
1890 - **Presets**: `tw.PaddingNone` (`{Left: "", Right: "", Top: "", Bottom: "", Overwrite: true}`) removes padding for tight layouts (`tw/preset.go`).
1891
1892 **Migration Tips**:
1893 - To achieve spacing similar to `SetTablePadding("\t")` when borders are off, you would set cell padding: `WithPadding(tw.Padding{Left: "\t", Right: "\t"})`. If you truly mean space *between* columns and not *inside* cells, ensure `tw.Rendition.Settings.Separators.BetweenColumns` is `tw.On` and customize `tw.Symbols.Column()` if needed.
1894 - Use `tw.PaddingNone` (e.g., via `ConfigBuilder.<Section>().Padding().WithGlobal(tw.PaddingNone)`) for no cell padding.
1895 - Set `Top` and `Bottom` padding for vertical spacing *within* cells, enhancing readability for multi-line content (`tw/types.go`).
1896 - Use `ConfigBuilder.<Section>().Padding().WithPerColumn` for column-specific padding to differentiate sections or columns (`config.go`).
1897 - Test padding with varied content and widths to ensure proper alignment and spacing, especially with wrapping enabled (`zoo.go`).
1898 - Combine padding with `Config.Widths` or `ColMaxWidths` to control total cell size (`config.go`).
1899
1900 **Potential Pitfalls**:
1901 - **Inter-Column Spacing vs. Cell Padding**: Be clear whether you want space *between* columns (separators) or *inside* cells (padding). `SetTablePadding` was ambiguous; v1.0.x distinguishes these.
1902 - **Width Inflation**: Cell padding increases column widths, potentially exceeding `Config.MaxWidth` or causing truncation in streaming; adjust `Config.Widths` accordingly (`zoo.go`).
1903 - **Top/Bottom Padding**: Non-empty `Top` or `Bottom` padding adds vertical lines *within* cells, increasing cell height; use sparingly for dense tables (`zoo.go:prepareContent`).
1904 - **Streaming Constraints**: Padding is fixed in streaming mode after `Start()`; ensure `Config.Widths` accommodates padding (`stream.go`).
1905 - **Default Padding**: `tw.PaddingDefault` adds spaces *inside* cells; set `tw.PaddingNone` for no internal cell padding (`tw/preset.go`).
1906
1907 ### 4.7. Column Widths (Fixed Widths and Max Content Widths)
1908 Column width control in v1.0.x is more sophisticated, offering fixed widths, maximum content widths, and overall table width constraints, replacing v0.0.5’s limited `SetColMinWidth`.
1909
1910 **Old (v0.0.5):**
1911 ```go
1912 package main
1913
1914 import (
1915 "github.com/olekukonko/tablewriter"
1916 "os"
1917 )
1918
1919 func main() {
1920 table := tablewriter.NewWriter(os.Stdout)
1921 // table.SetColMinWidth(0, 10) // Set minimum width for column 0
1922 table.SetHeader([]string{"Header1", "Header2"})
1923 table.Append([]string{"Cell1-Content", "Cell2-Content"})
1924 table.Render()
1925 }
1926 ```
1927
1928 **New (v1.0.x):**
1929 ```go
1930 package main
1931
1932 import (
1933 "github.com/olekukonko/tablewriter"
1934 "github.com/olekukonko/tablewriter/tw"
1935 "os"
1936 )
1937
1938 func main() {
1939 // Direct Config for Width Control
1940 cfg := tablewriter.Config{
1941 Widths: tw.CellWidth{ // Fixed total column widths (content + padding)
1942 Global: 20, // Default fixed width for all columns
1943 PerColumn: tw.NewMapper[int, int]().Set(0, 15), // Column 0 fixed at 15
1944 },
1945 Header: tw.CellConfig{
1946 ColMaxWidths: tw.CellWidth{ // Max content width (excluding padding) for header cells
1947 Global: 15, // Max content width for all header cells
1948 PerColumn: tw.NewMapper[int, int]().Set(0, 10), // Header Col 0 max content at 10
1949 },
1950 // Default header padding is " " on left/right, so content 10 + padding 2 = 12.
1951 // If Widths.PerColumn[0] is 15, there's space.
1952 },
1953 Row: tw.CellConfig{
1954 ColMaxWidths: tw.CellWidth{Global: 18}, // Max content width for row cells (18 + default padding 2 = 20)
1955 },
1956 MaxWidth: 80, // Constrain total table width (optional, columns might shrink)
1957 }
1958 tableWithCfg := tablewriter.NewTable(os.Stdout, tablewriter.WithConfig(cfg))
1959 tableWithCfg.Header("Very Long Header Name", "Status Information")
1960 tableWithCfg.Append("Some long content for the first column", "Ready")
1961 tableWithCfg.Render()
1962
1963 // Option Functions for Width Settings
1964 tableWithOpts := tablewriter.NewTable(os.Stdout,
1965 tablewriter.WithColumnMax(20), // Sets Config.Widths.Global (fixed total col width)
1966 tablewriter.WithColumnWidths(tw.NewMapper[int, int]().Set(0, 15)), // Sets Config.Widths.PerColumn for col 0
1967 tablewriter.WithMaxWidth(80), // Sets Config.MaxWidth
1968 // For max content width per section, you'd use WithHeaderConfig, WithRowConfig, etc.
1969 // e.g., tablewriter.WithRowMaxWidth(18) // Sets Config.Row.ColMaxWidths.Global
1970 )
1971 tableWithOpts.Header("Long Header", "Status")
1972 tableWithOpts.Append("Long Content", "Ready")
1973 tableWithOpts.Render()
1974 }
1975 ```
1976
1977 **Output (tableWithCfg - illustrative, exact wrapping depends on content and full config):**
1978 ```
1979 ┌───────────┬──────────────────┐
1980 │ VERY LONG │ STATUS INFORMAT… │
1981 │ HEADER NA…│ │
1982 ├───────────┼──────────────────┤
1983 │ Some long │ Ready │
1984 │ content f…│ │
1985 └───────────┴──────────────────┘
1986 ```
1987
1988 **Key Changes**:
1989 - **Enhanced Width System**: v1.0.x introduces three levels of width control, replacing `SetColMinWidth` (`config.go`):
1990 - **Config.Widths**: Sets fixed total widths (content + padding) for columns, applied globally or per-column (`tw.CellWidth`).
1991 - `Global`: Default fixed width for all columns.
1992 - `PerColumn`: `tw.Mapper[int, int]` for specific column widths.
1993 - **Config.<Section>.ColMaxWidths**: Sets maximum content widths (excluding padding) for a section (Header, Row, Footer) (`tw.CellWidth`).
1994 - `Global`: Max content width for all cells in the section.
1995 - `PerColumn`: `tw.Mapper[int, int]` for specific columns in the section.
1996 - **Config.MaxWidth**: Constrains the total table width, shrinking columns proportionally if needed (`config.go`).
1997 - **Streaming Support**: In streaming mode, `Config.Widths` fixes column widths at `Start()`; `ColMaxWidths` is used only for wrapping/truncation (`stream.go:streamCalculateWidths`).
1998 - **Calculation Logic**: Widths are computed by `calculateAndNormalizeWidths` in batch mode and `streamCalculateWidths` in streaming mode, considering content, padding, and constraints (`zoo.go`, `stream.go`).
1999 - **Deprecated Approach**: `SetColMinWidth` is replaced by `Config.Widths.PerColumn` or `Config.<Section>.ColMaxWidths.PerColumn` for more precise control (`deprecated.go`).
2000
2001 **Migration Tips**:
2002 - Replace `SetColMinWidth(col, w)` with `WithColumnWidths(tw.NewMapper[int, int]().Set(col, w))` for fixed column widths or `Config.<Section>.ColMaxWidths.PerColumn` for content width limits (`config.go`).
2003 - Use `Config.Widths.Global` or `WithColumnMax(w)` to set a default fixed width for all columns, ensuring consistency (`tablewriter.go`).
2004 - Apply `Config.MaxWidth` to constrain total table width, especially for wide datasets (`config.go`).
2005 - Use `ConfigBuilder.ForColumn(idx).WithMaxWidth(w)` to set per-column content width limits across sections (`config.go`). *(Note: This sets it for Header, Row, and Footer)*
2006 - In streaming mode, set `Config.Widths` before `Start()` to fix widths, avoiding content-based sizing (`stream.go`).
2007 - Test width settings with varied content to ensure wrapping and truncation behave as expected (`zoo.go`).
2008
2009 **Potential Pitfalls**:
2010 - **Width Precedence**: `Config.Widths.PerColumn` overrides `Widths.Global`; `ColMaxWidths` applies *within* those fixed total widths for content wrapping/truncation (`zoo.go`).
2011 - **Streaming Width Fixing**: Widths are locked after `Start()` in streaming; inconsistent data may cause truncation (`stream.go`).
2012 - **Padding Impact**: Padding adds to total width when considering `Config.Widths`; account for `tw.CellPadding` when setting fixed column widths (`zoo.go`).
2013 - **MaxWidth Shrinkage**: `Config.MaxWidth` may shrink columns unevenly; test with `MaxWidth` to avoid cramped layouts (`zoo.go`).
2014 - **No Width Constraints**: Without `Widths` or `MaxWidth`, columns size to content, potentially causing overflow; define limits (`zoo.go`).
2015
2016 ### 4.8. Colors
2017 Colors in v0.0.5 were applied via specific color-setting methods, while v1.0.x embeds ANSI escape codes in cell content or uses data-driven formatting for greater flexibility.
2018
2019 **Old (v0.0.5):**
2020 ```go
2021 package main
2022 // Assuming tablewriter.Colors and color constants existed in v0.0.5
2023 // This is a mock representation as the actual v0.0.5 definitions are not provided.
2024 // import "github.com/olekukonko/tablewriter"
2025 // import "os"
2026
2027 // type Colors []interface{} // Mock
2028 // const (
2029 // Bold = 1; FgGreenColor = 2; FgRedColor = 3 // Mock constants
2030 // )
2031
2032 func main() {
2033 // table := tablewriter.NewWriter(os.Stdout)
2034 // table.SetColumnColor(
2035 // tablewriter.Colors{tablewriter.Bold, tablewriter.FgGreenColor}, // Column 0
2036 // tablewriter.Colors{tablewriter.FgRedColor}, // Column 1
2037 // )
2038 // table.SetHeader([]string{"Name", "Status"})
2039 // table.Append([]string{"Node1", "Ready"})
2040 // table.Render()
2041 }
2042 ```
2043
2044 **New (v1.0.x):**
2045 ```go
2046 package main
2047
2048 import (
2049 "fmt"
2050 "github.com/olekukonko/tablewriter"
2051 "github.com/olekukonko/tablewriter/tw" // For tw.Formatter
2052 "os"
2053 )
2054
2055 // Direct ANSI Code Embedding
2056 const (
2057 Reset = "\033[0m"
2058 Bold = "\033[1m"
2059 FgGreen = "\033[32m"
2060 FgRed = "\033[31m"
2061 )
2062
2063 // Using tw.Formatter for Custom Types
2064 type Status string
2065
2066 func (s Status) Format() string { // Implements tw.Formatter
2067 color := FgGreen
2068 if s == "Error" || s == "Inactive" {
2069 color = FgRed
2070 }
2071 return color + string(s) + Reset
2072 }
2073
2074 func main() {
2075 // Example 1: Direct ANSI embedding
2076 tableDirectANSI := tablewriter.NewTable(os.Stdout,
2077 tablewriter.WithHeaderAutoFormat(tw.Off), // Keep header text as is for coloring
2078 )
2079 tableDirectANSI.Header(Bold+FgGreen+"Name"+Reset, Bold+FgRed+"Status"+Reset)
2080 tableDirectANSI.Append([]any{"Node1", FgGreen + "Ready" + Reset})
2081 tableDirectANSI.Append([]any{"Node2", FgRed + "Error" + Reset})
2082 tableDirectANSI.Render()
2083
2084 fmt.Println("\n--- Table with Formatter for Colors ---")
2085
2086 // Example 2: Using tw.Formatter
2087 tableFormatter := tablewriter.NewTable(os.Stdout)
2088 tableFormatter.Header("Name", "Status") // AutoFormat will apply to "NAME", "STATUS"
2089 tableFormatter.Append([]any{"Alice", Status("Active")})
2090 tableFormatter.Append([]any{"Bob", Status("Inactive")})
2091 tableFormatter.Render()
2092
2093 fmt.Println("\n--- Table with CellFilter for Colors ---")
2094 // Example 3: Using CellFilter
2095 tableWithFilters := tablewriter.NewTable(os.Stdout,
2096 tablewriter.WithConfig(
2097 tablewriter.NewConfigBuilder().
2098 Row().
2099 Filter().
2100 WithPerColumn([]func(string) string{
2101 nil, // No filter for Item column
2102 func(s string) string { // Status column: apply color
2103 if s == "Ready" || s == "Active" {
2104 return FgGreen + s + Reset
2105 }
2106 return FgRed + s + Reset
2107 },
2108 }).
2109 Build(). // Return to RowConfigBuilder
2110 Build(). // Return to ConfigBuilder
2111 Build(), // Finalize Config
2112 ),
2113 )
2114 tableWithFilters.Header("Item", "Availability")
2115 tableWithFilters.Append("ItemA", "Ready")
2116 tableWithFilters.Append("ItemB", "Unavailable")
2117 tableWithFilters.Render()
2118 }
2119 ```
2120
2121 **Output (Text Approximation, Colors Not Shown):**
2122 ```
2123 ┌──────┬────────┐
2124 │ Name │ Status │
2125 ├──────┼────────┤
2126 │Node1 │ Ready │
2127 │Node2 │ Error │
2128 └──────┴────────┘
2129
2130 --- Table with Formatter for Colors ---
2131 ┌───────┬──────────┐
2132 │ NAME │ STATUS │
2133 ├───────┼──────────┤
2134 │ Alice │ Active │
2135 │ Bob │ Inactive │
2136 └───────┴──────────┘
2137
2138 --- Table with CellFilter for Colors ---
2139 ┌───────┬────────────┐
2140 │ ITEM │ AVAILABILI │
2141 │ │ TY │
2142 ├───────┼────────────┤
2143 │ ItemA │ Ready │
2144 │ ItemB │ Unavailabl │
2145 │ │ e │
2146 └───────┴────────────┘
2147 ```
2148
2149 **Key Changes**:
2150 - **Removed Color Methods**: `SetColumnColor`, `SetHeaderColor`, and `SetFooterColor` are removed; colors are now applied by embedding ANSI escape codes in cell content or via data-driven mechanisms (`tablewriter.go`).
2151 - **Flexible Coloring Options**:
2152 - **Direct ANSI Codes**: Embed codes (e.g., `\033[32m` for green) in strings for manual control (`zoo.go:convertCellsToStrings`).
2153 - **tw.Formatter**: Implement `Format() string` on custom types to control cell output, including colors (`tw/types.go:Formatter`).
2154 - **tw.CellFilter**: Use `Config.<Section>.Filter.Global` or `PerColumn` to apply transformations like coloring dynamically (`tw/cell.go:CellFilter`).
2155 - **Width Handling**: `twdw.Width()` correctly calculates display width of ANSI-coded strings, ignoring escape sequences (`tw/fn.go:DisplayWidth`).
2156 - **No Built-In Color Presets**: Unlike v0.0.5’s potential `tablewriter.Colors`, v1.0.x requires manual ANSI code management or external libraries for color constants.
2157
2158 **Migration Tips**:
2159 - Replace `SetColumnColor` with direct ANSI code embedding for simple cases (e.g., `FgGreen+"text"+Reset`) (`zoo.go`).
2160 - Implement `tw.Formatter` on custom types for reusable, semantic color logic (e.g., `Status` type above) (`tw/types.go`).
2161 - Use `ConfigBuilder.<Section>().Filter().WithPerColumn` to apply color filters to specific columns, mimicking v0.0.5’s per-column coloring (`config.go`).
2162 - Define ANSI constants in your codebase or use a library (e.g., `github.com/fatih/color`) to simplify color management.
2163 - Test colored output in your target terminal to ensure ANSI codes render correctly.
2164 - Combine filters with `AutoFormat` or wrapping for consistent styling (`zoo.go:prepareContent`).
2165
2166 **Potential Pitfalls**:
2167 - **Terminal Support**: Some terminals may not support ANSI codes, causing artifacts; test in your environment or provide a non-colored fallback.
2168 - **Filter Overlap**: Combining `tw.CellFilter` with `AutoFormat` or other transformations can lead to unexpected results; prioritize filters for coloring (`zoo.go`).
2169 - **Width Miscalculation**: Incorrect ANSI code handling (e.g., missing `Reset`) can skew width calculations; use `twdw.Width` (`tw/fn.go`).
2170 - **Streaming Consistency**: In streaming mode, ensure color codes are applied consistently across rows to avoid visual discrepancies (`stream.go`).
2171 - **Performance**: Applying filters to large datasets may add overhead; optimize filter logic for efficiency (`zoo.go`).
2172
2173 ## Advanced Features in v1.0.x
2174
2175 v1.0.x introduces several advanced features that enhance table functionality beyond v0.0.5’s capabilities. This section covers cell merging, captions, filters, stringers, and performance optimizations, providing migration guidance and examples for leveraging these features.
2176
2177 ### 5. Cell Merging
2178 Cell merging combines adjacent cells with identical content, improving readability for grouped data. v1.0.x expands merging options beyond v0.0.5’s horizontal merging.
2179
2180 **Old (v0.0.5):**
2181 ```go
2182 package main
2183
2184 import (
2185 "github.com/olekukonko/tablewriter"
2186 "os"
2187 )
2188
2189 func main() {
2190 table := tablewriter.NewWriter(os.Stdout)
2191 // table.SetAutoMergeCells(true) // Enable horizontal merging
2192 table.SetHeader([]string{"Category", "Item", "Notes"})
2193 table.Append([]string{"Fruit", "Apple", "Red"})
2194 table.Append([]string{"Fruit", "Apple", "Green"}) // "Apple" might merge if SetAutoMergeCells was on
2195 table.Render()
2196 }
2197 ```
2198
2199 **New (v1.0.x):**
2200 ```go
2201 package main
2202
2203 import (
2204 "github.com/olekukonko/tablewriter"
2205 "github.com/olekukonko/tablewriter/renderer"
2206 "github.com/olekukonko/tablewriter/tw"
2207 "os"
2208 )
2209
2210 func main() {
2211 // Horizontal Merging (Similar to v0.0.5)
2212 tableH := tablewriter.NewTable(os.Stdout,
2213 tablewriter.WithConfig(tablewriter.Config{Row: tw.CellConfig{Merging: tw.CellMerging{Mode: tw.MergeHorizontal}}}),
2214 tablewriter.WithRenderer(renderer.NewBlueprint(tw.Rendition{Symbols: tw.NewSymbols(tw.StyleASCII)})), // Specify renderer for symbols
2215 )
2216 tableH.Header("Category", "Item", "Item", "Notes") // Note: Two "Item" headers for demo
2217 tableH.Append("Fruit", "Apple", "Apple", "Red") // "Apple" cells merge
2218 tableH.Render()
2219
2220 // Vertical Merging
2221 tableV := tablewriter.NewTable(os.Stdout,
2222 tablewriter.WithConfig(tablewriter.Config{Row: tw.CellConfig{Merging: tw.CellMerging{Mode: tw.MergeVertical}}}),
2223 tablewriter.WithRenderer(renderer.NewBlueprint(tw.Rendition{Symbols: tw.NewSymbols(tw.StyleASCII)})),
2224 )
2225 tableV.Header("User", "Permission")
2226 tableV.Append("Alice", "Read")
2227 tableV.Append("Alice", "Write") // "Alice" cells merge vertically
2228 tableV.Append("Bob", "Read")
2229 tableV.Render()
2230
2231 // Hierarchical Merging
2232 tableHier := tablewriter.NewTable(os.Stdout,
2233 tablewriter.WithConfig(tablewriter.Config{Row: tw.CellConfig{Merging: tw.CellMerging{Mode: tw.MergeHierarchical}}}),
2234 tablewriter.WithRenderer(renderer.NewBlueprint(tw.Rendition{Symbols: tw.NewSymbols(tw.StyleASCII)})),
2235 )
2236 tableHier.Header("Group", "SubGroup", "Item")
2237 tableHier.Append("Tech", "CPU", "i7")
2238 tableHier.Append("Tech", "CPU", "i9") // "Tech" and "CPU" merge
2239 tableHier.Append("Tech", "RAM", "16GB") // "Tech" merges, "RAM" is new
2240 tableHier.Append("Office", "CPU", "i5") // "Office" is new
2241 tableHier.Render()
2242 }
2243 ```
2244
2245 **Output (Horizontal):**
2246 ```
2247 +----------+-------+-------+-------+
2248 | CATEGORY | ITEM | ITEM | NOTES |
2249 +----------+-------+-------+-------+
2250 | Fruit | Apple | Red |
2251 +----------+---------------+-------+
2252 ```
2253
2254 **Output (Vertical):**
2255 ```
2256 +-------+------------+
2257 | USER | PERMISSION |
2258 +-------+------------+
2259 | Alice | Read |
2260 | | Write |
2261 +-------+------------+
2262 | Bob | Read |
2263 +-------+------------+
2264 ```
2265
2266 **Output (Hierarchical):**
2267 ```
2268 +---------+----------+------+
2269 | GROUP | SUBGROUP | ITEM |
2270 +---------+----------+------+
2271 | Tech | CPU | i7 |
2272 | | | i9 |
2273 | +----------+------+
2274 | | RAM | 16GB |
2275 +---------+----------+------+
2276 | Office | CPU | i5 |
2277 +---------+----------+------+
2278 ```
2279
2280 **Key Changes**:
2281 - **Method**: `SetAutoMergeCells` is replaced by `WithRowMergeMode(int_merge_mode)` or `Config.Row.Formatting.MergeMode` (`config.go`). Uses `tw.Merge...` constants.
2282 - **Merge Modes**: `tw.MergeMode` constants (`tw.MergeNone`, `tw.MergeHorizontal`, `tw.MergeVertical`, `tw.MergeHierarchical`) define behavior (`tw/tw.go`).
2283 - **Section-Specific**: Merging can be applied to `Header`, `Row`, or `Footer` via `Config.<Section>.Formatting.MergeMode` (`tw/cell.go`).
2284 - **Processing**: Merging is handled during content preparation (`zoo.go:prepareWithMerges`, `zoo.go:applyVerticalMerges`, `zoo.go:applyHierarchicalMerges`).
2285 - **Width Adjustment**: Horizontal merging adjusts column widths (`zoo.go:applyHorizontalMergeWidths`).
2286 - **Renderer Support**: `tw.MergeState` in `tw.CellContext` ensures correct border drawing for merged cells (`tw/cell.go:CellContext`).
2287 - **Streaming Limitation**: Streaming mode supports only simple horizontal merging due to fixed widths (`stream.go:streamAppendRow`).
2288
2289 **Migration Tips**:
2290 - Replace `SetAutoMergeCells(true)` with `WithRowMergeMode(tw.MergeHorizontal)` to maintain v0.0.5’s horizontal merging behavior (`config.go`).
2291 - Use `tw.MergeVertical` for vertical grouping (e.g., repeated user names) or `tw.MergeHierarchical` for nested data structures (`tw/tw.go`).
2292 - Apply merging to specific sections via `ConfigBuilder.<Section>().Formatting().WithMergeMode(int_merge_mode)` (`config.go`).
2293 - Test merging with sample data to verify visual output, especially for hierarchical merging with complex datasets.
2294 - In streaming mode, ensure `Config.Widths` supports merged cell widths to avoid truncation (`stream.go`).
2295 - Use `WithDebug(true)` to log merge processing for troubleshooting (`config.go`).
2296
2297 **Potential Pitfalls**:
2298 - **Streaming Restrictions**: Vertical and hierarchical merging are unsupported in streaming mode; use batch mode for these features (`stream.go`).
2299 - **Width Misalignment**: Merged cells may require wider columns; adjust `Config.Widths` or `ColMaxWidths` (`zoo.go`).
2300 - **Data Dependency**: Merging requires identical content; case or whitespace differences prevent merging (`zoo.go`).
2301 - **Renderer Errors**: Incorrect `tw.MergeState` handling in custom renderers can break merged cell borders; test thoroughly (`tw/cell.go`).
2302 - **Performance**: Hierarchical merging with large datasets may slow rendering; optimize data or limit merging (`zoo.go`).
2303
2304 ### 6. Table Captions
2305 Captions add descriptive text above or below the table, a new feature in v1.0.x not present in v0.0.5.
2306
2307 **Old (v0.0.5):**
2308 ```go
2309 package main
2310 // No direct caption support in v0.0.5. Users might have printed text manually.
2311 // import "github.com/olekukonko/tablewriter"
2312 // import "os"
2313 // import "fmt"
2314
2315 func main() {
2316 // fmt.Println("Movie ratings.") // Manual caption
2317 // table := tablewriter.NewWriter(os.Stdout)
2318 // table.SetHeader([]string{"Name", "Sign", "Rating"})
2319 // table.Render()
2320 }
2321 ```
2322
2323 **New (v1.0.x):**
2324 ```go
2325 package main
2326
2327 import (
2328 "github.com/olekukonko/tablewriter"
2329 "github.com/olekukonko/tablewriter/tw"
2330 "os"
2331 )
2332
2333 func main() {
2334 table := tablewriter.NewTable(os.Stdout)
2335 table.Caption(tw.Caption{ // tw/types.go:Caption
2336 Text: "System Status Overview - A Very Long Caption Example To Demonstrate Wrapping Behavior",
2337 Spot: tw.SpotTopCenter, // Placement: TopLeft, TopCenter, TopRight, BottomLeft, BottomCenter, BottomRight
2338 Align: tw.AlignCenter, // Text alignment within caption width
2339 Width: 30, // Fixed width for caption text wrapping; if 0, wraps to table width
2340 })
2341 table.Header("Name", "Status")
2342 table.Append("Node1", "Ready")
2343 table.Append("SuperLongNodeNameHere", "ActiveNow")
2344 table.Render()
2345 }
2346 ```
2347
2348 **Output:**
2349 ```
2350 System Status Overview - A Very
2351 Long Caption Example To Demonst…
2352 ┌─────────────────────┬──────────┐
2353 │ NAME │ STATUS │
2354 ├─────────────────────┼──────────┤
2355 │ Node1 │ Ready │
2356 │ SuperLongNodeNameHe │ ActiveNo │
2357 │ re │ w │
2358 └─────────────────────┴──────────┘
2359 ```
2360
2361 **Key Changes**:
2362 - **New Feature**: `Table.Caption(tw.Caption)` introduces captions, absent in v0.0.5 (`tablewriter.go:Caption`).
2363 - **Configuration**: `tw.Caption` (`tw/types.go:Caption`) includes:
2364 - `Text`: Caption content.
2365 - `Spot`: Placement (`tw.SpotTopLeft`, `tw.SpotBottomCenter`, etc.); defaults to `tw.SpotBottomCenter` if `tw.SpotNone`.
2366 - `Align`: Text alignment (`tw.AlignLeft`, `tw.AlignCenter`, `tw.AlignRight`).
2367 - `Width`: Optional fixed width for wrapping; defaults to table width.
2368 - **Rendering**: Captions are rendered by `printTopBottomCaption` before or after the table based on `Spot` (`tablewriter.go:printTopBottomCaption`).
2369 - **Streaming**: Captions are rendered during `Close()` in streaming mode if placed at the bottom (`stream.go`).
2370
2371 **Migration Tips**:
2372 - Add captions to enhance table context, especially for reports or documentation (`tw/types.go`).
2373 - Use `tw.SpotTopCenter` for prominent placement above the table, aligning with common report formats.
2374 - Set `Align` to match table aesthetics (e.g., `tw.AlignCenter` for balanced appearance).
2375 - Specify `Width` for consistent wrapping, especially with long captions or narrow tables (`tablewriter.go`).
2376 - Test caption placement and alignment with different table sizes to ensure readability.
2377
2378 **Potential Pitfalls**:
2379 - **Spot Default**: If `Spot` is `tw.SpotNone`, caption defaults to `tw.SpotBottomCenter`, which may surprise users expecting no caption (`tablewriter.go`).
2380 - **Width Overflow**: Without `Width`, captions wrap to table width, potentially causing misalignment; set explicitly for control (`tw/types.go`).
2381 - **Streaming Delay**: Bottom-placed captions in streaming mode appear only at `Close()`; ensure `Close()` is called (`stream.go`).
2382 - **Alignment Confusion**: Caption `Align` is independent of table cell alignment; verify separately (`tw/cell.go`).
2383
2384 ### 7. Filters
2385 Filters allow dynamic transformation of cell content during rendering, a new feature in v1.0.x for tasks like formatting, coloring, or sanitizing data.
2386
2387 **Old (v0.0.5):**
2388 ```go
2389 package main
2390 // No direct support for cell content transformation in v0.0.5.
2391 // Users would typically preprocess data before appending.
2392 // import "github.com/olekukonko/tablewriter"
2393 // import "os"
2394 // import "strings"
2395
2396 func main() {
2397 // table := tablewriter.NewWriter(os.Stdout)
2398 // table.SetHeader([]string{"Name", "Status"})
2399 // status := " Ready "
2400 // preprocessedStatus := "Status: " + strings.TrimSpace(status)
2401 // table.Append([]string{"Node1", preprocessedStatus})
2402 // table.Render()
2403 }
2404 ```
2405
2406 **New (v1.0.x):**
2407 ```go
2408 package main
2409
2410 import (
2411 "github.com/olekukonko/tablewriter"
2412 "github.com/olekukonko/tablewriter/tw" // For tw.CellConfig etc.
2413 "os"
2414 "strings"
2415 )
2416
2417 func main() {
2418 // Per-Column Filter for Specific Transformations
2419 cfgBuilder := tablewriter.NewConfigBuilder()
2420 cfgBuilder.Row().Filter().WithPerColumn([]func(string) string{
2421 nil, // No filter for Name column
2422 func(s string) string { // Status column: prefix and trim
2423 return "Status: " + strings.TrimSpace(s)
2424 },
2425 })
2426
2427 tableWithFilter := tablewriter.NewTable(os.Stdout, tablewriter.WithConfig(cfgBuilder.Build()))
2428 tableWithFilter.Header("Name", "Status")
2429 tableWithFilter.Append("Node1", " Ready ") // Note the extra spaces
2430 tableWithFilter.Append("Node2", "Pending")
2431 tableWithFilter.Render()
2432
2433 // Global filter example (applied to all cells in the Row section)
2434 cfgGlobalFilter := tablewriter.NewConfigBuilder()
2435 cfgGlobalFilter.Row().Filter().WithGlobal(func(s string) string {
2436 return "[" + s + "]" // Wrap all row cells in brackets
2437 })
2438 tableGlobalFilter := tablewriter.NewTable(os.Stdout, tablewriter.WithConfig(cfgGlobalFilter.Build()))
2439 tableGlobalFilter.Header("Item", "Count")
2440 tableGlobalFilter.Append("Apple", "5")
2441 tableGlobalFilter.Render()
2442 }
2443 ```
2444
2445 **Output (Per-Column Filter):**
2446 ```
2447 ┌───────┬─────────────────┐
2448 │ NAME │ STATUS │
2449 ├───────┼─────────────────┤
2450 │ Node1 │ Status: Ready │
2451 │ Node2 │ Status: Pending │
2452 └───────┴─────────────────┘
2453 ```
2454
2455 **Output (Global Filter):**
2456 ```
2457 ┌───────┬─────────┐
2458 │ ITEM │ COUNT │
2459 ├───────┼─────────┤
2460 │[Apple]│ [5] │
2461 └───────┴─────────┘
2462 ```
2463
2464 **Key Changes**:
2465 - **New Feature**: `tw.CellFilter` (`tw/cell.go:CellFilter`) introduces:
2466 - `Global`: A `func(s []string) []string` applied to entire rows (all cells in that row) of a section.
2467 - `PerColumn`: A slice of `func(string) string` for column-specific transformations on individual cells.
2468 - **Configuration**: Set via `Config.<Section>.Filter` (`Header`, `Row`, `Footer`) using `ConfigBuilder` or direct `Config` (`config.go`).
2469 - **Processing**: Filters are applied during content preparation, after `AutoFormat` but before rendering (`zoo.go:convertCellsToStrings` calls `prepareContent` which applies some transformations, filters are applied in `convertCellsToStrings` itself).
2470 - **Use Cases**: Formatting (e.g., uppercase, prefixes), coloring (via ANSI codes), sanitization (e.g., removing sensitive data), or data normalization.
2471
2472 **Migration Tips**:
2473 - Use filters to replace manual content preprocessing in v0.0.5 (e.g., string manipulation before `Append`).
2474 - Apply `Global` filters for uniform transformations across all cells of rows in a section (e.g., uppercasing all row data) (`tw/cell.go`).
2475 - Use `PerColumn` filters for column-specific formatting (e.g., adding prefixes to status columns) (`config.go`).
2476 - Combine filters with `tw.Formatter` for complex types or ANSI coloring for visual enhancements (`tw/cell.go`).
2477 - Test filters with diverse inputs to ensure transformations preserve data integrity (`zoo.go`).
2478
2479 **Potential Pitfalls**:
2480 - **Filter Order**: Filters apply before some other transformations like padding and alignment; combining can lead to interactions.
2481 - **Performance**: Complex filters on large datasets may slow rendering; optimize logic (`zoo.go`).
2482 - **Nil Filters**: Unset filters (`nil`) are ignored, but incorrect indexing in `PerColumn` can skip columns (`tw/cell.go`).
2483 - **Streaming Consistency**: Filters must be consistent in streaming mode, as widths are fixed at `Start()` (`stream.go`).
2484
2485 ### 8. Stringers and Caching
2486 Stringers allow custom string conversion for data types, with v1.0.x adding caching for performance.
2487
2488 **Old (v0.0.5):**
2489 ```go
2490 package main
2491 // v0.0.5 primarily relied on fmt.Stringer for custom types.
2492 // import "fmt"
2493 // import "github.com/olekukonko/tablewriter"
2494 // import "os"
2495
2496 // type MyCustomType struct {
2497 // Value string
2498 // }
2499 // func (m MyCustomType) String() string { return "Formatted: " + m.Value }
2500
2501 func main() {
2502 // table := tablewriter.NewWriter(os.Stdout)
2503 // table.SetHeader([]string{"Custom Data"})
2504 // table.Append([]string{MyCustomType{"test"}.String()}) // Manual call to String()
2505 // table.Render()
2506 }
2507 ```
2508
2509 **New (v1.0.x):**
2510 ```go
2511 package main
2512
2513 import (
2514 "fmt"
2515 "github.com/olekukonko/tablewriter"
2516 "github.com/olekukonko/tablewriter/tw" // For tw.Formatter
2517 "os"
2518 "strings" // For Person example
2519 )
2520
2521 // Example 1: Using WithStringer for general conversion
2522 type CustomInt int
2523
2524 func main() {
2525 // Table with a general stringer (func(any) []string)
2526 tableWithStringer := tablewriter.NewTable(os.Stdout,
2527 tablewriter.WithStringer(func(v any) []string { // Must return []string
2528 if ci, ok := v.(CustomInt); ok {
2529 return []string{fmt.Sprintf("CustomInt Value: %d!", ci)}
2530 }
2531 return []string{fmt.Sprintf("Value: %v", v)} // Fallback
2532 }),
2533 tablewriter.WithDebug(true), // Enable caching if WithStringerCache() is also used
2534 // tablewriter.WithStringerCache(), // Optional: enable caching
2535 )
2536 tableWithStringer.Header("Data")
2537 tableWithStringer.Append(123)
2538 tableWithStringer.Append(CustomInt(456))
2539 tableWithStringer.Render()
2540
2541 fmt.Println("\n--- Table with Type-Specific Stringer for Structs ---")
2542
2543 // Example 2: Stringer for a specific struct type
2544 type Person struct {
2545 ID int
2546 Name string
2547 City string
2548 }
2549
2550 // Stringer for Person to produce 3 cells
2551 personToStrings := func(p Person) []string {
2552 return []string{
2553 fmt.Sprintf("ID: %d", p.ID),
2554 p.Name,
2555 strings.ToUpper(p.City),
2556 }
2557 }
2558
2559 tablePersonStringer := tablewriter.NewTable(os.Stdout,
2560 tablewriter.WithStringer(personToStrings), // Pass the type-specific function
2561 )
2562 tablePersonStringer.Header("User ID", "Full Name", "Location")
2563 tablePersonStringer.Append(Person{1, "Alice", "New York"})
2564 tablePersonStringer.Append(Person{2, "Bob", "London"})
2565 tablePersonStringer.Render()
2566
2567 fmt.Println("\n--- Table with tw.Formatter ---")
2568 // Example 3: Using tw.Formatter for types
2569 type Product struct {
2570 Name string
2571 Price float64
2572 }
2573 func (p Product) Format() string { // Implements tw.Formatter
2574 return fmt.Sprintf("%s - $%.2f", p.Name, p.Price)
2575 }
2576 tableFormatter := tablewriter.NewTable(os.Stdout)
2577 tableFormatter.Header("Product Details")
2578 tableFormatter.Append(Product{"Laptop", 1200.99}) // Will use Format()
2579 tableFormatter.Render()
2580 }
2581 ```
2582
2583 **Output (Stringer Examples):**
2584 ```
2585 ┌─────────────────────┐
2586 │ DATA │
2587 ├─────────────────────┤
2588 │ Value: 123 │
2589 │ CustomInt Value: 456! │
2590 └─────────────────────┘
2591
2592 --- Table with Type-Specific Stringer for Structs ---
2593 ┌─────────┬───────────┬──────────┐
2594 │ USER ID │ FULL NAME │ LOCATION │
2595 ├─────────┼───────────┼──────────┤
2596 │ ID: 1 │ Alice │ NEW YORK │
2597 │ ID: 2 │ Bob │ LONDON │
2598 └─────────┴───────────┴──────────┘
2599
2600 --- Table with tw.Formatter ---
2601 ┌─────────────────┐
2602 │ PRODUCT DETAILS │
2603 ├─────────────────┤
2604 │ Laptop - $1200… │
2605 └─────────────────┘
2606 ```
2607
2608 **Key Changes**:
2609 - **Stringer Support**: `WithStringer(fn any)` sets a table-wide string conversion function. This function must have a signature like `func(SomeType) []string` or `func(any) []string`. It's used to convert an input item (e.g., a struct) into a slice of strings, where each string is a cell for the row (`tablewriter.go:WithStringer`).
2610 - **Caching**: `WithStringerCache()` enables caching for the function provided via `WithStringer`, improving performance for repeated conversions of the same input type (`tablewriter.go:WithStringerCache`).
2611 - **Formatter**: `tw.Formatter` interface (`Format() string`) allows types to define their own single-string representation for a cell. This is checked before `fmt.Stringer` (`tw/types.go:Formatter`).
2612 - **Priority**: When converting an item to cell(s):
2613 1. `WithStringer` (if provided and compatible with the item's type).
2614 2. If not handled by `WithStringer`, or if `WithStringer` is not set:
2615 * If the item is a struct that does *not* implement `tw.Formatter` or `fmt.Stringer`, its exported fields are reflected into multiple cells.
2616 * If the item (or struct) implements `tw.Formatter` (`Format() string`), that's used for a single cell.
2617 * Else, if it implements `fmt.Stringer` (`String() string`), that's used for a single cell.
2618 * Else, default `fmt.Sprintf("%v", ...)` for a single cell.
2619 (`zoo.go:convertCellsToStrings`, `zoo.go:convertItemToCells`)
2620
2621 **Migration Tips**:
2622 - For types that should produce a single cell with custom formatting, implement `tw.Formatter`.
2623 - For types (especially structs) that should be expanded into multiple cells with custom logic, use `WithStringer` with a function like `func(MyType) []string`.
2624 - If you have a general way to convert *any* type into a set of cells, use `WithStringer(func(any) []string)`.
2625 - Enable `WithStringerCache` for large datasets with repetitive data types if using `WithStringer`.
2626 - Test stringer/formatter output to ensure formatting meets expectations (`zoo.go`).
2627
2628 **Potential Pitfalls**:
2629 - **Cache Overhead**: `WithStringerCache` may increase memory usage for diverse data; disable for small tables or if not using `WithStringer` (`tablewriter.go`).
2630 - **Stringer Signature**: The function passed to `WithStringer` *must* return `[]string`. A function returning `string` will lead to a warning and fallback behavior.
2631 - **Formatter vs. Stringer Priority**: Be aware of the conversion priority if your types implement multiple interfaces or if you also use `WithStringer`.
2632 - **Streaming**: Stringers/Formatters must produce consistent cell counts in streaming mode to maintain width alignment (`stream.go`).
2633
2634 ## Examples
2635
2636 This section provides practical examples to demonstrate v1.0.x features, covering common and advanced use cases to aid migration. Each example includes code, output, and notes to illustrate functionality.
2637
2638 ### Example: Minimal Setup
2639 A basic table with default settings, ideal for quick setups.
2640
2641 ```go
2642 package main
2643
2644 import (
2645 "github.com/olekukonko/tablewriter"
2646 "os"
2647 )
2648
2649 func main() {
2650 table := tablewriter.NewTable(os.Stdout)
2651 table.Header("Name", "Status")
2652 table.Append("Node1", "Ready")
2653 table.Render()
2654 }
2655 ```
2656
2657 **Output**:
2658 ```
2659 ┌───────┬────────┐
2660 │ NAME │ STATUS │
2661 ├───────┼────────┤
2662 │ Node1 │ Ready │
2663 └───────┴────────┘
2664 ```
2665
2666 **Notes**:
2667 - Uses default `renderer.NewBlueprint()` and `defaultConfig()` settings (`tablewriter.go`, `config.go`).
2668 - `Header: tw.AlignCenter`, `Row: tw.AlignLeft` (`config.go:defaultConfig`).
2669 - Simple replacement for v0.0.5’s `NewWriter` and `SetHeader`/`Append`.
2670
2671 ### Example: Streaming with Fixed Widths
2672 Demonstrates streaming mode for real-time data output.
2673
2674 ```go
2675 package main
2676
2677 import (
2678 "fmt"
2679 "github.com/olekukonko/tablewriter"
2680 "github.com/olekukonko/tablewriter/tw"
2681 "log"
2682 "os"
2683 )
2684
2685 func main() {
2686 table := tablewriter.NewTable(os.Stdout,
2687 tablewriter.WithStreaming(tw.StreamConfig{Enable: true}),
2688 tablewriter.WithColumnMax(10), // Sets Config.Widths.Global
2689 )
2690 if err := table.Start(); err != nil {
2691 log.Fatalf("Start failed: %v", err)
2692 }
2693 table.Header("Name", "Status")
2694 for i := 0; i < 2; i++ {
2695 err := table.Append(fmt.Sprintf("Node%d", i+1), "Ready")
2696 if err != nil {
2697 log.Printf("Append failed: %v", err)
2698 }
2699 }
2700 if err := table.Close(); err != nil {
2701 log.Fatalf("Close failed: %v", err)
2702 }
2703 }
2704 ```
2705
2706 **Output**:
2707 ```
2708 ┌──────────┬──────────┐
2709 │ NAME │ STATUS │
2710 ├──────────┼──────────┤
2711 │ Node1 │ Ready │
2712 │ Node2 │ Ready │
2713 └──────────┴──────────┘
2714 ```
2715
2716 **Notes**:
2717 - Streaming requires `Start()` and `Close()`; `Config.Widths` (here set via `WithColumnMax`) fixes widths (`stream.go`).
2718 - Replaces v0.0.5’s batch rendering for real-time use cases.
2719 - Ensure error handling for `Start()`, `Append()`, and `Close()`.
2720
2721 ### Example: Markdown-Style Table
2722 Creates a Markdown-compatible table for documentation.
2723
2724 ```go
2725 package main
2726
2727 import (
2728 "fmt"
2729 "github.com/olekukonko/tablewriter"
2730 "github.com/olekukonko/tablewriter/renderer" // Import renderer
2731 "github.com/olekukonko/tablewriter/tw"
2732 "os"
2733 )
2734
2735 func main() {
2736 // Example 1: Using Blueprint renderer with Markdown symbols
2737 tableBlueprintMarkdown := tablewriter.NewTable(os.Stdout,
2738 tablewriter.WithRenderer(renderer.NewBlueprint()), // Use Blueprint
2739 tablewriter.WithRendition(tw.Rendition{
2740 Symbols: tw.NewSymbols(tw.StyleMarkdown),
2741 Borders: tw.Border{Left: tw.On, Right: tw.On}, // Markdown needs left/right borders
2742 }),
2743 tablewriter.WithRowAlignment(tw.AlignLeft), // Common for Markdown
2744 tablewriter.WithHeaderAlignment(tw.AlignCenter), // Center align headers
2745 )
2746 tableBlueprintMarkdown.Header("Name", "Status")
2747 tableBlueprintMarkdown.Append("Node1", "Ready")
2748 tableBlueprintMarkdown.Append("Node2", "NotReady")
2749 tableBlueprintMarkdown.Render()
2750
2751 fmt.Println("\n--- Using dedicated Markdown Renderer (if one exists or is built) ---")
2752 // Example 2: Assuming a dedicated Markdown renderer (hypothetical example)
2753 // If a `renderer.NewMarkdown()` existed that directly outputs GitHub Flavored Markdown table syntax:
2754 /*
2755 tableDedicatedMarkdown := tablewriter.NewTable(os.Stdout,
2756 tablewriter.WithRenderer(renderer.NewMarkdown()), // Hypothetical Markdown renderer
2757 )
2758 tableDedicatedMarkdown.Header("Name", "Status")
2759 tableDedicatedMarkdown.Append("Node1", "Ready")
2760 tableDedicatedMarkdown.Append("Node2", "NotReady")
2761 tableDedicatedMarkdown.Render()
2762 */
2763 // Since `renderer.NewMarkdown()` isn't shown in the provided code,
2764 // the first example (Blueprint with StyleMarkdown) is the current viable way.
2765 }
2766 ```
2767
2768 **Output (Blueprint with StyleMarkdown):**
2769 ```
2770 | NAME | STATUS |
2771 |--------|----------|
2772 | Node1 | Ready |
2773 | Node2 | NotReady |
2774 ```
2775
2776 **Notes**:
2777 - `StyleMarkdown` ensures compatibility with Markdown parsers (`tw/symbols.go`).
2778 - Left alignment for rows and center for headers is common for Markdown readability (`config.go`).
2779 - Ideal for GitHub READMEs or documentation.
2780 - A dedicated Markdown renderer (like the commented-out example) would typically handle alignment syntax (e.g., `|:---:|:---|`). With `Blueprint` and `StyleMarkdown`, alignment is visual within the text rather than Markdown syntax.
2781
2782 ### Example: ASCII-Style Table
2783 Uses `StyleASCII` for maximum terminal compatibility.
2784
2785 ```go
2786 package main
2787
2788 import (
2789 "github.com/olekukonko/tablewriter"
2790 "github.com/olekukonko/tablewriter/renderer"
2791 "github.com/olekukonko/tablewriter/tw"
2792 "os"
2793 )
2794
2795 func main() {
2796 table := tablewriter.NewTable(os.Stdout,
2797 tablewriter.WithRenderer(renderer.NewBlueprint()),
2798 tablewriter.WithRendition(tw.Rendition{
2799 Symbols: tw.NewSymbols(tw.StyleASCII),
2800 }),
2801 tablewriter.WithRowAlignment(tw.AlignLeft),
2802 )
2803 table.Header("ID", "Value")
2804 table.Append("1", "Test")
2805 table.Render()
2806 }
2807 ```
2808
2809 **Output**:
2810 ```
2811 +----+-------+
2812 │ ID │ VALUE │
2813 +----+-------+
2814 │ 1 │ Test │
2815 +----+-------+
2816 ```
2817
2818 **Notes**:
2819 - `StyleASCII` is robust for all terminals (`tw/symbols.go`).
2820 - Replaces v0.0.5’s default style with explicit configuration.
2821
2822
2823 ### Example: Kubectl-Style Output
2824 Creates a borderless, minimal table similar to `kubectl` command output, emphasizing simplicity and readability.
2825
2826 ```go
2827 package main
2828
2829 import (
2830 "os"
2831 "sync"
2832 "github.com/olekukonko/tablewriter"
2833 "github.com/olekukonko/tablewriter/renderer"
2834 "github.com/olekukonko/tablewriter/tw"
2835 )
2836
2837 var wg sync.WaitGroup
2838
2839 func main() {
2840 data := [][]any{
2841 {"node1.example.com", "Ready", "compute", "1.11"},
2842 {"node2.example.com", "Ready", "compute", "1.11"},
2843 {"node3.example.com", "Ready", "compute", "1.11"},
2844 {"node4.example.com", "NotReady", "compute", "1.11"},
2845 }
2846
2847 table := tablewriter.NewTable(os.Stdout,
2848 tablewriter.WithRenderer(renderer.NewBlueprint(tw.Rendition{
2849 Borders: tw.BorderNone,
2850 Settings: tw.Settings{
2851 Separators: tw.SeparatorsNone,
2852 Lines: tw.LinesNone,
2853 },
2854 })),
2855 tablewriter.WithConfig(tablewriter.Config{
2856 Header: tw.CellConfig{
2857 Formatting: tw.CellFormatting{Alignment: tw.AlignLeft},
2858 },
2859 Row: tw.CellConfig{
2860 Formatting: tw.CellFormatting{Alignment: tw.AlignLeft},
2861 Padding: tw.CellPadding{Global: tw.PaddingNone},
2862 },
2863 }),
2864 )
2865 table.Header("Name", "Status", "Role", "Version")
2866 table.Bulk(data)
2867 table.Render()
2868 }
2869 ```
2870
2871 **Output:**
2872 ```
2873 NAME STATUS ROLE VERSION
2874 node1.example.com Ready compute 1.21.3
2875 node2.example.com Ready infra 1.21.3
2876 node3.example.com NotReady compute 1.20.7
2877 ```
2878
2879 **Notes**:
2880 - **Configuration**: Uses `tw.BorderNone`, `tw.LinesNone`, `tw.SeparatorsNone`, `tw.NewSymbols(tw.StyleNone)` and specific padding (`Padding{Right:" "}`) for a minimal, borderless layout.
2881 - **Migration from v0.0.5**: Replaces `SetBorder(false)` and manual spacing with `tw.Rendition` and `Config` settings, achieving a cleaner kubectl-like output.
2882 - **Key Features**:
2883 - Left-aligned text for readability (`config.go`).
2884 - `WithTrimSpace(tw.Off)` preserves spacing (`config.go`).
2885 - `Bulk` efficiently adds multiple rows (`tablewriter.go`).
2886 - Padding `Right: " "` is used to create space between columns as separators are off.
2887 - **Best Practices**: Test in terminals to ensure spacing aligns with command-line aesthetics; use `WithDebug(true)` for layout issues (`config.go`).
2888 - **Potential Issues**: Column widths are content-based. For very long content in one column and short in others, it might not look perfectly aligned like fixed-width CLI tools. `Config.Widths` could be used for more control if needed.
2889
2890 ### Example: Hierarchical Merging
2891 Demonstrates hierarchical cell merging for nested data structures, a new feature in v1.0.x.
2892
2893 ```go
2894 package main
2895
2896 import (
2897 "github.com/olekukonko/tablewriter"
2898 "github.com/olekukonko/tablewriter/renderer"
2899 "github.com/olekukonko/tablewriter/tw"
2900 "os"
2901 )
2902
2903 func main() {
2904 data := [][]string{
2905 // Header row is separate
2906 {"table\nwriter", "v0.0.1", "legacy"},
2907 {"table\nwriter", "v0.0.2", "legacy"},
2908 {"table\nwriter", "v0.0.2", "legacy"}, // Duplicate for testing merge
2909 {"table\nwriter", "v0.0.2", "legacy"}, // Duplicate for testing merge
2910 {"table\nwriter", "v0.0.5", "legacy"},
2911 {"table\nwriter", "v1.0.6", "latest"},
2912 }
2913
2914 rendition := tw.Rendition{
2915 Symbols: tw.NewSymbols(tw.StyleLight), // Use light for clearer merge lines
2916 Settings: tw.Settings{
2917 Separators: tw.Separators{BetweenRows: tw.On},
2918 Lines: tw.Lines{ShowHeaderLine: tw.On, ShowFooterLine: tw.On}, // Show header line
2919 },
2920 Borders: tw.Border{Left:tw.On, Right:tw.On, Top:tw.On, Bottom:tw.On},
2921 }
2922
2923 tableHier := tablewriter.NewTable(os.Stdout,
2924 tablewriter.WithRenderer(renderer.NewBlueprint()),
2925 tablewriter.WithRendition(rendition),
2926 tablewriter.WithConfig(tablewriter.Config{
2927 Row: tw.CellConfig{
2928 Formatting: tw.CellFormatting{
2929 MergeMode: tw.MergeHierarchical,
2930 // Alignment: tw.AlignCenter, // Default is Left, often better for hierarchical
2931 AutoWrap: tw.WrapNormal, // Allow wrapping for "table\nwriter"
2932 },
2933 },
2934 }),
2935 )
2936
2937 tableHier.Header("Package", "Version", "Status") // Header
2938 tableHier.Bulk(data) // Bulk data
2939 tableHier.Render()
2940
2941 // --- Vertical Merging Example for Contrast ---
2942 tableVert := tablewriter.NewTable(os.Stdout,
2943 tablewriter.WithRenderer(renderer.NewBlueprint()),
2944 tablewriter.WithRendition(rendition), // Reuse same rendition
2945 tablewriter.WithConfig(tablewriter.Config{
2946 Row: tw.CellConfig{
2947 Formatting: tw.CellFormatting{
2948 MergeMode: tw.MergeVertical,
2949 AutoWrap: tw.WrapNormal,
2950 },
2951 },
2952 }),
2953 )
2954 tableVert.Header("Package", "Version", "Status")
2955 tableVert.Bulk(data)
2956 tableVert.Render()
2957 }
2958 ```
2959
2960 **Output (Hierarchical):**
2961 ```
2962 ┌─────────┬─────────┬────────┐
2963 │ PACKAGE │ VERSION │ STATUS │
2964 ├─────────┼─────────┼────────┤
2965 │ table │ v0.0.1 │ legacy │
2966 │ writer │ │ │
2967 │ ├─────────┼────────┤
2968 │ │ v0.0.2 │ legacy │
2969 │ │ │ │
2970 │ │ │ │
2971 │ │ │ │
2972 │ │ │ │
2973 │ ├─────────┼────────┤
2974 │ │ v0.0.5 │ legacy │
2975 │ ├─────────┼────────┤
2976 │ │ v1.0.6 │ latest │
2977 └─────────┴─────────┴────────┘
2978 ```
2979 **Output (Vertical):**
2980 ```
2981 ┌─────────┬─────────┬────────┐
2982 │ PACKAGE │ VERSION │ STATUS │
2983 ├─────────┼─────────┼────────┤
2984 │ table │ v0.0.1 │ legacy │
2985 │ writer │ │ │
2986 │ ├─────────┤ │
2987 │ │ v0.0.2 │ │
2988 │ │ │ │
2989 │ │ │ │
2990 │ │ │ │
2991 │ │ │ │
2992 │ ├─────────┤ │
2993 │ │ v0.0.5 │ │
2994 │ ├─────────┼────────┤
2995 │ │ v1.0.6 │ latest │
2996 └─────────┴─────────┴────────┘
2997 ```
2998
2999 **Notes**:
3000 - **Configuration**: Uses `tw.MergeHierarchical` to merge cells based on matching values in preceding columns (`tw/tw.go`).
3001 - **Migration from v0.0.5**: Extends `SetAutoMergeCells(true)` (horizontal only) with hierarchical merging for complex data (`tablewriter.go`).
3002 - **Key Features**:
3003 - `StyleLight` for clear visuals (`tw/symbols.go`).
3004 - `Bulk` for efficient data loading (`tablewriter.go`).
3005 - **Best Practices**: Test merging with nested data; use batch mode, as streaming doesn’t support hierarchical merging (`stream.go`).
3006 - **Potential Issues**: Ensure data is sorted appropriately for hierarchical merging to work as expected; mismatches prevent merging (`zoo.go`). `AutoWrap: tw.WrapNormal` helps with multi-line cell content like "table\nwriter".
3007
3008 ### Example: Colorized Table
3009 Applies ANSI colors to highlight status values, replacing v0.0.5’s `SetColumnColor`.
3010
3011 ```go
3012 package main
3013
3014 import (
3015 "github.com/olekukonko/tablewriter"
3016 "github.com/olekukonko/tablewriter/tw" // For tw.State, tw.CellConfig etc.
3017 "os"
3018 )
3019
3020 func main() {
3021 const (
3022 FgGreen = "\033[32m"
3023 FgRed = "\033[31m"
3024 Reset = "\033[0m"
3025 )
3026
3027 cfgBuilder := tablewriter.NewConfigBuilder()
3028 cfgBuilder.Row().Filter().WithPerColumn([]func(string) string{
3029 nil, // No filter for Name
3030 func(s string) string { // Color Status
3031 if s == "Ready" {
3032 return FgGreen + s + Reset
3033 }
3034 return FgRed + s + Reset
3035 },
3036 })
3037
3038 table := tablewriter.NewTable(os.Stdout, tablewriter.WithConfig(cfgBuilder.Build()))
3039 table.Header("Name", "Status")
3040 table.Append("Node1", "Ready")
3041 table.Append("Node2", "Error")
3042 table.Render()
3043 }
3044 ```
3045
3046 **Output (Text Approximation, Colors Not Shown):**
3047 ```
3048 ┌───────┬────────┐
3049 │ NAME │ STATUS │
3050 ├───────┼────────┤
3051 │ Node1 │ Ready │
3052 │ Node2 │ Error │
3053 └───────┴────────┘
3054 ```
3055
3056 **Notes**:
3057 - **Configuration**: Uses `tw.CellFilter` for per-column coloring, embedding ANSI codes (`tw/cell.go`).
3058 - **Migration from v0.0.5**: Replaces `SetColumnColor` with dynamic filters (`tablewriter.go`).
3059 - **Key Features**: Flexible color application; `twdw.Width` handles ANSI codes correctly (`tw/fn.go`).
3060 - **Best Practices**: Test in ANSI-compatible terminals; use constants for code clarity.
3061 - **Potential Issues**: Non-ANSI terminals may show artifacts; provide fallbacks (`tw/fn.go`).
3062
3063 ### Example: Vertical Merging
3064 Shows vertical cell merging for repeated values in a column. (This example was very similar to the hierarchical one, so I'll ensure it's distinct by using simpler data).
3065
3066 ```go
3067 package main
3068
3069 import (
3070 "github.com/olekukonko/tablewriter"
3071 "github.com/olekukonko/tablewriter/renderer"
3072 "github.com/olekukonko/tablewriter/tw"
3073 "os"
3074 )
3075
3076 func main() {
3077 table := tablewriter.NewTable(os.Stdout,
3078 tablewriter.WithRenderer(renderer.NewBlueprint()), // Default renderer
3079 tablewriter.WithRendition(tw.Rendition{
3080 Symbols: tw.NewSymbols(tw.StyleLight),
3081 Settings: tw.Settings{Separators: tw.Separators{BetweenRows: tw.On}},
3082 Borders: tw.Border{Left:tw.On, Right:tw.On, Top:tw.On, Bottom:tw.On},
3083 }),
3084 tablewriter.WithConfig(
3085 tablewriter.NewConfigBuilder().
3086 Row().Formatting().WithMergeMode(tw.MergeVertical).Build(). // Enable Vertical Merge
3087 Build(),
3088 ),
3089 )
3090 table.Header("User", "Permission", "Target")
3091 table.Append("Alice", "Read", "FileA")
3092 table.Append("Alice", "Write", "FileA") // Alice and FileA will merge vertically
3093 table.Append("Alice", "Read", "FileB")
3094 table.Append("Bob", "Read", "FileA")
3095 table.Append("Bob", "Read", "FileC") // Bob and Read will merge
3096 table.Render()
3097 }
3098 ```
3099
3100 **Output:**
3101 ```
3102 ┌───────┬────────────┬────────┐
3103 │ USER │ PERMISSION │ TARGET │
3104 ├───────┼────────────┼────────┤
3105 │ Alice │ Read │ FileA │
3106 │ │ │ │
3107 │ ├────────────┤ │
3108 │ │ Write │ │
3109 │ ├────────────┼────────┤
3110 │ │ Read │ FileB │
3111 ├───────┼────────────┼────────┤
3112 │ Bob │ Read │ FileA │
3113 │ │ ├────────┤
3114 │ │ │ FileC │
3115 └───────┴────────────┴────────┘
3116 ```
3117
3118 **Notes**:
3119 - **Configuration**: `tw.MergeVertical` merges identical cells vertically (`tw/tw.go`).
3120 - **Migration from v0.0.5**: Extends `SetAutoMergeCells` with vertical merging (`tablewriter.go`).
3121 - **Key Features**: Enhances grouped data display; requires batch mode (`stream.go`).
3122 - **Best Practices**: Sort data by the columns you intend to merge for best results; test with `StyleLight` for clarity (`tw/symbols.go`).
3123 - **Potential Issues**: Streaming doesn’t support vertical merging; use batch mode (`stream.go`).
3124
3125 ### Example: Custom Renderer (CSV Output)
3126 Implements a custom renderer for CSV output.
3127
3128 ```go
3129 package main
3130
3131 import (
3132 "fmt"
3133 "github.com/olekukonko/ll" // For logger type
3134 "github.com/olekukonko/tablewriter"
3135 "github.com/olekukonko/tablewriter/tw"
3136 "io"
3137 "os"
3138 "strings" // For CSV escaping
3139 )
3140
3141 // CSVRenderer implements tw.Renderer
3142 type CSVRenderer struct {
3143 writer io.Writer
3144 config tw.Rendition // Store the rendition
3145 logger *ll.Logger
3146 err error
3147 }
3148
3149 func (r *CSVRenderer) Start(w io.Writer) error {
3150 r.writer = w
3151 return nil // No initial output for CSV typically
3152 }
3153
3154 func (r *CSVRenderer) escapeCSVCell(data string) string {
3155 // Basic CSV escaping: double quotes if it contains comma, newline, or quote
3156 if strings.ContainsAny(data, ",\"\n") {
3157 return `"` + strings.ReplaceAll(data, `"`, `""`) + `"`
3158 }
3159 return data
3160 }
3161
3162 func (r *CSVRenderer) writeLine(cells map[int]tw.CellContext, numCols int) {
3163 if r.err != nil { return }
3164 var lineParts []string
3165 // Need to iterate in column order for CSV
3166 keys := make([]int, 0, len(cells))
3167 for k := range cells {
3168 keys = append(keys, k)
3169 }
3170 // This simple sort works for int keys 0,1,2...
3171 // For more complex scenarios, a proper sort might be needed if keys aren't sequential.
3172 for i := 0; i < numCols; i++ { // Assume numCols reflects the intended max columns
3173 if cellCtx, ok := cells[i]; ok {
3174 lineParts = append(lineParts, r.escapeCSVCell(cellCtx.Data))
3175 } else {
3176 lineParts = append(lineParts, "") // Empty cell if not present
3177 }
3178 }
3179 _, r.err = r.writer.Write([]byte(strings.Join(lineParts, ",") + "\n"))
3180 }
3181
3182
3183 func (r *CSVRenderer) Header(headers [][]string, ctx tw.Formatting) {
3184 // For CSV, usually only the first line of headers is relevant
3185 // The ctx.Row.Current will contain the cells for the first line of the header being processed
3186 r.writeLine(ctx.Row.Current, len(ctx.Row.Current))
3187 }
3188
3189 func (r *CSVRenderer) Row(row []string, ctx tw.Formatting) {
3190 // ctx.Row.Current contains the cells for the current row line
3191 r.writeLine(ctx.Row.Current, len(ctx.Row.Current))
3192 }
3193
3194 func (r *CSVRenderer) Footer(footers [][]string, ctx tw.Formatting) {
3195 // Similar to Header/Row, using ctx.Row.Current for the footer line data
3196 r.writeLine(ctx.Row.Current, len(ctx.Row.Current))
3197 }
3198
3199 func (r *CSVRenderer) Line(ctx tw.Formatting) { /* No separator lines in CSV */ }
3200
3201 func (r *CSVRenderer) Close() error { return r.err }
3202
3203 func (r *CSVRenderer) Config() tw.Rendition { return r.config }
3204 func (r *CSVRenderer) Logger(logger *ll.Logger) { r.logger = logger }
3205
3206 func main() {
3207 table := tablewriter.NewTable(os.Stdout, tablewriter.WithRenderer(&CSVRenderer{
3208 // config can be minimal for CSV as symbols/borders aren't used
3209 config: tw.Rendition{},
3210 }))
3211 table.Header("Name", "Status", "Notes, with comma")
3212 table.Append("Node1", "Ready", "All systems \"go\"!")
3213 table.Append("Node2", "Error", "Needs\nattention")
3214 table.Footer("Summary", "2 Nodes", "Check logs")
3215 table.Render()
3216 }
3217 ```
3218
3219 **Output:**
3220 ```csv
3221 Name,Status,"Notes, with comma"
3222 Node1,Ready,"All systems ""go""!"
3223 Node2,Error,"Needs
3224 attention"
3225 Summary,2 Nodes,Check logs
3226 ```
3227
3228 **Notes**:
3229 - **Configuration**: Custom `CSVRenderer` implements `tw.Renderer` for CSV output (`tw/renderer.go`).
3230 - **Migration from v0.0.5**: Extends v0.0.5’s text-only output with custom formats (`tablewriter.go`).
3231 - **Key Features**: Handles basic CSV cell escaping; supports streaming if `Append` is called multiple times. `ctx.Row.Current` (map[int]tw.CellContext) is used to access cell data.
3232 - **Best Practices**: Test with complex data (e.g., commas, quotes, newlines); implement all renderer methods. A more robust CSV renderer would use the `encoding/csv` package.
3233 - **Potential Issues**: Custom renderers require careful error handling and correct interpretation of `tw.Formatting` and `tw.RowContext`. This example's `writeLine` assumes columns are 0-indexed and contiguous for simplicity.
3234
3235 ## Troubleshooting and Common Pitfalls
3236
3237 This section addresses common migration issues with detailed solutions, covering 30+ scenarios to reduce support tickets.
3238
3239 | Issue | Cause/Solution |
3240 |-------------------------------------------|-------------------------------------------------------------------------------|
3241 | No output from `Render()` | **Cause**: Missing `Start()`/`Close()` in streaming mode or invalid `io.Writer`. **Solution**: Ensure `Start()` and `Close()` are called in streaming; verify `io.Writer` (`stream.go`). |
3242 | Incorrect column widths | **Cause**: Missing `Config.Widths` in streaming or content-based sizing. **Solution**: Set `Config.Widths` before `Start()`; use `WithColumnMax` (`stream.go`). |
3243 | Merging not working | **Cause**: Streaming mode or mismatched data. **Solution**: Use batch mode for vertical/hierarchical merging; ensure identical content (`zoo.go`). |
3244 | Alignment ignored | **Cause**: `PerColumn` overrides `Global`. **Solution**: Check `Config.Section.Alignment.PerColumn` settings or `ConfigBuilder` calls (`tw/cell.go`). |
3245 | Padding affects widths | **Cause**: Padding included in `Config.Widths`. **Solution**: Adjust `Config.Widths` to account for `tw.CellPadding` (`zoo.go`). |
3246 | Colors not rendering | **Cause**: Non-ANSI terminal or incorrect codes. **Solution**: Test in ANSI-compatible terminal; use `twdw.Width` (`tw/fn.go`). |
3247 | Caption missing | **Cause**: `Close()` not called in streaming or incorrect `Spot`. **Solution**: Ensure `Close()`; verify `tw.Caption.Spot` (`tablewriter.go`). |
3248 | Filters not applied | **Cause**: Incorrect `PerColumn` indexing or nil filters. **Solution**: Set filters correctly; test with sample data (`tw/cell.go`). |
3249 | Stringer cache overhead | **Cause**: Large datasets with diverse types. **Solution**: Disable `WithStringerCache` for small tables if not using `WithStringer` or if types vary greatly (`tablewriter.go`). |
3250 | Deprecated methods used | **Cause**: Using `WithBorders`, old `tablewriter.Behavior` constants. **Solution**: Migrate to `WithRendition`, `tw.Behavior` struct (`tablewriter.go`, `deprecated.go`). |
3251 | Streaming footer missing | **Cause**: `Close()` not called. **Solution**: Always call `Close()` (`stream.go`). |
3252 | Hierarchical merging fails | **Cause**: Unsorted data or streaming mode. **Solution**: Sort data; use batch mode (`zoo.go`). |
3253 | Custom renderer errors | **Cause**: Incomplete method implementation or misinterpreting `tw.Formatting`. **Solution**: Implement all `tw.Renderer` methods; test thoroughly (`tw/renderer.go`). |
3254 | Width overflow | **Cause**: No `MaxWidth` or wide content. **Solution**: Set `Config.MaxWidth` (`config.go`). |
3255 | Truncated content | **Cause**: Narrow `Config.Widths` or `tw.WrapTruncate`. **Solution**: Widen columns or use `tw.WrapNormal` (`zoo.go`). |
3256 | Debug logs absent | **Cause**: `Debug = false`. **Solution**: Enable `WithDebug(true)` (`config.go`). |
3257 | Alignment mismatch across sections | **Cause**: Different defaults. **Solution**: Set uniform alignment options (e.g., via `ConfigBuilder.<Section>.Alignment()`) (`config.go`). |
3258 | ANSI code artifacts | **Cause**: Non-ANSI terminal. **Solution**: Provide non-colored fallback (`tw/fn.go`). |
3259 | Slow rendering | **Cause**: Complex filters or merging. **Solution**: Optimize logic; limit merging (`zoo.go`). |
3260 | Uneven cell counts | **Cause**: Mismatched rows/headers. **Solution**: Pad with `""` (`zoo.go`). |
3261 | Border inconsistencies | **Cause**: Mismatched `Borders`/`Symbols`. **Solution**: Align settings (`tw/renderer.go`). |
3262 | Streaming width issues | **Cause**: No `Config.Widths`. **Solution**: Set before `Start()` (`stream.go`). |
3263 | Formatter ignored | **Cause**: `WithStringer` might take precedence if compatible. **Solution**: Review conversion priority; `tw.Formatter` is high-priority for single-item-to-single-cell conversion (`zoo.go`). |
3264 | Caption misalignment | **Cause**: Incorrect `Width` or `Align`. **Solution**: Set `tw.Caption.Width`/`Align` (`tablewriter.go`). |
3265 | Per-column padding errors | **Cause**: Incorrect indexing in `Padding.PerColumn`. **Solution**: Verify indices (`tw/cell.go`). |
3266 | Vertical merging in streaming | **Cause**: Unsupported. **Solution**: Use batch mode (`stream.go`). |
3267 | Filter performance | **Cause**: Complex logic. **Solution**: Simplify filters (`zoo.go`). |
3268 | Custom symbols incomplete | **Cause**: Missing characters. **Solution**: Define all symbols (`tw/symbols.go`). |
3269 | Table too wide | **Cause**: No `MaxWidth`. **Solution**: Set `Config.MaxWidth` (`config.go`). |
3270 | Streaming errors | **Cause**: Missing `Start()`. **Solution**: Call `Start()` before data input (`stream.go`). |
3271
3272 ## Additional Notes
3273
3274 - **Performance Optimization**: Enable `WithStringerCache` for repetitive data types when using `WithStringer`; optimize filters and merging for large datasets (`tablewriter.go`, `zoo.go`).
3275 - **Debugging**: Use `WithDebug(true)` and `table.Debug()` to log configuration and rendering details; invaluable for troubleshooting (`config.go`).
3276 - **Testing Resources**: The `tests/` directory contains examples of various configurations.
3277 - **Community Support**: For advanced use cases or issues, consult the source code or open an issue on the `tablewriter` repository.
3278 - **Future Considerations**: Deprecated methods in `deprecated.go` (e.g., `WithBorders`) are slated for removal in future releases; migrate promptly to ensure compatibility.
3279
3280 This guide aims to cover all migration scenarios comprehensively. For highly specific or advanced use cases, refer to the source files (`config.go`, `tablewriter.go`, `stream.go`, `tw/*`) or engage with the `tablewriter` community for support.