Added CSV to ASCII table
This commit is contained in:
parent
44e4d09c3a
commit
cb9c05a57b
2 changed files with 152 additions and 0 deletions
|
|
@ -5,6 +5,7 @@ import (
|
|||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/csv"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
|
@ -12,6 +13,7 @@ import (
|
|||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"text/template"
|
||||
|
||||
|
|
@ -184,6 +186,64 @@ var TextFilters = map[string]TextProcessor{
|
|||
return TextFilterResponse{Output: dst.String()}, nil
|
||||
},
|
||||
},
|
||||
"csv-to-ascii-table": {
|
||||
Label: "Convert: CSV to ASCII Table",
|
||||
Filter: func(ctx context.Context, input string) (resp TextFilterResponse, err error) {
|
||||
endNL := ""
|
||||
if strings.HasSuffix(input, "\n") {
|
||||
endNL = "\n"
|
||||
}
|
||||
|
||||
reader := csv.NewReader(strings.NewReader(input))
|
||||
reader.FieldsPerRecord = -1
|
||||
records, err := reader.ReadAll()
|
||||
if err != nil {
|
||||
return TextFilterResponse{}, err
|
||||
}
|
||||
if len(records) == 0 {
|
||||
return TextFilterResponse{Output: input}, nil
|
||||
}
|
||||
|
||||
var colWidths []int
|
||||
for _, record := range records {
|
||||
for i, cell := range record {
|
||||
if i >= len(colWidths) {
|
||||
colWidths = append(colWidths, 0)
|
||||
}
|
||||
colWidths[i] = max(colWidths[i], utf8.RuneCountInString(cell))
|
||||
}
|
||||
}
|
||||
|
||||
writeRow := func(dst *strings.Builder, cells []string) {
|
||||
line := make([]string, len(colWidths))
|
||||
for i, width := range colWidths {
|
||||
cell := ""
|
||||
if i < len(cells) {
|
||||
cell = cells[i]
|
||||
}
|
||||
line[i] = cell + strings.Repeat(" ", width-utf8.RuneCountInString(cell))
|
||||
}
|
||||
dst.WriteString(strings.TrimRight(strings.Join(line, " "), " "))
|
||||
dst.WriteString("\n")
|
||||
}
|
||||
|
||||
dashes := make([]string, len(colWidths))
|
||||
for i, width := range colWidths {
|
||||
dashes[i] = strings.Repeat("-", width)
|
||||
}
|
||||
dashLine := strings.Join(dashes, " ") + "\n"
|
||||
|
||||
var dst strings.Builder
|
||||
writeRow(&dst, records[0])
|
||||
dst.WriteString(dashLine)
|
||||
for _, record := range records[1:] {
|
||||
writeRow(&dst, record)
|
||||
}
|
||||
dst.WriteString(dashLine)
|
||||
|
||||
return TextFilterResponse{Output: strings.TrimSuffix(dst.String(), "\n") + endNL}, nil
|
||||
},
|
||||
},
|
||||
"convert-yaml-to-json": {
|
||||
Label: "Convert: YAML to JSON",
|
||||
Filter: func(ctx context.Context, input string) (resp TextFilterResponse, err error) {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue