streamline table api (#101)

This commit is contained in:
T. von Dein
2026-08-09 21:53:47 +02:00
parent 59331fc721
commit 325433ed81
30 changed files with 349 additions and 316 deletions

View File

@@ -1,3 +1,5 @@
package printer
/*
Copyright © 2026 Thomas von Dein
@@ -14,7 +16,6 @@ GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package printer
import (
"fmt"
@@ -25,9 +26,11 @@ import (
"github.com/elastic/go-elasticsearch/v9/typedapi/types"
)
func any2string(in any) string {
// stringer returns the string representation of different types of
// values
func stringer(cell any) string {
//nolint:gocritic
switch val := in.(type) {
switch val := cell.(type) {
case string:
return val
case bool:
@@ -54,52 +57,27 @@ func any2string(in any) string {
return string(val)
case nil:
return "null"
case types.Percentage, types.DateTime:
return val.(string)
}
case *types.Float64:
// ignore err here, because types.Float64.MarshalJSON() never returns one
f, _ := val.MarshalJSON()
return ""
return string(f)
default:
// Caution: this may cause a panic if the [unknown] type does
// not implement fmt.Stringer. In this case add another case
// to the type switch for it above.
return cell.(fmt.Stringer).String()
}
}
func (data *Table) preprocessRows() {
if data.processed {
// only do it once
return
// visibleLen returns the length of a string but only visible chars,
// w/o ansi color escapes
func visibleLen(word string) int {
if !strings.Contains(word, "\x1b") {
// no ansi escape in there, use faster method
return len(word)
}
// convert entries to strings
data.rows = make([][]string, len(data.Entries))
for rowidx, entries := range data.Entries {
data.rows[rowidx] = make([]string, len(entries))
for colidx, entry := range data.Entries[rowidx] {
data.rows[rowidx][colidx] = any2string(entry)
}
}
// determine header lenght's
for idx, head := range data.Headers {
data.lenHeaders[idx] = visibleLen(head)
}
// determine max width per column
for _, entries := range data.rows {
currentWidth := 0
for idx, entry := range entries {
length := visibleLen(entry)
if data.lenHeaders[idx] < length {
if length > currentWidth+data.maxwidth {
data.lenHeaders[idx] = data.maxwidth - currentWidth
} else {
data.lenHeaders[idx] = length
}
}
currentWidth += data.lenHeaders[idx]
}
}
data.processed = true
// contains escapes, need to clean up before counting
return len(ansiCtrlSeq.ReplaceAllLiteralString(word, ""))
}