Files
dataxl/cmd/dataxl/conversion.go
T
agent 60a43a42e5
CI / test (pull_request) Failing after 1m6s
Add Markdown table format support
2026-09-05 16:45:44 +09:00

82 lines
1.9 KiB
Go

package main
import (
"fmt"
"path/filepath"
"strings"
)
// convert routes data through either the structured-value or table internal
// representation. Keeping this matrix in one place makes format adapters
// independent from CLI and file I/O concerns.
func convert(input []byte, from, to, sheet string, pretty bool) ([]byte, error) {
switch {
case isTabular(from) && isTabular(to):
t, err := parseTable(input, from, sheet)
if err != nil {
return nil, err
}
return encodeTable(t, to, sheet)
case isTabular(from):
t, err := parseTable(input, from, sheet)
if err != nil {
return nil, err
}
records, err := tableToRecords(t)
if err != nil {
return nil, err
}
return encodeStructured(records, to, pretty)
case isTabular(to):
value, err := parseStructured(input, from)
if err != nil {
return nil, err
}
t := valueToTable(value)
if len(t.Header) == 0 && len(t.Rows) > 0 {
return nil, fmt.Errorf("structured value has records but no scalar fields to represent as a table")
}
return encodeTable(t, to, sheet)
default:
value, err := parseStructured(input, from)
if err != nil {
return nil, err
}
return encodeStructured(value, to, pretty)
}
}
func normalizeFormat(format string) string {
format = strings.ToLower(strings.TrimPrefix(strings.TrimSpace(format), "."))
switch format {
case "yml":
return "yaml"
case "md", "mdown", "mkd":
return "markdown"
case "xlsm", "xls":
return "xlsx"
default:
return format
}
}
func inferFormat(path string) string {
if path == "" || path == "-" {
return ""
}
return normalizeFormat(filepath.Ext(path))
}
func validateFormat(format string) error {
switch format {
case "json", "yaml", "toml", "csv", "tsv", "xlsx", "markdown":
return nil
default:
return fmt.Errorf("unsupported format %q", format)
}
}
func isTabular(format string) bool {
return format == "csv" || format == "tsv" || format == "xlsx" || format == "markdown"
}