gitlink-cli/internal/output/formatter.go

234 lines
4.9 KiB
Go

package output
import (
"encoding/json"
"fmt"
"io"
"os"
"reflect"
"strings"
"text/tabwriter"
"gopkg.in/yaml.v3"
)
func Print(envelope *Envelope, format string) error {
if format == "" {
format = "json"
}
return PrintTo(os.Stdout, envelope, format)
}
func PrintTo(w io.Writer, envelope *Envelope, format string) error {
switch format {
case "json":
return printJSON(w, envelope)
case "yaml":
return printYAML(w, envelope)
case "table":
return printTable(w, envelope)
default:
return printJSON(w, envelope)
}
}
func printJSON(w io.Writer, envelope *Envelope) error {
data, err := json.MarshalIndent(envelope, "", " ")
if err != nil {
return err
}
_, err = fmt.Fprintln(w, string(data))
return err
}
func printYAML(w io.Writer, envelope *Envelope) error {
data, err := yaml.Marshal(envelope)
if err != nil {
return err
}
_, err = fmt.Fprint(w, string(data))
return err
}
func printTable(w io.Writer, envelope *Envelope) error {
if !envelope.OK {
if envelope.Error != nil {
fmt.Fprintf(w, "Error: %s\n", envelope.Error.Message)
if envelope.Error.Suggestion != "" {
fmt.Fprintf(w, "Suggestion: %s\n", envelope.Error.Suggestion)
}
}
return nil
}
if envelope.Data == nil {
fmt.Fprintln(w, "No data")
return nil
}
// Convert struct types to generic map/slice via JSON round-trip
data := envelope.Data
if _, ok := data.(map[string]interface{}); !ok {
if _, ok := data.([]interface{}); !ok {
generic, err := toGeneric(data)
if err != nil {
return printJSON(w, envelope)
}
data = generic
}
}
switch data := data.(type) {
case []interface{}:
return printSliceTable(w, data)
case map[string]interface{}:
if slice := findSliceInMap(data); slice != nil {
return printSliceTable(w, slice)
}
if hasComplexValues(data) {
return printJSON(w, envelope)
}
return printMapTable(w, data)
default:
return printJSON(w, envelope)
}
}
func toGeneric(v interface{}) (interface{}, error) {
b, err := json.Marshal(v)
if err != nil {
return nil, err
}
var result interface{}
if err := json.Unmarshal(b, &result); err != nil {
return nil, err
}
return result, nil
}
func findSliceInMap(m map[string]interface{}) []interface{} {
for _, key := range []string{
"issues", "pull_requests", "milestones", "webhooks", "issue_tags",
"commits", "files", "members", "collaborators", "users", "branches",
"releases", "entries", "tags", "watchers", "results",
} {
if v, ok := m[key]; ok {
if slice, ok := v.([]interface{}); ok && len(slice) > 0 {
return slice
}
}
}
for _, v := range m {
if slice, ok := v.([]interface{}); ok && len(slice) > 0 {
if _, isMap := slice[0].(map[string]interface{}); isMap {
return slice
}
}
}
return nil
}
func hasComplexValues(m map[string]interface{}) bool {
for _, v := range m {
switch v.(type) {
case map[string]interface{}, []interface{}:
return true
}
}
return false
}
func printSliceTable(w io.Writer, items []interface{}) error {
if len(items) == 0 {
fmt.Fprintln(w, "No results")
return nil
}
first, ok := items[0].(map[string]interface{})
if !ok {
data, _ := json.MarshalIndent(items, "", " ")
fmt.Fprintln(w, string(data))
return nil
}
headers := collectKeys(first)
tw := tabwriter.NewWriter(w, 0, 4, 2, ' ', 0)
fmt.Fprintln(tw, strings.Join(headers, "\t"))
dashes := make([]string, len(headers))
for i, h := range headers {
dashes[i] = strings.Repeat("-", len(h))
}
fmt.Fprintln(tw, strings.Join(dashes, "\t"))
for _, item := range items {
m, ok := item.(map[string]interface{})
if !ok {
continue
}
vals := make([]string, len(headers))
for i, h := range headers {
vals[i] = formatValue(m[h])
}
fmt.Fprintln(tw, strings.Join(vals, "\t"))
}
return tw.Flush()
}
func printMapTable(w io.Writer, m map[string]interface{}) error {
tw := tabwriter.NewWriter(w, 0, 4, 2, ' ', 0)
fmt.Fprintln(tw, "KEY\tVALUE")
fmt.Fprintln(tw, "---\t-----")
for k, v := range m {
fmt.Fprintf(tw, "%s\t%s\n", k, formatValue(v))
}
return tw.Flush()
}
func collectKeys(m map[string]interface{}) []string {
keys := make([]string, 0, len(m))
priority := []string{"id", "name", "login", "title", "status", "state", "created_at", "updated_at"}
seen := map[string]bool{}
for _, k := range priority {
if _, ok := m[k]; ok {
keys = append(keys, k)
seen[k] = true
}
}
for k := range m {
if !seen[k] {
keys = append(keys, k)
}
}
return keys
}
func formatValue(v interface{}) string {
if v == nil {
return ""
}
rv := reflect.ValueOf(v)
switch rv.Kind() {
case reflect.Map, reflect.Slice:
data, _ := json.Marshal(v)
s := string(data)
if len(s) > 50 {
return s[:47] + "..."
}
return s
case reflect.Bool:
if v.(bool) {
return "yes"
}
return "no"
case reflect.Float64:
f := v.(float64)
if f == float64(int64(f)) {
return fmt.Sprintf("%d", int64(f))
}
return fmt.Sprintf("%v", v)
default:
return fmt.Sprintf("%v", v)
}
}