github.com/getgauge/gauge@v1.6.9/config/formatter.go (about) 1 /*---------------------------------------------------------------- 2 * Copyright (c) ThoughtWorks, Inc. 3 * Licensed under the Apache License, Version 2.0 4 * See LICENSE in the project root for license information. 5 *----------------------------------------------------------------*/ 6 7 package config 8 9 import ( 10 "encoding/json" 11 "fmt" 12 "sort" 13 "strings" 14 ) 15 16 type Formatter interface { 17 Format([]Property) (string, error) 18 } 19 20 type JsonFormatter struct { 21 } 22 23 func (f JsonFormatter) Format(p []Property) (string, error) { 24 sort.Sort(byPropertyKey(p)) 25 bytes, err := json.MarshalIndent(p, "", "\t") 26 return string(bytes), err 27 } 28 29 type TextFormatter struct { 30 Headers []string 31 } 32 33 func (f TextFormatter) Format(p []Property) (string, error) { 34 sort.Sort(byPropertyKey(p)) 35 format := "%-30s\t%-35s" 36 var s []string 37 max := 0 38 for _, v := range p { 39 text := fmt.Sprintf(format, v.Key, v.Value) 40 s = append(s, text) 41 if max < len(text) { 42 max = len(text) 43 } 44 } 45 if len(f.Headers) == 0 { 46 f.Headers = []string{"Key", "Value"} 47 } 48 s = append([]string{fmt.Sprintf(format, f.Headers[0], f.Headers[1]), strings.Repeat("-", max)}, s...) 49 return strings.Join(s, "\n"), nil 50 } 51 52 type byPropertyKey []Property 53 54 func (a byPropertyKey) Len() int { return len(a) } 55 func (a byPropertyKey) Swap(i, j int) { a[i], a[j] = a[j], a[i] } 56 func (a byPropertyKey) Less(i, j int) bool { return a[i].Key < a[j].Key }