Debian Codegraph @

tw/types.go

raw
1 // Package tw defines types and constants for table formatting and configuration,
2 // including validation logic for various table properties.
3 package tw
4
5 import (
6 "bytes"
7 "io"
8 "strconv"
9 "strings"
10
11 "github.com/olekukonko/errors"
12 ) // Custom error handling library
13
14 // Position defines where formatting applies in the table (e.g., header, footer, or rows).
15 type Position string
16
17 // Validate checks if the Position is one of the allowed values: Header, Footer, or Row.
18 func (pos Position) Validate() error {
19 switch pos {
20 case Header, Footer, Row:
21 return nil // Valid position
22 }
23 // Return an error for any unrecognized position
24 return errors.New("invalid position")
25 }
26
27 // Filter defines a function type for processing cell content.
28 // It takes a slice of strings (representing cell data) and returns a processed slice.
29 type Filter func([]string) []string
30
31 // Formatter defines an interface for types that can format themselves into a string.
32 // Used for custom formatting of table cell content.
33 type Formatter interface {
34 Format() string // Returns the formatted string representation
35 }
36
37 // Counter defines an interface that combines io.Writer with a method to retrieve a total.
38 // This is used by the WithCounter option to allow for counting lines, bytes, etc.
39 type Counter interface {
40 io.Writer // It must be a writer to be used in io.MultiWriter.
41 Total() int
42 }
43
44 // Align specifies the text alignment within a table cell.
45 type Align string
46
47 // Validate checks if the Align is one of the allowed values: None, Center, Left, or Right.
48 func (a Align) Validate() error {
49 switch a {
50 case AlignNone, AlignCenter, AlignLeft, AlignRight:
51 return nil // Valid alignment
52 }
53 // Return an error for any unrecognized alignment
54 return errors.New("invalid align")
55 }
56
57 type Alignment []Align
58
59 func (a Alignment) String() string {
60 var str strings.Builder
61 for i, a := range a {
62 if i > 0 {
63 str.WriteString("; ")
64 }
65 str.WriteString(strconv.Itoa(i))
66 str.WriteString("=")
67 str.WriteString(string(a))
68 }
69 return str.String()
70 }
71
72 func (a Alignment) Add(aligns ...Align) Alignment {
73 aa := make(Alignment, len(aligns))
74 copy(aa, aligns)
75 return aa
76 }
77
78 func (a Alignment) Set(col int, align Align) Alignment {
79 if col >= 0 && col < len(a) {
80 a[col] = align
81 }
82 return a
83 }
84
85 // Copy creates a new independent copy of the Alignment
86 func (a Alignment) Copy() Alignment {
87 aa := make(Alignment, len(a))
88 copy(aa, a)
89 return aa
90 }
91
92 // Level indicates the vertical position of a line in the table (e.g., header, body, or footer).
93 type Level int
94
95 // Validate checks if the Level is one of the allowed values: Header, Body, or Footer.
96 func (l Level) Validate() error {
97 switch l {
98 case LevelHeader, LevelBody, LevelFooter:
99 return nil // Valid level
100 }
101 // Return an error for any unrecognized level
102 return errors.New("invalid level")
103 }
104
105 // Location specifies the horizontal position of a cell or column within a table row.
106 type Location string
107
108 // Validate checks if the Location is one of the allowed values: First, Middle, or End.
109 func (l Location) Validate() error {
110 switch l {
111 case LocationFirst, LocationMiddle, LocationEnd:
112 return nil // Valid location
113 }
114 // Return an error for any unrecognized location
115 return errors.New("invalid location")
116 }
117
118 type Caption struct {
119 Text string
120 Spot Spot
121 Align Align
122 Width int
123 }
124
125 func (c Caption) WithText(text string) Caption {
126 c.Text = text
127 return c
128 }
129
130 func (c Caption) WithSpot(spot Spot) Caption {
131 c.Spot = spot
132 return c
133 }
134
135 func (c Caption) WithAlign(align Align) Caption {
136 c.Align = align
137 return c
138 }
139
140 func (c Caption) WithWidth(width int) Caption {
141 c.Width = width
142 return c
143 }
144
145 type Control struct {
146 Hide State
147 }
148
149 // Compact configures compact width optimization for merged cells.
150 type Compact struct {
151 Merge State // Merge enables compact width calculation during cell merging, optimizing space allocation.
152 }
153
154 // Struct holds settings for struct-based operations like AutoHeader.
155 type Struct struct {
156 // AutoHeader automatically extracts and sets headers from struct fields when Bulk is called with a slice of structs.
157 // Uses JSON tags if present, falls back to field names (title-cased). Skips unexported or json:"-" fields.
158 // Enabled by default for convenience.
159 AutoHeader State
160
161 // Tags is a priority-ordered list of struct tag keys to check for header names.
162 // The first tag found on a field will be used. Defaults to ["json", "db"].
163 Tags []string
164 }
165
166 // Behavior defines settings that control table rendering behaviors, such as column visibility and content formatting.
167 type Behavior struct {
168 AutoHide State // AutoHide determines whether empty columns are hidden. Ignored in streaming mode.
169 TrimSpace State // TrimSpace determines trimming of leading and trailing spaces from cell content.
170 TrimLine State // TrimLine determines whether empty visual lines within a cell are collapsed.
171 TrimTab State // TrimTab determines trimming of leading and trailing tabs from cell content.
172
173 Header Control // Header specifies control settings for the table header.
174 Footer Control // Footer specifies control settings for the table footer.
175
176 // Compact enables optimized width calculation for merged cells, such as in horizontal merges,
177 // by systematically determining the most efficient width instead of scaling by the number of columns.
178 Compact Compact
179
180 // Structs contains settings for how struct data is processed.
181 Structs Struct
182 }
183
184 // Padding defines the spacing characters around cell content in all four directions.
185 // A zero-value Padding struct will use the table's default padding unless Overwrite is true.
186 type Padding struct {
187 Left string
188 Right string
189 Top string
190 Bottom string
191
192 // Overwrite forces tablewriter to use this padding configuration exactly as specified,
193 // even when empty. When false (default), empty Padding fields will inherit defaults.
194 //
195 // For explicit no-padding, use the PaddingNone constant instead of setting Overwrite.
196 Overwrite bool
197 }
198
199 // Common padding configurations for convenience
200
201 // Equals reports whether two Padding configurations are identical in all fields.
202 // This includes comparing the Overwrite flag as part of the equality check.
203 func (p Padding) Equals(padding Padding) bool {
204 return p.Left == padding.Left &&
205 p.Right == padding.Right &&
206 p.Top == padding.Top &&
207 p.Bottom == padding.Bottom &&
208 p.Overwrite == padding.Overwrite
209 }
210
211 // Empty reports whether all padding strings are empty (all fields == "").
212 // Note that an Empty padding may still take effect if Overwrite is true.
213 func (p Padding) Empty() bool {
214 return p.Left == "" && p.Right == "" && p.Top == "" && p.Bottom == ""
215 }
216
217 // Paddable reports whether this Padding configuration should override existing padding.
218 // Returns true if either:
219 // - Any padding string is non-empty (!p.Empty())
220 // - Overwrite flag is true (even with all strings empty)
221 //
222 // This is used internally during configuration merging to determine whether to
223 // apply the padding settings.
224 func (p Padding) Paddable() bool {
225 return !p.Empty() || p.Overwrite
226 }
227
228 // LineCounter is the default implementation of the Counter interface.
229 // It counts the number of newline characters written to it.
230 type LineCounter struct {
231 count int
232 }
233
234 // Write implements the io.Writer interface, counting newlines in the input.
235 // It uses a pointer receiver to modify the internal count.
236 func (lc *LineCounter) Write(p []byte) (n int, err error) {
237 lc.count += bytes.Count(p, []byte{'\n'})
238 return len(p), nil
239 }
240
241 // Total implements the Counter interface, returning the final count.
242 func (lc *LineCounter) Total() int {
243 return lc.count
244 }