| 1 |
package tablewriter |
| 2 |
|
| 3 |
import ( |
| 4 |
"reflect" |
| 5 |
"strconv" |
| 6 |
"strings" |
| 7 |
|
| 8 |
"github.com/olekukonko/tablewriter/tw" |
| 9 |
) |
| 10 |
|
| 11 |
// Recognized keys for the `tw` struct tag. Centralizing them here means the |
| 12 |
// parser switch, and anything that documents or tests the tag vocabulary, |
| 13 |
// all refer back to one definition instead of duplicating string literals. |
| 14 |
// |
| 15 |
// Note: Go struct tags are raw string literals, so a tag written on a field |
| 16 |
// (e.g. `tw:"align=left"`) can never reference these constants directly — |
| 17 |
// that part of the duplication is a language limitation, not a design |
| 18 |
// choice. What these constants buy us is refactor-safety on the parsing |
| 19 |
// side: renaming a key is a one-line change instead of a grep-and-pray. |
| 20 |
const ( |
| 21 |
twTagSkip = "-" // valid as the entire tag, or as a bare key/part |
| 22 |
|
| 23 |
twKeyName = "name" |
| 24 |
twKeyAlign = "align" |
| 25 |
twKeyHeaderAlign = "header_align" |
| 26 |
twKeyMaxWidth = "max_width" |
| 27 |
twKeyPadLeft = "pad_left" |
| 28 |
twKeyPadRight = "pad_right" |
| 29 |
twKeyTrimSpace = "trim_space" |
| 30 |
twKeyTrimTab = "trim_tab" |
| 31 |
twKeyAutoFormat = "auto_format" |
| 32 |
twKeyWrap = "wrap" |
| 33 |
) |
| 34 |
|
| 35 |
// extractHeadersFromStruct is a thin wrapper around the unified extraction |
| 36 |
// function below. It only cares about the header names. |
| 37 |
func (t *Table) extractHeadersFromStruct(sample interface{}) []string { |
| 38 |
headers, _ := t.extractFieldsAndValuesFromStruct(sample) |
| 39 |
return headers |
| 40 |
} |
| 41 |
|
| 42 |
// extractFieldsAndValuesFromStruct is the single source of truth for struct |
| 43 |
// reflection. It initiates recursive extraction starting at column offset 0. |
| 44 |
func (t *Table) extractFieldsAndValuesFromStruct(sample interface{}) ([]string, []string) { |
| 45 |
return t.extractFieldsAndValuesFromStructWithOffset(sample, 0) |
| 46 |
} |
| 47 |
|
| 48 |
// extractFieldsAndValuesFromStructWithOffset recursively processes a struct, |
| 49 |
// handling pointers and embedded structs, and natively parses the readable |
| 50 |
// 'tw' struct tag. colOffset is the absolute column index of this struct's |
| 51 |
// first field, used to keep embedded structs' per-column config (alignment, |
| 52 |
// width, padding) addressed correctly within the parent's column layout. |
| 53 |
func (t *Table) extractFieldsAndValuesFromStructWithOffset(sample interface{}, colOffset int) ([]string, []string) { |
| 54 |
v := reflect.ValueOf(sample) |
| 55 |
if v.Kind() == reflect.Ptr { |
| 56 |
if v.IsNil() { |
| 57 |
return nil, nil |
| 58 |
} |
| 59 |
v = v.Elem() |
| 60 |
} |
| 61 |
|
| 62 |
if v.Kind() != reflect.Struct { |
| 63 |
return nil, nil |
| 64 |
} |
| 65 |
|
| 66 |
typ := v.Type() |
| 67 |
headers := make([]string, 0, typ.NumField()) |
| 68 |
values := make([]string, 0, typ.NumField()) |
| 69 |
|
| 70 |
// Apply structural table configuration (alignment, width, padding, ...) |
| 71 |
// only on the first row, to avoid redundant work on every appended row |
| 72 |
// in Bulk(). Field tags are identical across rows of the same struct |
| 73 |
// type, so re-applying them on every row would be wasted reflection and |
| 74 |
// map writes, not a behavior change. |
| 75 |
isFirstPass := len(t.rows) == 0 |
| 76 |
|
| 77 |
for i := 0; i < typ.NumField(); i++ { |
| 78 |
field := typ.Field(i) |
| 79 |
fieldValue := v.Field(i) |
| 80 |
|
| 81 |
// Skip unexported fields |
| 82 |
if field.PkgPath != "" { |
| 83 |
continue |
| 84 |
} |
| 85 |
|
| 86 |
// Handle embedded structs recursively, tracking absolute column offset |
| 87 |
if field.Anonymous { |
| 88 |
h, val := t.extractFieldsAndValuesFromStructWithOffset(fieldValue.Interface(), colOffset+len(headers)) |
| 89 |
if h != nil { |
| 90 |
headers = append(headers, h...) |
| 91 |
values = append(values, val...) |
| 92 |
} |
| 93 |
continue |
| 94 |
} |
| 95 |
|
| 96 |
var legacyTagName string |
| 97 |
skipField := false |
| 98 |
twTag := field.Tag.Get("tw") |
| 99 |
|
| 100 |
// Check legacy priority tags (e.g., json, db) for fallback headers |
| 101 |
for _, tagKey := range t.config.Behavior.Structs.Tags { |
| 102 |
tagValue := field.Tag.Get(tagKey) |
| 103 |
if tagValue != "" { |
| 104 |
if tagValue == "-" { |
| 105 |
skipField = true |
| 106 |
break |
| 107 |
} |
| 108 |
legacyTagName = tagValue |
| 109 |
break |
| 110 |
} |
| 111 |
} |
| 112 |
|
| 113 |
// Determine base header name (Fallback: legacy tag -> field name). |
| 114 |
// Title-case it now, before any 'tw' name= override is applied below. |
| 115 |
// This matters for multi-word Go field names like "KeepMe": titling |
| 116 |
// it here turns it into "KEEPME" (one word, already uppercase), so |
| 117 |
// the render-time AutoFormat pass (which splits camelCase on case |
| 118 |
// transitions to insert spaces) has no lowercase-to-uppercase |
| 119 |
// transition left to find and won't turn it into "KEEP ME". An |
| 120 |
// explicit tw:"name=..." value is taken verbatim instead, after |
| 121 |
// this point, and intentionally skips this step to preserve casing. |
| 122 |
headerName := field.Name |
| 123 |
if legacyTagName != "" { |
| 124 |
headerName = strings.Split(legacyTagName, ",")[0] |
| 125 |
} |
| 126 |
headerName = tw.Title(headerName) |
| 127 |
|
| 128 |
// Absolute column index this field will occupy in the rendered table |
| 129 |
colIdx := colOffset + len(headers) |
| 130 |
|
| 131 |
// Parse the 'tw' struct tag schema |
| 132 |
if twTag != "" { |
| 133 |
if strings.TrimSpace(twTag) == twTagSkip { |
| 134 |
continue |
| 135 |
} |
| 136 |
|
| 137 |
parts := strings.Split(twTag, ",") |
| 138 |
|
| 139 |
// Pass 1: resolve skip first, before any part is allowed to |
| 140 |
// mutate table config. A tag like "align=left,-" must not leave |
| 141 |
// behind an alignment write for colIdx; if this field is going |
| 142 |
// to be dropped, the part that comes before "-" in the tag |
| 143 |
// string shouldn't matter, and a stale config write would leak |
| 144 |
// onto whichever field ends up occupying this column index. |
| 145 |
for _, p := range parts { |
| 146 |
kv := strings.SplitN(p, "=", 2) |
| 147 |
if strings.TrimSpace(kv[0]) == twTagSkip { |
| 148 |
skipField = true |
| 149 |
break |
| 150 |
} |
| 151 |
} |
| 152 |
|
| 153 |
// Pass 2: only now apply side effects, and only if the field |
| 154 |
// survived pass 1. |
| 155 |
if !skipField { |
| 156 |
for _, p := range parts { |
| 157 |
kv := strings.SplitN(p, "=", 2) |
| 158 |
key := strings.TrimSpace(kv[0]) |
| 159 |
|
| 160 |
if len(kv) != 2 { |
| 161 |
continue |
| 162 |
} |
| 163 |
|
| 164 |
val := kv[1] // Do not TrimSpace val yet, to preserve padding spaces |
| 165 |
valTrimmed := strings.TrimSpace(val) |
| 166 |
|
| 167 |
switch key { |
| 168 |
case twKeyName: |
| 169 |
headerName = val // Use exact string, preserve casing |
| 170 |
|
| 171 |
// Per-Column Configurations |
| 172 |
case twKeyAlign: |
| 173 |
if isFirstPass { |
| 174 |
align := t.parseTwAlign(valTrimmed) |
| 175 |
t.setTwColumnAlignment(tw.Row, colIdx, align) |
| 176 |
t.setTwColumnAlignment(tw.Footer, colIdx, align) |
| 177 |
} |
| 178 |
case twKeyHeaderAlign: |
| 179 |
if isFirstPass { |
| 180 |
t.setTwColumnAlignment(tw.Header, colIdx, t.parseTwAlign(valTrimmed)) |
| 181 |
} |
| 182 |
case twKeyMaxWidth: |
| 183 |
if isFirstPass { |
| 184 |
if mw, err := strconv.Atoi(valTrimmed); err == nil && mw > 0 { |
| 185 |
t.setTwColumnMaxWidth(colIdx, mw) |
| 186 |
} |
| 187 |
} |
| 188 |
case twKeyPadLeft: |
| 189 |
if isFirstPass { |
| 190 |
t.setTwColumnPadding(colIdx, val, true) |
| 191 |
} |
| 192 |
case twKeyPadRight: |
| 193 |
if isFirstPass { |
| 194 |
t.setTwColumnPadding(colIdx, val, false) |
| 195 |
} |
| 196 |
|
| 197 |
// Table-wide configurations. These cannot be scoped to a |
| 198 |
// single column: TrimSpace/TrimTab are a single flag on |
| 199 |
// t.config.Behavior used for every cell in the table |
| 200 |
// (header, row and footer alike), and Header.Formatting |
| 201 |
// .AutoFormat is one flag per section, not a per-column |
| 202 |
// array like Alignment.PerColumn is. Setting one of |
| 203 |
// these on a field changes that behavior for every |
| 204 |
// other column too, including ones processed earlier. |
| 205 |
// Whichever field sets a given key last "wins" for the |
| 206 |
// whole table. If genuinely independent per-column |
| 207 |
// control is needed, these settings don't belong in a |
| 208 |
// per-field tag — that would require making |
| 209 |
// CellFormatting per-column-aware first. |
| 210 |
case twKeyTrimSpace: |
| 211 |
if isFirstPass { |
| 212 |
t.config.Behavior.TrimSpace = t.parseTwState(valTrimmed) |
| 213 |
} |
| 214 |
case twKeyTrimTab: |
| 215 |
if isFirstPass { |
| 216 |
t.config.Behavior.TrimTab = t.parseTwState(valTrimmed) |
| 217 |
} |
| 218 |
case twKeyAutoFormat: |
| 219 |
if isFirstPass { |
| 220 |
t.config.Header.Formatting.AutoFormat = t.parseTwState(valTrimmed) |
| 221 |
} |
| 222 |
case twKeyWrap: |
| 223 |
if isFirstPass { |
| 224 |
switch valTrimmed { |
| 225 |
case "none": |
| 226 |
t.config.Row.Formatting.AutoWrap = tw.WrapNone |
| 227 |
case "normal": |
| 228 |
t.config.Row.Formatting.AutoWrap = tw.WrapNormal |
| 229 |
case "truncate": |
| 230 |
t.config.Row.Formatting.AutoWrap = tw.WrapTruncate |
| 231 |
case "break": |
| 232 |
t.config.Row.Formatting.AutoWrap = tw.WrapBreak |
| 233 |
} |
| 234 |
} |
| 235 |
} |
| 236 |
} |
| 237 |
} |
| 238 |
} |
| 239 |
|
| 240 |
if skipField { |
| 241 |
continue |
| 242 |
} |
| 243 |
|
| 244 |
headers = append(headers, headerName) |
| 245 |
|
| 246 |
// Extract value |
| 247 |
value := "" |
| 248 |
if !strings.Contains(legacyTagName, ",omitempty") || !fieldValue.IsZero() { |
| 249 |
value = t.convertToString(fieldValue.Interface()) |
| 250 |
} |
| 251 |
values = append(values, value) |
| 252 |
} |
| 253 |
|
| 254 |
return headers, values |
| 255 |
} |
| 256 |
|
| 257 |
// Configuration Helper Methods |
| 258 |
|
| 259 |
func (t *Table) parseTwAlign(val string) tw.Align { |
| 260 |
switch strings.ToLower(val) { |
| 261 |
case "center": |
| 262 |
return tw.AlignCenter |
| 263 |
case "left": |
| 264 |
return tw.AlignLeft |
| 265 |
case "right": |
| 266 |
return tw.AlignRight |
| 267 |
default: |
| 268 |
return tw.AlignDefault |
| 269 |
} |
| 270 |
} |
| 271 |
|
| 272 |
func (t *Table) parseTwState(val string) tw.State { |
| 273 |
if strings.ToLower(val) == "true" { |
| 274 |
return tw.On |
| 275 |
} |
| 276 |
return tw.Off |
| 277 |
} |
| 278 |
|
| 279 |
func (t *Table) setTwColumnAlignment(pos tw.Position, colIdx int, align tw.Align) { |
| 280 |
var alignConfig *[]tw.Align |
| 281 |
switch pos { |
| 282 |
case tw.Header: |
| 283 |
alignConfig = &t.config.Header.Alignment.PerColumn |
| 284 |
case tw.Row: |
| 285 |
alignConfig = &t.config.Row.Alignment.PerColumn |
| 286 |
case tw.Footer: |
| 287 |
alignConfig = &t.config.Footer.Alignment.PerColumn |
| 288 |
} |
| 289 |
|
| 290 |
if alignConfig != nil { |
| 291 |
if *alignConfig == nil { |
| 292 |
*alignConfig = make([]tw.Align, colIdx+1) |
| 293 |
} |
| 294 |
for len(*alignConfig) <= colIdx { |
| 295 |
*alignConfig = append(*alignConfig, tw.Skip) |
| 296 |
} |
| 297 |
(*alignConfig)[colIdx] = align |
| 298 |
} |
| 299 |
} |
| 300 |
|
| 301 |
// setTwColumnMaxWidth records a per-column max width for the header, row, |
| 302 |
// and footer sections. This must operate on pointers to the actual config |
| 303 |
// fields, not copies: tw.CellWidth.PerColumn is a map, and on a table that |
| 304 |
// has never had a per-column width set before, that map is nil. Ranging |
| 305 |
// over a []tw.CellWidth of *values* would initialize the map only on a |
| 306 |
// local copy of the struct, which is discarded at the end of the loop body |
| 307 |
// — the real t.config.*.ColMaxWidths.PerColumn would stay nil and the tag |
| 308 |
// would silently do nothing. See setTwColumnPadding below for the same |
| 309 |
// pattern done correctly, which this mirrors. |
| 310 |
func (t *Table) setTwColumnMaxWidth(colIdx, mw int) { |
| 311 |
configs := []*tw.CellWidth{ |
| 312 |
&t.config.Header.ColMaxWidths, |
| 313 |
&t.config.Row.ColMaxWidths, |
| 314 |
&t.config.Footer.ColMaxWidths, |
| 315 |
} |
| 316 |
for _, cfg := range configs { |
| 317 |
if cfg.PerColumn == nil { |
| 318 |
cfg.PerColumn = tw.NewMapper[int, int]() |
| 319 |
} |
| 320 |
cfg.PerColumn.Set(colIdx, mw) |
| 321 |
} |
| 322 |
} |
| 323 |
|
| 324 |
func (t *Table) setTwColumnPadding(colIdx int, padStr string, isLeft bool) { |
| 325 |
configs := []*tw.CellPadding{&t.config.Header.Padding, &t.config.Row.Padding, &t.config.Footer.Padding} |
| 326 |
|
| 327 |
for _, p := range configs { |
| 328 |
if p.PerColumn == nil { |
| 329 |
p.PerColumn = make([]tw.Padding, colIdx+1) |
| 330 |
} |
| 331 |
for len(p.PerColumn) <= colIdx { |
| 332 |
p.PerColumn = append(p.PerColumn, tw.Padding{}) |
| 333 |
} |
| 334 |
|
| 335 |
if isLeft { |
| 336 |
p.PerColumn[colIdx].Left = padStr |
| 337 |
} else { |
| 338 |
p.PerColumn[colIdx].Right = padStr |
| 339 |
} |
| 340 |
p.PerColumn[colIdx].Overwrite = true |
| 341 |
} |
| 342 |
} |