Refactor conversion pipeline by responsibility
This commit is contained in:
71
cmd/dataxl/conversion.go
Normal file
71
cmd/dataxl/conversion.go
Normal file
@@ -0,0 +1,71 @@
|
||||
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
|
||||
}
|
||||
return encodeStructured(tableToRecords(t), to, pretty)
|
||||
case isTabular(to):
|
||||
value, err := parseStructured(input, from)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return encodeTable(valueToTable(value), 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 "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":
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("unsupported format %q", format)
|
||||
}
|
||||
}
|
||||
|
||||
func isTabular(format string) bool {
|
||||
return format == "csv" || format == "tsv" || format == "xlsx"
|
||||
}
|
||||
Reference in New Issue
Block a user